Platform Admin Manual

Version 2.1 May 27, 2026 — Cleanup Pass

1a. Overview & Architecture

Each church gets a fully isolated GCP tenant. No data is shared between churches.

Resource Per-church name pattern Notes
Cloud Run — Backend koinonia-{id}-api FastAPI, port 8000
Cloud Run — Frontend koinonia-{id}-web Next.js, port 3000
Cloud SQL (PostgreSQL 15) koinonia-{id}-db db-f1-micro by default
GCS Bucket koinoniacloud-490205-{id}-uploads Photos, documents, import ZIPs
Service Account koinonia-{id}-sa Runtime identity for Cloud Run
Secret Manager prefix koinonia-{id}-* All secrets namespaced per church

GCP Project: koinoniacloud-490205
Region: us-central1
Artifact Registry: us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/

The {id} is a short, lowercase, hyphen-safe identifier you choose for each church (e.g. demo, firstbaptist, gracechapel). It appears in all resource names and Cloud Run URLs.

1b. Zero-Trust Administrative Blindness

Koinonia Cloud is built on a principle of Zero-Trust Administrative Blindness. The platform is architected so that Unbalanced Force administrators act as Infrastructure Custodians rather than Data Custodians.

Privacy Guarantee: Unbalanced Force platform administrators and system owners do not have access to a church's member data, private communications, or financial records.

What this means in practice:

  • No shared database. Each church has its own Cloud SQL instance. There is no central database that aggregates church data, and no query that can return member records from multiple churches.
  • No administrative back door. UF administrators deploy, monitor, and maintain infrastructure — they do not have application-level credentials to log into any church's Koinonia Cloud instance. Only the church's own SuperAdmin controls who can access their data.
  • Secrets are church-scoped. Every secret (database password, JWT key, API tokens) is namespaced per church in GCP Secret Manager. The platform service account cannot read church secrets; each church's service account can only read its own.
  • The Command Center is blind to data. Fleet Monitoring shows infrastructure health (CPU, memory, error rates, request volume) — it never exposes church member data, giving records, or any PII. The operations tab can restart or redeploy services but cannot query a church's database.
  • Exports are encrypted. Church data exports are AES-256 encrypted with a passphrase known only to the church. Even if an export file were intercepted, it is unreadable without the church's passphrase.

This architecture means that a breach of Unbalanced Force's own infrastructure — including the Command Center, the platform database, and the GCP project's IAM — does not grant access to any church's congregational data. The worst case is a service disruption, not a data breach.

A Note on Root Authority and Integrity:

It is important to clarify the distinction between infrastructure management and data access. As the GCP Project Owner, Unbalanced Force holds the master keys to the cloud project. While root-level authority technically permits an owner to override IAM policies to grant themselves temporary access to a resource, the Koinonia architecture is designed for Administrative Neutrality:

  • No Operational Back Doors: There are no UF-controlled "Global Admin" accounts at the application layer. An administrator cannot simply log into a church's dashboard.
  • Immutable Audit Logs: Every action taken by a project owner is recorded in GCP Cloud Audit Logs. These logs cannot be deleted or modified by the administrator, ensuring that any deviation from "Infrastructure-Only" management is permanently discoverable.
  • Separation of Duty: The operational platform is designed to be managed via the Command Center, which is physically incapable of querying tenant databases.
For the website:¹ This principle should be featured prominently on the Koinonia Cloud marketing site as a trust differentiator. Churches evaluating ChMS platforms need to know that their data is structured for isolation — a guarantee that monolithic multi-tenant SaaS platforms cannot make.
¹ Pending addition to koinoniacloud.com — see index.html in the koinonia-platform repo.

1c. Platform-to-Church Monitoring (Service-to-Service Auth)

The Command Center needs to read infrastructure metrics (database connection saturation, auth-endpoint health) from each church's API. These endpoints use a dedicated service-to-service auth boundary that is separate from the JWT-based church user authentication:

  • Church-side endpoint: GET /api/monitoring/stats — accepts an X-Admin-Token header and validates it against the PLATFORM_MONITOR_TOKEN environment variable (stored as a GCP Secret Manager secret per church).
  • Platform-side proxy: GET /api/admin/monitoring/church-stats/{church_id} — resolves the church API URL from the fleet, then calls /api/monitoring/stats with the platform's admin token.
  • Security boundary: The monitoring endpoint returns only aggregate counts (connection pool usage, auth request/error counts). It never exposes church member data, PII, or query text. This is by design — if the token leaks, the blast radius is limited to infrastructure metrics.
  • Why not JWT? JWT auth requires church user credentials (email/password). The platform has no business holding church user passwords. A shared monitoring token is scoped, auditable, and rotatable without affecting church users.
Secret name convention: koinonia-{church-id}-platform-monitor-token in GCP Secret Manager. The deploy.sh script automatically wires it as PLATFORM_MONITOR_TOKEN on Cloud Run if the secret exists.
Intrusion response at a glance: honeypot/tarpit trip → URGENT ntfy page + the Intrusions panel → if confirmed, Freeze the instance (it stays alive, sealed; evidence is auto-captured) → investigate from the sealed bundle → Unfreeze, or drop the customer. A trip only alerts — it never auto-freezes or auto-captures; those are your call.

1c-iii. Intrusion Alerting (Honeypot / Tarpit)

The shared platform code carries decoy endpoints (honeypots) and latency traps (tarpits). No legitimate user ever touches a honeypot, so a trip means a bot is crawling the platform — a UF concern, not the church's. When a church instance's security middleware records a trip (honeypot_block, block, tarpit_high, tarpit_low) it pushes it, best-effort, to the platform so UF is paged:

  • Hub endpoint: POST /api/admin/security/trip, authed by the shared PLATFORM_SECURITY_INGEST_TOKEN (X-Ingest-Token header). It stores one row per trip in platform_security_events — attack metadata only; user_id is the offending account when the bot was authenticated (the ToS link).
  • Page: an URGENT message to the dedicated intrusion ntfy channel (NTFY_INTRUSION_URL), coalesced per church (one page per 10 min) so a crawl of many decoys is a single alert, not a storm.
  • Command Center: the Intrusions panel under Fleet Monitoring lists every trip across all instances, newest first — church, decoy path, attacker IP, account, and risk score.
On a page: open the Intrusions panel to gauge scope (how many churches, sessions, and accounts are implicated), then, if the intrusion is confirmed, seal the instance with Freeze Instance (Operations tab). The church's own security_events table stays the durable, append-only forensic record even if the push failed. Churches have no view of this data (no Admin-tab panel, no church API route); to read an instance's full security_events history, connect to its database as the koinonia Postgres user.

1c-iv. Freeze Instance (Lockdown)

In Operations, with a church selected, Freeze puts that instance into lockdown: the security middleware serves a 503 maintenance page to all traffic — only health/info and the platform control endpoints stay up. Crucially, the instance keeps running: Freeze is a database flag the middleware reads (within ~10 s), not a scale-down or redeploy, so the live container and its state are preserved for forensic capture. Unfreeze restores normal service in seconds. The operator's name and reason are logged (an INSTANCE_FREEZE_ON/OFF marker the forensic-capture job will hook). This control is UF-only; churches cannot reach it. While frozen, the Freeze button greys out and reads FROZEN (and Unfreeze lights up), so the state is unmistakable at a glance. Freezing automatically seals a forensic evidence bundle (see 1c-v) — unless you tick this is a test — skip evidence capture in the dialog.

Freeze takes a whole church offline for its users — use it when an intrusion is confirmed, not as a first response. The honeypot/tarpit layer is already tarpitting and blocking the bot on its own before you freeze.

1c-v. Forensic Evidence Capture

Freeze automatically seals a forensic evidence bundle — synchronously, so it is guaranteed to complete before the freeze returns (the freeze takes ~15–25 s because of it). You can also seal one without freezing via Capture Evidence in Operations. The platform gathers it — never the frozen church — so a compromised instance cannot tamper with what is collected. Each bundle is written under evidence/<church>/<timestamp>/ in the retention-locked evidence bucket and contains:

  • A point-in-time DB export (db.sql.gz) — the offending account's full activity plus the append-only security_events trail. Taken with offload (a temporary instance) so it never loads the live/frozen instance; it runs async — confirm completion under Cloud SQL → Operations.
  • The full 24 h of request logs (requests.json) — independent Cloud Run corroboration the attacker never touched. (The complete logs also stay in Cloud Logging ~30 days regardless.)
  • A manifest (manifest.json) — who/why/when and the operations that produced it, for chain of custody.
WORM + PII: the DB export is plaintext member PII, so it goes to a dedicated, access-controlled bucket that is retention-locked (WORM) for 180 days — nothing written can be deleted until it expires, surviving even a compromised project admin. One-time setup is deploy/setup_evidence_capture.sh (creates the bucket + grants each church's Cloud SQL service account objectCreator — the export writes as that SA; LOCK=1 arms the 180-day WORM, irreversible, already done). Grant a newly-provisioned church's SQL SA by re-running it with CHURCHES="<id>".
⚠ Always tick “this is a test — skip evidence” on a TEST freeze. A real freeze seals a bundle that is (correctly) immutable for 180 days; a test freeze without the box leaves a permanent, un-deletable prod-PII dump. Cost is otherwise negligible — object storage grows only per capture (~$0.03 for a baylife-sized dump held the full window), and captures are rare, deliberate events (a honeypot trip only pages; it never auto-captures).

1c-vi. Unattended Alert Watchers (5xx & Email-Send)

Two background watchers read the fleet's Cloud Run logs on one shared Cloud Scheduler tick (~every 15 min, POST /api/admin/monitoring/errors/scan) and page a dedicated ntfy channel so a silent outage can't run for days unseen. They run on the platform's own service account (koinonia-platform-sa, which holds roles/logging.viewer) — no credential that can expire, so the watcher never goes blind.

  • 5xx errors → NTFY_GCP_ERRORS_URL. Any Cloud Run service over the threshold of server errors in the window pages, with a per-service hourly cooldown.
  • Email-send failures → NTFY_EMAIL_URL. Watches every koinonia-*-api for Postmark send failures (SMTP error, recipient refused, token missing) — the exact silent-failure mode of the 2026-10-01 Postmark outage, where staff screens still read “sent.” Pages carry only the service, a count, and a sanitized error kind — never a recipient address or subject, since ntfy.sh is third-party.
Both channels are guarded in deploy.sh: the ntfy URL is stored and bound only when its variable (NTFY_GCP_ERRORS_URL / NTFY_EMAIL_URL) is present in the platform .env — keep them there across deploys. Subscribe your phone to each topic in the ntfy app. The email watcher replaces the former on-prem cron (.199 kc-monitor/check_email.sh), which read logs with an interactive login that expired and paged about its own blindness.

1d. Prerequisites

On your local machine

  • gcloud CLI installed and authenticated:
gcloud auth login
gcloud config set project koinoniacloud-490205
  • Docker installed (for local dev only — Cloud Build handles GCP builds)
  • Git access to the koinonia-cloud repository
  • Run all deploy commands from the repository root (koinonia-cloud/)

Third-party accounts needed before deployment

  • Postmark account at postmarkapp.com — one Server per church
  • Twilio account at twilio.com — optional; required for SMS features
  • Stripe account — optional; required for paid event registrations and giving
  • Cloudflare access to koinoniacloud.com DNS — for custom subdomains

1e. Pre-Deployment Checklist

There are two provisioning flows. Choose one before starting:

Automated flow (preferred — church came in via get-started form)

  • Church submitted the get-started form and the application is in the platform DB
  • UF admin has approved the application in admin.html → church receives an agreement-acceptance link by email (not a Stripe link — see the callout below)
  • Church opened /accept/{token}, accepted the Master Subscriber Agreement, and was redirected to Stripe checkout
  • Church has completed Stripe payment (confirm in Stripe dashboard before proceeding)
  • You have the interest/application ID from the platform (shown on the admin panel card)
  • Choose a {church-id} (lowercase, hyphens only, e.g. firstbaptist)
  • Complete Postmark setup → have server token + From address ready
  • Complete Twilio setup if SMS is needed
  • Have the platform API admin token ready (koinonia-platform-admin-token secret)
Note: In the automated flow, admin email and password are derived automatically from the interest form and do not need to be collected. The church receives a welcome email with login credentials after provisioning.
Agreement-acceptance gate (Phase 1 onboarding): Approving an application no longer emails the Stripe link directly. Instead the platform mints a one-time accept_token (valid 14 days) and the approval email links to /accept/{token}. There the church reviews the Master Subscriber Agreement (Terms + Privacy), confirms they are authorized to bind the church, types their name, and accepts — only then is the Stripe checkout link revealed and the church redirected to pay. Each acceptance is recorded in the agreement_acceptances table (version, name, IP, user-agent, UTC timestamp) as the E-SIGN Act (15 U.S.C. § 7001) legal record. If a church reports the link expired or already used, re-approve the application to mint a fresh token. The acceptance version is set by the AGREEMENT_VERSION env var (default 1.2, matching the published Terms/Privacy on the marketing site); bump it in lockstep with those documents. The full Terms and Privacy documents are served from the marketing site (koinonia-cloud-web, currently its Cloud Run URL until the top-level domain is live), not this platform — the accept page links out to them via the MARKETING_BASE_URL setting.

Manual flow (direct onboarding without a get-started form submission)

  • Choose a {church-id} (lowercase, hyphens only, e.g. firstbaptist)
  • Obtain church's admin email address
  • Set a strong initial password (minimum 8 characters) — store it safely
  • Complete Postmark setup → have server token + From address ready
  • Complete Twilio setup if SMS is needed → have Account SID, API Key SID, API Key Secret, From Number ready
  • Complete Stripe setup if payments are needed
  • Confirm the church's domain for DNS/CORS (if using a custom subdomain)

1f. One-Click Provisioning (Command Center button)

The Provision instance → button on an approved application card stands up a full church environment without touching the CLI. It stages the per-church secrets in Secret Manager, then dispatches the provision-church GitHub Actions workflow on billburnham/koinonia-cloud, which runs deploy.sh (creates Cloud SQL + Cloud Run + bucket + secrets, seeds the church profile from the interest application, and calls back to mark it provisioned).

How the secrets stay safe: the Anthropic key, Postmark token, and From address are written straight into Secret Manager by the platform; only non-secret inputs (church id, interest id, map URLs) travel through the GitHub dispatch — GitHub event payloads are logged, so no credential ever passes through them. deploy.sh step 7 grants the new church's service account access to every koinonia-{church}-* secret automatically, so the staged secrets are readable without any per-secret grant.
Push notifications are auto-configured — no manual step. As of 2026-06-06, deploy.sh (Step 6) self-heals the Web Push secrets on a church's first deploy: it generates the per-church VAPID keypair (koinonia-{church}-vapid-public-key / -vapid-private-key) and the -push-scheduler-secret, then provisions the Cloud Scheduler reminder jobs. You no longer need to run generate_vapid.sh before onboarding a church — parent pickup alerts and volunteer reminders work out of the box. Existing keys are reused on redeploy (never regenerated), so active subscriptions are preserved. generate_vapid.sh is retained only for intentional key rotation. (Before this change, push silently no-op'd on any church that hadn't had the script run manually — /api/push/vapid-public-key returned 503 and devices showed "Push isn't configured on this church's server yet.")
One-time operator setup before the button works. Provisioning wields project-admin-grade power, so it runs under a dedicated identity in GitHub, not on the always-on backend:
  1. Create a provisioning service account (e.g. provision-sa@koinoniacloud-490205.iam.gserviceaccount.com) and grant it: Cloud SQL Admin, Cloud Run Admin, Artifact Registry Admin, Service Account Admin, Secret Manager Admin, Cloud Build Editor, Service Usage Admin, Project IAM Admin, Storage Admin.
  2. Configure Workload Identity Federation for the koinonia-cloud repo and add repo secrets GCP_WIF_PROVIDER and GCP_PROVISION_SA (see .github/workflows/provision-church.yml header).
  3. Grant the platform service account roles/secretmanager.admin on the project (so it can stage the per-church secrets).
  4. Ensure GITHUB_DISPATCH_TOKEN (already used by the Quality tab) has workflow scope on the repo.
Until these exist, the button returns a clear error (503 if the dispatch token is missing, 502 if secret staging or dispatch fails).

Provisioning is intentionally NOT gated on agreement acceptance or payment — you may stand an environment up in advance. The modal shows whether the church has accepted and paid so you can decide, but it won't stop you. Track a run in GitHub Actions → Provision Church Instance, then in Fleet Monitoring once the services appear.


2a. Postmark Setup (Email)

Koinonia Cloud uses the Postmark HTTP API (not SMTP) for all outgoing email. Each church gets its own Postmark Server so email streams are fully isolated.

4.1 Create a Postmark Server

  1. Log in to account.postmarkapp.com
  2. Click "+ Create Server"
  3. Name it after the church (e.g. First Baptist Church)
  4. Leave Message Streams at defaults (Transactional + Broadcasts created automatically)

4.2 Verify the Sender Domain

  1. In the new server, go to Sender Signatures → Add Domain
  2. Enter the church's domain (e.g. firstbaptist.org) or use koinoniacloud.com for the demo
  3. Postmark will show you two DNS records to add — add them in the church's DNS provider
  4. Click Verify — you need both DKIM Verified and Return-Path Verified (green checkmarks)
Tip: For the shared koinoniacloud.com demo domain: koinoniacloud.com is already verified. Use noreply@koinoniacloud.com as the From address.

4.3 Get the API Token & Store in GCP

  1. In your Postmark server, go to API Tokens
  2. Copy the Server API Token (looks like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

Store the token as a GCP secret:

echo -n "YOUR_POSTMARK_SERVER_TOKEN" | gcloud secrets create koinonia-${CHURCH_ID}-postmark-token \
  --project=koinoniacloud-490205 --replication-policy=automatic --data-file=- --quiet

Grant the church's service account access:

gcloud secrets add-iam-policy-binding koinonia-${CHURCH_ID}-postmark-token \
  --member="serviceAccount:koinonia-${CHURCH_ID}-sa@koinoniacloud-490205.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor" --quiet

Wire the secret into the Cloud Run API service:

gcloud run services update koinonia-${CHURCH_ID}-api \
  --region=us-central1 \
  --project=koinoniacloud-490205 \
  --update-secrets=POSTMARK_SERVER_TOKEN=koinonia-${CHURCH_ID}-postmark-token:latest

To update an existing token (e.g. rotating credentials or switching Postmark servers):

# Add a new version of the secret
echo -n "NEW_POSTMARK_SERVER_TOKEN" | gcloud secrets versions add koinonia-${CHURCH_ID}-postmark-token \
  --project=koinoniacloud-490205 --data-file=- --quiet

# Redeploy to pick up the new secret version
gcloud run services update koinonia-${CHURCH_ID}-api \
  --region=us-central1 \
  --project=koinoniacloud-490205 \
  --update-secrets=POSTMARK_SERVER_TOKEN=koinonia-${CHURCH_ID}-postmark-token:latest

4.3a Sandbox Mode for Test & Demo Environments

For test or demo environments (e.g. baylife-test), use a Postmark Sandbox server to prevent emails from reaching real inboxes. Sandbox servers accept API calls and log messages in the Postmark Activity tab, but never deliver to actual recipients.

  1. In Postmark, create a new server and set the Server Type to Sandbox (shown as a yellow badge in the dashboard)
  2. Copy the sandbox server's API token and store it as the church's GCP secret using the commands above
  3. All emails will appear in the Postmark Activity tab for inspection without reaching real people

Alternative: Set DISABLE_EMAIL=true on the Cloud Run service to suppress all email sends entirely (emails are logged in Cloud Run logs but not sent to Postmark at all):

gcloud run services update koinonia-${CHURCH_ID}-api \
  --region=us-central1 \
  --project=koinoniacloud-490205 \
  --set-env-vars="DISABLE_EMAIL=true"
Note: Use Sandbox mode (preferred) when you want to inspect email content and formatting during testing. Use DISABLE_EMAIL when you want to completely suppress email activity.

4.4 Configure the Webhook (after deployment)

After the church's backend Cloud Run service is deployed, register the delivery webhook:

  1. In Postmark → your server → Default Transactional Stream → Webhooks → Add Webhook
  2. Set the URL to:
https://postmark:{webhook-password}@koinonia-{id}-api-[hash].us-central1.run.app/api/communications/postmark-webhook

(Replace the host with the actual Cloud Run URL shown at the end of deploy.sh. The postmark:{webhook-password} pair is the Basic-Auth credential secrets.sh generated for this church — read it back with gcloud secrets versions access latest --secret=koinonia-{id}-postmark-webhook-password.)

  1. Enable: Delivery, Bounce, Open, Click, SpamComplaint
  2. Click Save, then use the Test button — expect a 200 {"status":"ok"} response. A 401 means the user:password in the URL does not match the church's secrets; a 503 means the backend revision was deployed before secrets.sh minted the pair — re-run secrets.sh, then deploy.sh.
The endpoint refuses unauthenticated events. Since 2026-09-08 the backend fails closed: without the credential pair every Postmark event is rejected. This is deliberate — an open webhook let anyone who knew the API hostname forge a SubscriptionChange and silently unsubscribe a real member. Churches deployed before that date need secrets.sh re-run (it mints the pair once and keeps it on later runs) and the Postmark webhook URL updated to the credentialed form above.
Note: When moving to a custom domain, update this webhook URL to https://postmark:{webhook-password}@api-{id}.koinoniacloud.com/api/communications/postmark-webhook if you add a custom domain to the backend Cloud Run service.

4.5 DMARC DNS Record

Add this TXT record in the church's DNS provider (or in Cloudflare for koinoniacloud.com):

Type Name Value
TXT _dmarc v=DMARC1; p=quarantine; pct=100; rua=mailto:dmarc@postmarkapp.com

p=quarantine tells receiving servers to route failing messages to spam rather than reject them outright. The rua address sends DMARC aggregate reports to Postmark's reporting inbox.

Tip: koinoniacloud.com already has this record configured.

4.6 Summary of values needed for secrets.sh

Prompt Value
From name The church's display name as it appears in recipients' inboxes, e.g. First Baptist Church
From email address noreply@{church-domain} (must match verified sender domain)
Postmark server token Your server's API token from step 4.3

2b. Twilio Setup (SMS)

SMS is optional. Skip this section if the church does not need SMS.

5.1 Get a Twilio Phone Number

  1. Log in to console.twilio.com
  2. Go to Phone Numbers → Manage → Buy a number
  3. Filter by SMS capability, choose a local area code if possible
  4. Purchase and note the number (e.g. +15125550100)

5.2 Create an API Key (recommended over Account SID + Auth Token)

  1. Go to Account → API keys & tokens → Create API key
  2. Choose Standard key type, name it after the church
  3. Copy the SID (starts with SK) and Secret — the secret is shown only once

5.3 Configure the Status Webhook (after deployment)

  1. Go to Phone Numbers → Manage → Active numbers → [your number]
  2. Under Messaging → A message comes in — leave blank (Koinonia doesn't receive inbound SMS)
  3. Under Status Callback URL, set:
https://koinonia-{id}-api-[hash].us-central1.run.app/api/sms/twilio-webhook
  1. Save

5.4 Summary of values needed for secrets.sh

Prompt Value
Twilio Account SID Found on console.twilio.com main dashboard
Twilio API Key SID SK... from step 5.2
Twilio API Key Secret Secret from step 5.2 (shown once)
Twilio From Number E.164 format, e.g. +15125550100

2c. Stripe Connect Setup (Payments)

Stripe is optional. Skip this section if the church does not need paid event registrations or digital giving.

6.1 Create or connect a Stripe account

Each church needs its own Stripe account (or a connected account under a platform account if you are using Stripe Connect).

For a simple standalone deployment:

  1. The church creates a Stripe account at stripe.com
  2. In the Stripe Dashboard → Developers → API keys, copy the Secret key (sk_live_...)
  3. Under Developers → Webhooks → Add endpoint, set:
https://koinonia-{id}-api-[hash].us-central1.run.app/api/webhooks/stripe
  1. Select events: payment_intent.succeeded, payment_intent.payment_failed, charge.refunded
  2. Copy the Signing secret (whsec_...)

6.2 Store secrets

Stripe secrets are stored manually after deployment via direct gcloud commands (not yet in secrets.sh):

Required: The STRIPE_WEBHOOK_SECRET below is mandatory whenever Stripe is enabled. The webhook receiver fails closed (HTTP 503) if it's missing — forged webhook events cannot be processed without it. If you set up Stripe but skip this secret, payment confirmations from Stripe will fail until you add it.
CHURCH_ID="firstbaptist"
SA_EMAIL="koinonia-${CHURCH_ID}-sa@koinoniacloud-490205.iam.gserviceaccount.com"

# Store secrets
printf 'sk_live_...' | gcloud secrets create koinonia-${CHURCH_ID}-stripe-secret-key \
  --project=koinoniacloud-490205 --replication-policy=automatic --data-file=- --quiet

printf 'whsec_...' | gcloud secrets create koinonia-${CHURCH_ID}-stripe-webhook-secret \
  --project=koinoniacloud-490205 --replication-policy=automatic --data-file=- --quiet

# Grant SA access
gcloud secrets add-iam-policy-binding koinonia-${CHURCH_ID}-stripe-secret-key \
  --member="serviceAccount:${SA_EMAIL}" --role="roles/secretmanager.secretAccessor" --quiet

gcloud secrets add-iam-policy-binding koinonia-${CHURCH_ID}-stripe-webhook-secret \
  --member="serviceAccount:${SA_EMAIL}" --role="roles/secretmanager.secretAccessor" --quiet

# Wire into Cloud Run
gcloud run services update koinonia-${CHURCH_ID}-api \
  --region=us-central1 \
  --update-secrets="STRIPE_SECRET_KEY=koinonia-${CHURCH_ID}-stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=koinonia-${CHURCH_ID}-stripe-webhook-secret:latest" \
  --quiet

3a. Cloudflare DNS Setup

7.1 Default URLs (no DNS config needed)

After deploy.sh completes, the church is immediately accessible at the auto-generated Cloud Run URLs:

  • Frontend: https://koinonia-{id}-web-[hash].us-central1.run.app
  • Backend: https://koinonia-{id}-api-[hash].us-central1.run.app

7.2 Custom subdomain (optional)

To give the church a branded URL like https://firstbaptist.koinoniacloud.com:

  1. In the Google Cloud Console → Cloud Run → koinonia-{id}-web, go to Custom domains → Add mapping
  2. Enter firstbaptist.koinoniacloud.com
  3. GCP will show you a CNAME record — add it in Cloudflare:
Type Name Target
CNAME firstbaptist ghs.googlehosted.com
  1. IMPORTANT: In Cloudflare, set the proxy to DNS only (grey cloud). Google Cloud cannot provision its managed SSL certificate if Cloudflare's proxy is active during the challenge. You can turn proxying back ON only after the certificate status shows "Active" in the GCP console.
  2. Repeat for the backend (api-firstbaptist.koinoniacloud.com → koinonia-{id}-api) if desired.
Important: After adding a custom domain, update the CORS_ORIGINS secret to include the new frontend URL (comma-separated), then update the Postmark and Twilio webhook URLs accordingly.

3b. Running the Deployment Scripts

All commands run from the repository root: cd /mnt/AntiGravity/KoinoniaCloud/koinonia-cloud

Automated flow (church came in via get-started form)

Step 1 — Store manual secrets (automated flow)

Run secrets.sh with --interest-id. This skips the admin credential prompts — those are auto-derived from the interest form.

./deploy/secrets.sh --church-id {church-id} --interest-id {application-id}

You will be prompted for:

  • Anthropic API key (required) — sk-ant-... from console.anthropic.com
  • SMTP from name (optional) — display name in recipients' inboxes
  • SMTP from address (optional) — noreply@{church-domain} (must be verified in Postmark)
  • Postmark server token (optional) — from Postmark dashboard
  • Public URL (skip for now) — set after first deploy
  • Twilio credentials (optional)
Note: Admin email and password are not prompted — they will be auto-derived from the interest form by deploy.sh.

Step 2 — Run the full deployment (automated flow)

./deploy/deploy.sh --church-id {church-id} --interest-id {application-id} \
  --platform-url https://koinonia-platform-api-3gkbpl3h6q-uc.a.run.app \
  --platform-token {ADMIN_TOKEN}

The script refuses to start on a dirty working tree (see 6a) and then runs these steps automatically (the numbers are the ones printed in its output):

  1. Enables required GCP APIs
  2. Creates Artifact Registry repository (shared across all churches)
  3. Creates the church's service account
  4. Creates Cloud SQL instance + database + user (~5 min on first run)
  5. Creates GCS bucket for uploads
  6. Stores auto-generated secrets (DB password, DB URL, JWT secret key), and on a first deploy self-heals the Web Push secrets (VAPID keypair, push-scheduler secret) and the Postmark webhook credentials. Automated flow only: fetches contact_email from the interest form → stores as admin-email secret; auto-generates a random password → stores as admin-password secret
  7. Grants IAM roles to the service account (including access to every koinonia-{church}-* secret)
  8. Builds the backend image with Cloud Build and deploys koinonia-{id}-api; 8a runs alembic upgrade head + seeding through a one-shot Cloud Run Job before traffic shifts; the same image is deployed as the koinonia-{id}-worker Cloud Run Job (backups, restores and file-packing exports run there, not on the API); 8.5 deploys the dedicated SSE service koinonia-{id}-sse
  9. Builds and deploys the frontend koinonia-{id}-web (with the API URL looked up from the live service, never guessed); 9.5 maps the custom domain {id}.koinoniacloud.com; then stamps LAST_DEPLOY, DEPLOY_COMMIT, WORKER_JOB and GCP_REGION on the API and creates or updates the Cloud Scheduler jobs (push reminders, security-event prune) and the Cloud Tasks queue
  10. Automated flow only: calls POST /api/admin/applications/{id}/provision on the platform, which:
    • Seeds church_profile on the new instance with data from the interest form, authenticating with that church’s own push scheduler secret (read from Secret Manager). If the secret is missing the call fails with 502 and the application is not marked provisioned
    • Creates no user: the first SUPERADMIN was already minted in 8a from the -admin-email / -admin-password secrets
    • Sends a welcome email to the church contact with login URL and temporary password
    • Marks the application as provisioned in the platform DB

At the end, it prints the deployed URLs and provisioning status:

Frontend    : https://koinonia-{id}-web-[hash].us-central1.run.app
Backend     : https://koinonia-{id}-api-[hash].us-central1.run.app
Provisioned : application #{id} marked as provisioned

Manual flow (direct onboarding without a get-started form)

Step 1 — Store manual secrets (manual flow)

./deploy/secrets.sh --church-id {church-id}

You will be prompted for:

  • Anthropic API key (required)
  • Admin email (required) — the SuperAdmin account Koinonia creates on first startup
  • Admin password (required) — minimum 8 characters, store it somewhere safe
  • CORS origins (skip for now) — set automatically by deploy.sh after frontend deploys
  • SMTP from address (required for email) — e.g. noreply@firstbaptist.org
  • Postmark server token (required for email)
  • Public URL (skip for now)
  • Twilio credentials (optional)

Step 2 — Run the full deployment (manual flow)

./deploy/deploy.sh --church-id {church-id}

The script runs the same steps minus the interest-form parts of step 6 and step 10. The admin must log in and complete Church Profile manually after deployment.

First startup: The backend automatically runs alembic upgrade head on startup. Alembic owns both the schema (created by 0001_bootstrap_baseline) AND every platform-default row a new church needs to be functional (seeded by c2d7c86cf2a4_seed_platform_reference_data and follow-ups). No separate seeding step. The first request may be slow (10–20 seconds) while migrations apply. See Section 5a.10 for the full inventory of what every new church starts with.

4a. Post-Deployment Configuration

9.1 Set the Public URL (for QR codes in emails)

CHURCH_ID="firstbaptist"
FRONTEND_URL="https://koinonia-firstbaptist-web-[hash].us-central1.run.app"
SA_EMAIL="koinonia-${CHURCH_ID}-sa@koinoniacloud-490205.iam.gserviceaccount.com"

printf "${FRONTEND_URL}" | gcloud secrets create koinonia-${CHURCH_ID}-public-url \
  --project=koinoniacloud-490205 --replication-policy=automatic --data-file=- --quiet 2>/dev/null || \
printf "${FRONTEND_URL}" | gcloud secrets versions add koinonia-${CHURCH_ID}-public-url \
  --project=koinoniacloud-490205 --data-file=- --quiet

gcloud secrets add-iam-policy-binding koinonia-${CHURCH_ID}-public-url \
  --member="serviceAccount:${SA_EMAIL}" --role="roles/secretmanager.secretAccessor" --quiet

gcloud run services update koinonia-${CHURCH_ID}-api \
  --region=us-central1 \
  --update-secrets="PUBLIC_URL=koinonia-${CHURCH_ID}-public-url:latest" \
  --quiet

9.2 Register Postmark webhook

See Section 2a (4.4 Configure the Webhook).

9.3 Register Twilio status webhook

See Section 2b (5.3 Status Webhook).

9.4 Log in and configure the church profile

  1. Navigate to the frontend URL
  2. Log in with the admin email and password set in secrets.sh at /operator-signin, then enrol the authenticator app on that account — see 8c. The operator account must carry it.
  3. Go to Settings → fill in the church name, address, logo, mission statement
  4. Go to Settings → Scripture — add weekly scriptures for the home screen
  5. Go to Settings → Emergency Contacts — add emergency contact numbers

9.5 Configure Finance settings

After logging in as SuperAdmin, complete the Finance module setup:

  1. Click the Finance tab → Settings sub-tab (SuperAdmin only)
  2. Set the church's Fiscal Year Start Month (default: January). This controls how the financial reports group data by period. Note: year-end giving statements always use the calendar year (January–December) regardless of this setting, as required by the IRS.
  3. Enter the church's EIN (Employer Identification Number) — this appears on printed giving statements.
  4. Enter the church's legal name as it appears on tax filings.
  5. Review the default Funds (General Fund, Building Fund, Missions Fund) — add, rename, or mark as active/inactive to match your church's structure.
  6. Review the pre-seeded Chart of Accounts under the Accounts sub-tab. The 39 default accounts cover a standard church chart of accounts. Add any church-specific accounts as needed (the Finance Director or bookkeeper should approve the chart before going live).
Important: The Chart of Accounts, Funds, and Income Categories are seeded by Alembic migration c2d7c86cf2a4_seed_platform_reference_data as part of alembic upgrade head on first startup. No manual SQL seeding is required, and the seed runs once per database (idempotent on re-deploy).

9.6 Configure Safety & Compliance (Background Check / Ministry Safe)

Koinonia Cloud tracks Background Check and Ministry Safe training dates as first-class fields on each person record. Per-role compliance gates enforce these requirements on the Volunteers roster.

Step 1 — Set the Background Check expiry period

  1. Log in as SuperAdmin → go to the Volunteers tab
  2. Click the ⚙ Role Catalog button (top right of the Volunteers tab)
  3. In the header of the Role Catalog, find "Background Check Expiry" — default is 48 months (4 years)
  4. Click Edit, enter the number of months your church policy requires, click Save

Step 2 — Flag roles that require a Background Check

  1. In the Role Catalog, click Edit on any role that requires a background check
  2. Check "Requires Background Check"
  3. Click Save

Only roles with this flag will show amber/red status for volunteers whose background check is missing or expired. Roles without the flag are unaffected.

Step 3 — Flag roles that require Ministry Safe training

Same process — check "Requires Ministry Safe training" on any role where that applies.

Step 4 — Record Background Check and Ministry Safe dates per person

Staff can enter dates two ways:

  • Individually: Open a person's detail card → click Edit (pencil icon) → scroll to the Additional Info dates section → fill in Background Check Date and/or Ministry Safe Training Date → Save
  • In bulk via CSV import: Use the Prereq Import tool (Volunteers tab → Import) — map CSV columns to → Background Check Date or → Ministry Safe Date actions

Viewing compliance status

When a staff member opens a person's Volunteer Roles popup, the header shows their current Background Check date and status badge (Active / Expiring / Expired / Not on file) and Ministry Safe training date — applying to all roles at a glance.

9.7 Verify email is working

  1. Create a test event and register yourself
  2. Go to the event's registrant list and send a test email
  3. Check the Communications tab — the send should appear in the Email log
  4. Confirm the email arrived in your inbox from noreply@{church-domain}
  5. Check Postmark dashboard → your server → Activity — the message should appear there

5a. Database Migrations (Alembic)

As of 2026-04-06, all schema changes are managed by Alembic. Manual SQL migration scripts are retired. This is a critical system — Koinonia Cloud is single-tenant SaaS with 1,000+ church databases. Every schema change must propagate automatically and reliably across all instances.

5a.1 How it works

The backend runs alembic upgrade head automatically every time it starts (backend/app/main.py → run_migrations()). This means:

  • New deployments — no separate migration step. Deploy the backend image and the schema is created and brought up to date automatically.
  • Existing deployments — deploy the new backend image. Any new Alembic revision files included in the image will apply on startup.
  • You never need to run psql or apply .sql files manually for schema changes.

All instances (local Docker, demo, baylife-test, and any future church deployments) share the same Alembic revision history. The chain root is 0001_bootstrap_baseline (replaced the older 4c9a9ea557e7 baseline on 2026-05-04 because that one ALTERed tables that no migration created — it implicitly relied on the legacy database/init.sql bootstrap, which broke automated provisioning of new churches).

Alembic migrations form a linked list — each migration file has a revision (its own unique ID) and a down_revision (pointing to the previous migration). At any point, alembic heads should return exactly one head. Multiple heads indicate a fork that must be merged before deploy.

5a.2 Creating a new migration — the --autogenerate workflow

CRITICAL RULE: ALWAYS use --autogenerate. Never hand-write migration files. Never generate empty skeletons and fill them in manually. Autogenerate compares your Python models against the actual database and produces the exact DDL needed to bring the database in line with the code. Hand-written migrations caused multiple production outages (see Troubleshooting and Lessons Learned).

How autogenerate works

Alembic's --autogenerate flag tells the tool to:

  1. Read every Column(), Table(), ForeignKey(), and Index() defined in backend/app/models/models.py
  2. Connect to the running database and read every table, column, and constraint from information_schema
  3. Diff the two — find every column that exists in the model but not in the database (or vice versa), every type mismatch, every missing index
  4. Generate a complete Python migration file with the exact op.add_column(), op.alter_column(), op.create_table(), etc. calls needed to close the gap

What autogenerate catches and what it misses

Detected automatically NOT detected (must handle manually)
New tables Table or column renames (seen as drop + create)
New columns Changes to CHECK constraints
Dropped tables/columns Data migrations (backfilling values)
Column type changes (e.g., JSON → JSONB) Enum value additions
Nullable changes
Index additions/removals
Foreign key changes

For the cases autogenerate misses, you still use autogenerate to create the file, then add the manual operations to the generated upgrade() function. You never start from a blank file.

Step-by-step workflow

models.py --> autogenerate --> review --> add guards --> apply locally --> verify --> commit --> deploy
   (1)            (2)           (3)          (4)             (5)            (6)        (7)        (8)

1a. Edit the model — make your changes in backend/app/models/models.py. Add columns, change types, create tables — whatever the feature requires. Save the file.

1d. Generate the migration with --autogenerate:

sg docker -c "docker exec koinonia_api alembic revision --autogenerate -m 'add_foo_column_to_bar'"

This does three things at once: connects to the local Docker database, diffs every model class against the actual schema, and writes a complete migration file with a unique auto-generated revision ID.

1e. Review the generated file. Open it and read the upgrade() function. Verify it matches what you changed in the model. Watch for:

  • Renames detected as drop + create — if you renamed a column, autogenerate will drop the old one and create a new one (losing data). Replace with op.alter_column(..., new_column_name=...).
  • Unexpected changes — if autogenerate picks up something you didn't intend, investigate before removing it. It may be legitimate drift.

2a. Add idempotent guards to the generated operations (see Section 5a.4):

if not _column_exists("bar", "foo"):
    op.add_column("bar", sa.Column("foo", sa.Integer(), nullable=True))

2b. Apply the migration locally:

sg docker -c "docker exec koinonia_api alembic upgrade head"

2c. Run the schema comparison to verify zero drift:

sg docker -c "docker exec koinonia_api python /app/scripts/compare_schemas.py"

This must report MODELS AND DATABASE MATCH. If it reports differences, something was missed — go back to step 2.

3a. Verify single head and commit:

sg docker -c "docker exec koinonia_api alembic heads"
# Must show exactly one (head) line

git add backend/migrations/versions/<generated_file>.py backend/app/models/models.py
git commit -m "feat: add foo column to bar"
git push

3b. Deploy the backend. The migration applies automatically on startup.

Rules that must never be broken

Rule Why
Always use --autogenerate It diffs models vs DB — humans forget tables, the tool does not
Never hand-write a migration file Every hand-written migration in this project has caused an incident
Never use --rev-id Hand-crafted IDs have collided and caused silent migration skips
Never edit a migration after it's been committed GCP stamps the revision as "done" on first run. Editing the file changes the DDL but Alembic will never re-run it — the new operations are silently skipped on every instance that already applied the original version. If you need to fix a deployed migration, create a new migration.
Never run manual ALTER TABLE It fixes one instance and leaves every other church broken
Never run alembic revision outside Docker The container has the correct DATABASE_URL and migration history
Always run compare_schemas.py before deploying This is the final gate. Zero differences = safe to deploy.

5a.3 Parallel development (multiple agents)

When two Claude Code agents (or developers) work simultaneously on features that both require schema changes, they will each run alembic revision and both will get the same down_revision (the current head). This creates a fork:

                 +-- abc123 (Agent A: add_foo)
a2b3c4d5e6f7 --+
                 +-- def456 (Agent B: add_bar)

This is normal and expected. Alembic supports it via merge migrations.

How to resolve (manual)

# 1. Confirm the fork
sg docker -c "docker compose exec api-server alembic heads"
# Output: abc123 (head), def456 (head)

# 2. Create a merge migration
sg docker -c "docker compose exec api-server alembic merge heads -m 'merge_parallel_migrations'"

# 3. Verify single head
sg docker -c "docker compose exec api-server alembic heads"
# Output: ghi789 (head)   <-- the merge point

# 4. Commit the merge file

The merge migration is just a pointer — it has empty upgrade() and downgrade() functions. Both branches' schema changes still run independently.

Automatic safety net

The startup code in backend/app/main.py automatically detects multiple heads before running upgrade head. If a fork makes it to production, the app self-heals by creating a merge migration on the fly. This is a last resort — always merge locally before deploying.

When parallel migrations conflict

If both agents modify the same table or column, the merge will succeed but the second migration to run might fail (e.g., "column already exists"). This is why all migrations must be idempotent (see next section) — the _column_exists() guard makes even conflicting parallel migrations safe.

5a.4 Idempotency requirements

Every migration must safely survive partial-failure retries. If a Cloud Run container OOM-crashes or restarts mid-migration, the next boot retries the same migration. If it fails on "already exists," that church's database is bricked until manual intervention — unacceptable at 1,000+ instances.

Required helper functions

Copy from any recent migration:

def _column_exists(table: str, column: str) -> bool:
    conn = op.get_bind()
    result = conn.execute(sa.text(
        "SELECT EXISTS (SELECT 1 FROM information_schema.columns "
        "WHERE table_schema = 'public' AND table_name = :t AND column_name = :c)"
    ), {"t": table, "c": column})
    return result.scalar()

def _table_exists(table: str) -> bool:
    conn = op.get_bind()
    result = conn.execute(sa.text(
        "SELECT EXISTS (SELECT 1 FROM information_schema.tables "
        "WHERE table_schema = 'public' AND table_name = :t)"
    ), {"t": table})
    return result.scalar()

Required patterns

Operation Guard
op.create_table() if not _table_exists('table_name')
op.add_column() if not _column_exists('table', 'column')
op.drop_column() if _column_exists('table', 'column')
op.drop_table() if _table_exists('table_name')

Never use Base.metadata.create_all() — it creates tables outside Alembic's control, which blocks migration retries. Alembic is the sole schema authority.

5a.5 Pre-commit hook

A local git pre-commit hook (.git/hooks/pre-commit) automatically checks for multiple Alembic heads when you commit migration files. If a fork is detected, the commit is blocked with instructions to merge.

The hook only runs when:

  • Migration files are staged for commit (backend/migrations/versions/*.py)
  • The Docker api-server container is running

If Docker isn't running, the hook passes silently — the runtime auto-merge (Section 5a.3) serves as the fallback.

Installing the hook

Create .git/hooks/pre-commit with executable permissions. The hook runs:

sg docker -c "docker compose exec -T api-server alembic heads"

and blocks if more than one (head) line is found.

5a.6 Pre-deploy schema verification

Before deploying any backend update that includes migration changes, run the schema comparison tool. This is a mandatory gate — do not deploy if it reports differences.

Verify models match the local database

sg docker -c "docker exec koinonia_api python /app/scripts/compare_schemas.py"

Expected output:

  RESULT: MODELS AND DATABASE MATCH

If it reports differences, there are missing migrations. Run --autogenerate to generate them.

Verify local database matches GCP (one-time or periodic audit)

This compares the actual column-by-column schema between your on-premises Dev database and the GCP instance. Use this when you suspect drift or after recovering from a migration incident.

# 1. Dump local schema
sg docker -c "docker exec koinonia_api python /app/scripts/compare_schemas.py --dump" > /tmp/local_schema.json

# 2. Start Cloud SQL Proxy
cloud-sql-proxy --unix-socket /tmp/cloudsql koinoniacloud-490205:us-central1:koinonia-{id}-db &
sleep 3

# 3. Get DB password
GCP_PASS=$(gcloud secrets versions access latest --secret="koinonia-{id}-db-password" --project=koinoniacloud-490205)

# 4. Dump GCP schema
python3 backend/scripts/compare_schemas.py \
  --local "postgresql://koinonia:${GCP_PASS}@/koinoniacloud?host=/tmp/cloudsql/koinoniacloud-490205:us-central1:koinonia-{id}-db" \
  --dump > /tmp/gcp_schema.json

# 5. Compare
sg docker -c "docker exec koinonia_api python /app/scripts/compare_schemas.py --remote-json /app/scripts/gcp_schema.json"

Copy the GCP JSON into backend/scripts/ temporarily so the Docker container can access it (the container's filesystem is isolated). Remove it after comparing.

Expected output: RESULT: SCHEMAS MATCH

At scale: hundreds of church instances

When Koinonia Cloud reaches hundreds of churches, each one has its own Cloud SQL database. You cannot manually verify every instance. The safety model is:

  1. All instances run the same Docker image — same Alembic migration files, same code
  2. alembic upgrade head runs automatically on every startup — new migrations apply without manual intervention
  3. Migrations are idempotent — if a container restarts mid-migration, the retry succeeds
  4. --autogenerate prevents missed columns — the tool diffs models vs DB, not humans
  5. compare_schemas.py catches drift before deploy — run it against Dev, and if Dev matches models, every church will too

The risk surface is: Dev works → GCP Test works → all churches work.

5a.7 Checking migration status

To verify which revision a GCP database is at, connect via Cloud SQL Proxy:

# 1. Start the proxy (Unix socket -- avoids port conflicts)
kill $(pgrep cloud-sql-proxy) 2>/dev/null; sleep 1
~/bin/cloud-sql-proxy koinoniacloud-490205:us-central1:koinonia-{id}-db \
    --unix-socket /tmp/cloudsql &
sleep 2

# 2. Get the DB password
gcloud secrets versions access latest --secret="koinonia-{id}-db-password" \
  --project=koinoniacloud-490205 && echo ""

# 3. Check current revision
PGPASSWORD='<password>' psql \
  -h /tmp/cloudsql/koinoniacloud-490205:us-central1:koinonia-{id}-db \
  -U koinonia -d koinoniacloud \
  -c "SELECT version_num FROM alembic_version;"

The output should show the current head revision. If it shows nothing or an old revision, the backend may not have started successfully — check Cloud Run logs.

Local Docker

sg docker -c "docker compose exec api-server alembic current"
sg docker -c "docker compose exec api-server alembic heads"
sg docker -c "docker compose exec api-server alembic history --verbose"

5a.8 Troubleshooting

Multiple heads ("ERROR: Multiple head revisions")

Cause: Two developers or agents created migrations in parallel (both point to the same down_revision).

Fix:

sg docker -c "docker compose exec api-server alembic merge heads -m 'merge_parallel_migrations'"

Commit the generated merge file.

"Column already exists" or "Table already exists"

Cause: A migration ran partially (container crashed mid-migration), then retried. The DDL succeeded on the first attempt but Alembic didn't record completion.

Fix: This shouldn't happen if migrations follow the idempotency patterns in Section 5a.4. If it does happen, add the missing _column_exists / _table_exists guard to the failing migration, commit, and redeploy.

Revision ID collision

Cause: Revision IDs were hand-crafted instead of auto-generated by alembic revision.

Incident (2026-04-12): Hand-crafted IDs using a rotating hex pattern (a1b2c3d4e5f6, b2c3d4e5f6a7, ...) collided — e5f6a7b8c9d0 was used for two different migrations. Alembic forked into two heads, the deploy skipped the cm_override_group_id migration, and the families endpoint crashed on GCP because the column didn't exist.

Prevention: Always use alembic revision -m '...' inside Docker to generate files. Never use --rev-id. The auto-generated hash (e.g., d7d591ed0df4) is unique and collision-proof.

Migration skipped but version advanced

Cause: Alembic recorded the revision as applied (wrote to alembic_version) but the actual DDL didn't execute — typically due to a duplicate revision ID creating a fork that Alembic silently resolved by skipping one branch.

Diagnosis:

  1. Check alembic_version — it will show the head revision
  2. Check information_schema.columns — the expected column will be missing
  3. Compare: if the version says "done" but the column doesn't exist, a migration was skipped

Fix: Create a new backfill migration that idempotently adds the missing column(s).

Migration file edited after deploy — column missing on GCP

Cause: A migration was deployed to GCP and ran successfully. Then the migration file was edited locally to add more operations. The local database was patched with a manual ALTER TABLE to match. On the next deploy, Alembic sees the revision is already stamped in alembic_version and skips it entirely — the new operations never run.

This is the most dangerous Alembic failure mode because everything looks correct locally: the version is at head, the columns exist, alembic heads shows one head. The only way to catch it is with the schema comparison tool.

Incident (2026-04-13): Migration c4d5e6f7a8b9 was deployed to GCP with grade_cutoff_year only on event_templates. The file was later updated to also add the column to church_events, and a manual ALTER TABLE was run on the local Docker DB. GCP never got the church_events column. The Events tab returned 500 errors on every request.

Prevention:

  • Never edit a migration file after it has been committed. Create a new migration instead.
  • Never run manual ALTER TABLE on the local Docker DB. If the migration is wrong, fix the migration file before it's deployed, or create a new one.
  • Run compare_schemas.py before every deploy. It will catch the mismatch.

"Can't locate revision"

Cause: The alembic_version table references a revision ID that doesn't exist in the migration files (possibly deleted or renamed).

Fix: Never delete or rename existing migration files. If a migration needs to be superseded, create a new one that undoes or replaces its work.

Index migration hangs on Cloud Run deploy

Cause: Plain op.create_index() takes AccessExclusiveLock on the target table. During a Cloud Run blue-green deploy, the OLD revision keeps serving traffic for the entire new-revision startup window; the OLD revision's connections hold AccessShareLock on the same tables, blocking the new revision's CREATE INDEX. After 4 minutes, Cloud Run's startup probe times out and kills the new revision — but the queued CREATE INDEX has been added to the postgres lock queue and stays there. Each subsequent deploy attempt adds another zombie.

Incident (2026-05-02): PR #9 added five op.create_index(...) statements (FK-column indexes for cleanup performance). Three deploys all hung at the same line. Direct DB inspection via cloud-sql-proxy showed: the user-clicked “Clean Up Empty Family Records” DELETE had been running for 2.5+ hours (slow because of the missing indexes), holding all the locks the deploys needed. Six zombie CREATE INDEX queries from failed deploys sat in the queue behind it. Cleanup required manually terminating all stuck sessions, applying the indexes via psql, and stamping alembic_version forward.

Prevention: For any migration that creates indexes, use the CONCURRENTLY form inside an autocommit block. PostgreSQL's CONCURRENTLY uses a non-blocking strategy (longer build, no exclusive lock — coexists with concurrent queries):

def upgrade() -> None:
    # Each statement runs in its own transaction; CONCURRENTLY forbids
    # being inside an explicit transaction.
    with op.get_context().autocommit_block():
        op.execute(
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_individuals_family_id "
            "ON individuals (family_id)"
        )
        # ... one statement per index

def downgrade() -> None:
    with op.get_context().autocommit_block():
        op.execute("DROP INDEX CONCURRENTLY IF EXISTS ix_individuals_family_id")
Caveat: CONCURRENTLY can still hang if a long-running client transaction is open on the target table. CONCURRENTLY waits for transactions that started before its own to complete. Quick concurrent queries don't block it — only long ones do. See Section 7b for how to identify and terminate stuck client transactions when this happens.

5a.9 Lessons learned — why autogenerate is mandatory

This section exists so future administrators understand why these rules are so strict. Every rule in Section 5a.2 was written because the opposite was tried and failed.

The promise vs. what happened

Alembic was adopted on 2026-04-06 specifically for its --autogenerate capability. However, --autogenerate was never actually used. For two weeks (2026-04-06 through 2026-04-13), every migration was hand-written.

What went wrong

Incident Date Root cause Would autogenerate have prevented it?
Revision ID collision (e5f6a7b8c9d0 used twice) 2026-04-12 Hand-crafted IDs using a rotating hex pattern Yes — autogenerate creates unique hash IDs
cm_override_group_id missing on GCP 2026-04-12 Fork caused by ID collision skipped the migration Yes — no collision, no fork, no skip
church_events.grade_cutoff_year missing on GCP 2026-04-13 Migration edited after deploy, local DB patched with ALTER TABLE Yes — autogenerate would have included both tables in the original migration
9 columns with wrong types (JSON vs JSONB) Pre-Alembic Drift from the pre-Alembic manual SQL era Partially — autogenerate would detect type mismatches on the next run

The cost

Each incident caused the GCP test instance to return 500 errors on critical endpoints (Events, Families, Check-in). The errors appeared as CORS failures in the browser because FastAPI's error responses don't include CORS headers, making them harder to diagnose. Each incident required emergency backfill migrations and redeployments.

At scale with hundreds of church instances, a single missed column would brick every church simultaneously.

What about the old database/*.sql files?

The database/ directory contains the manual migration scripts used before Alembic was adopted. They are kept as a historical reference only. Do not run them on any instance. The Alembic chain root (0001_bootstrap_baseline) already incorporates all of their changes. The previous database/init.sql seed file was deleted on 2026-05-07 in favor of an Alembic-owned seed migration — see Section 5a.10.

5a.10 Seed data ownership — what every new church starts with

As of 2026-05-07, Alembic owns both the schema AND the seed data for every Koinonia Cloud church. Provisioning a new operational church is a single command (alembic upgrade head on first container startup) that produces a fully usable database with all platform defaults already in place. No init.sql, no manual seed scripts, no separate startup logic for a new instance.

Why this matters

Before this change, schema and seed data were spread across three sources:

  • database/init.sql — ran via Postgres' docker-entrypoint-initdb.d hook on local Docker. Cloud SQL never runs this script, so any seed data here was missing on every GCP instance.
  • _seed_database() in backend/app/main.py — ran on every container startup, gated by if count == 0. Worked, but split the source of truth.
  • Manual psql sessions — used at least once (2026-04-30) to re-seed spiritual_gifts and skills on baylife-test when those tables were silently empty.

That patchwork made “what does every church start with?” impossible to answer from one place, and broke fresh-volume CI runs because init.sql tried to INSERT into tables that Alembic hadn't created yet. Migration c2d7c86cf2a4_seed_platform_reference_data consolidated everything into Alembic.

Inventory: what gets seeded on a fresh church DB

Table Rows What it is Migration
church_event_types 14 Sunday Service, Children's Ministry, Life Group, etc. — the calendar event taxonomy c2d7c86cf2a4
org_positions 14 Senior Pastor, Associate Pastor, Operations Director, Connections Director, etc. c2d7c86cf2a4 + renames in 8656fe15469a
volunteer_roles 7 Children's Ministry Volunteer, Welcome, Security, Life Group Leader, Bible Study Leader, etc. c2d7c86cf2a4 + renames in 8656fe15469a
volunteer_role_prerequisites 23 Application, Interview, Background Check, CPR Certification, Elder Approval, etc. — per role c2d7c86cf2a4
funds 3 General, Building, Missions c2d7c86cf2a4
accounts 39 Standard nonprofit chart of accounts (1000s Assets, 2000s Liabilities, 3000s Equity, 4000s Revenue, 6000s Expenses) c2d7c86cf2a4
income_categories 6 Tithes & General Giving, Building Fund Gift, Missions Gift, Special Offering, Merchandise Sale, Event Ticket c2d7c86cf2a4
class_education 8 New Member Class, Baptism Class, Marriage Enrichment, etc. c2d7c86cf2a4
spiritual_gifts 16 Prophecy, Serving, Teaching, Exhortation, Leadership, etc. — surfaced on the Talents pane of PersonDetailModal c2d7c86cf2a4
skills 19 Carpentry, First Aid & CPR, Counseling, Cooking, etc. — community-resilience catalog on the Talents pane c2d7c86cf2a4
scriptures 92 Curated verses for the random-verse rotator on the member Welcome tab c2d7c86cf2a4
pastor_notes 1 Welcome letter from The Koinonia Team c2d7c86cf2a4
groups 4 Demo groups so the UI isn't empty on day 1 (a church can rename or delete freely) c2d7c86cf2a4
event_templates + sections + groups + slots 1 / 4 / 16 / 1 "Children's Ministry Sunday Service" template (renamed from "Children's Ministry Service" in 8656fe15469a) c2d7c86cf2a4
event_templates + sections + groups + slots 1 / 4 / 16 / 43 "Vacation Bible School" template — full grade-filtered, 4-color-team structure with all volunteer slots c1ed808f106b
volunteer_roles 23 Worship & Arts positions: 14 band and vocal positions under "Worship Arts Volunteer" and 9 production positions (sound, lights, lyrics, cameras, video, livestream, stage) under "Tech Team Volunteer", all in the Worship & Arts area. New churches only (a database with nobody in its directory yet); an existing church adds them with "Add the standard Worship & Arts positions" in Volunteers › ⚙️, behind the studio flag 340c054f6d87
event_templates + slots 1 / 15 "Sunday Worship Service" template: band, production, security and welcome seats (new churches only) 340c054f6d87
widget_definitions 11 Welcome-tab staff widget catalog (Today's Events, This Sunday's Roster, Birthdays, etc.) 31b6b1509b58
biblical_sites 100 Bible Atlas curriculum locations (member-facing, feature-flag-gated by BETA_FEATURE_BIBLE_ATLAS_USERS) 42d4532046e2
bible_stories + bible_site_stories 37 / 109 Narrative groupings of biblical sites (Old & New Testament tour mode) 4bf73528c9a5

Total: ~430 platform-default rows across 17 tables, every new church gets identically.

What does NOT get seeded automatically

  • SuperAdmin user. Created from the ADMIN_EMAIL and ADMIN_PASSWORD environment variables (per-church, set during provisioning) by _seed_database() in main.py. This is intentionally provisioning-time logic, not part of Alembic.
  • Church profile. The church_profile row is seeded from the get-started form data by the platform's POST /api/admin/applications/{id}/provision call — church name, address, timezone, etc. are per-church identity, not platform defaults.
  • Report templates. Still seeded by seed_report_templates.py at app startup (separate upsert pattern from the rest; out of Alembic scope for now).

The defensive backstop in _seed_database()

The _seed_database() function in backend/app/main.py still runs on every container startup, but every block is now guarded by if count == 0 AND emits a BACKSTOP: WARN log if it fires. In steady state on every church the function is silent — Alembic has already seeded the data. If a BACKSTOP: log appears, that's a signal that an Alembic seed missed something and a follow-up migration is needed. The function is kept as belt-and-suspenders for the first 2–3 operational church provisionings; once it has stayed silent across multiple deploys, it can be retired.

How to add a new platform-default seed

  1. Decide the table and the rows. Example: a new "Mens Breakfast Group" template type.
  2. Generate an Alembic revision: alembic revision -m 'seed_mens_breakfast_template'.
  3. Edit the migration to use idempotent INSERTs: ON CONFLICT DO NOTHING if the table has a unique natural key (slug, code, name), or WHERE NOT EXISTS if it doesn't.
  4. Test on a fresh DB locally: alembic upgrade head against a brand-new database and verify row counts. pytest -m migration exercises the full chain.
  5. Test on the existing dev DB: re-run alembic upgrade head — should be a clean no-op (idempotent).
  6. Commit and deploy. Existing churches pick up the seed on next backend deploy; new churches get it as part of their initial bootstrap.

5b. Automated Testing

Koinonia Cloud has a 220-test automated test suite (219 active + 1 conditionally skipped) that runs on every push, on every PR, and (manually triggered) after every deploy. This section is the platform administrator's reference for the testing machinery: what runs when, what it reports, and what to do when something fails.

The canonical lists live in the koinonia-cloud repo:

5b.1 The three-gate model

Every code change passes through up to three independent test gates before it can affect a real church. Each gate has a different cost/coverage trade-off, and each catches a different class of bug.

Gate Where When it runs What it catches
A — Local pre-push Your laptop, before git push Manual (developer discipline) Obvious unit-level regressions before they hit anyone else
B — CI on push GitHub Actions Test workflow. Results mirrored to Command Center → Quality tab. Automatic on every push to main or feature/** and every PR Schema drift, integration regressions, frontend build errors, broken E2E flows. The gate that emails you on failure. Quality tab is silent on success but turns the chip amber if no run has happened in 24h.
C — Post-deploy smoke GitHub Actions Post-Deploy Smoke workflow. Triggerable from Command Center → Quality tab "Run Smoke Test" button. Manual trigger after each deploy — one click in Command Center, or fall back to GitHub Actions UI Whether a deployed Cloud Run instance is actually serving traffic correctly. See Section 6a. Quality tab chip turns amber if no Gate C run has happened in 7 days — a silent post-deploy queue that nobody verified.
D — Per-church probe (Future) Cloud Scheduler → per-church dispatch, mirrored to Command Center. (Future) auto-fires on schedule against every operational church (Future) per-church post-deploy verification at scale. Step 6 of the plan_test_command_center.md roadmap; not yet wired.
The mental model: Gate A is your sanity check. Gate B is GitHub's sanity check on your behalf. Gate C is the real-world sanity check. If all three are green, the deploy is verified end-to-end.

5b.2 Gate A — Local pre-push tests

Run from your laptop before pushing. Catches the obvious before it reaches the email gate. Fast feedback (under 30 seconds) for the most common failure modes.

The fast subset (run in <5 seconds)

# Backend pure-logic tests: RBAC matrix, schema validators, etc.
sg docker -c "docker exec koinonia_api pytest -m unit"

# Frontend pure-logic tests: getApiBase URL resolution, etc.
cd frontend && npm test

Both run inside their existing Docker containers and require no extra setup. You should run these before every push.

The full backend suite (run in ~90 seconds)

sg docker -c "docker exec -w /app \
  -e TEST_DATABASE_URL=postgresql://koinonia:password123@postgres-db:5432/koinoniacloud_test \
  -e SECRET_KEY=test-secret \
  koinonia_api pytest tests/"

Runs unit + integration + migration tiers against the dedicated test DB (koinoniacloud_test, which the conftest creates automatically). Identical to what CI runs in Gate B — if this passes locally, Gate B will pass too.

5b.3 Gate B — CI on push (the email gate)

The single most important gate from a platform administrator's perspective: this is the workflow that emails you when something breaks. Defined in .github/workflows/test.yml. Fires automatically on every push to main or feature/** and every pull request.

What runs in Gate B

Fires on every push to main or feature/**, on every pull request to main, and on demand (Run workflow). A newer push to the same branch cancels the run in progress. Six jobs — five run in parallel; E2E waits for Backend and Frontend to pass and, since 2026-09-09, runs only on pull requests and manual dispatches (it brings up the whole compose stack, which is too slow to pay for on every push to main).

Job What it does Typical duration Test count
PII guard (tracked spreadsheets) Fails if any spreadsheet/CSV export of member data is tracked in git (the 2026-09-08 purge must never recur) ~10 sec —
OpenAPI contract (docs/openapi.json is current) Regenerates the API's OpenAPI document with backend/scripts/export_openapi.py and fails when the committed docs/openapi.json is stale — the contract the web app's generated types and the iOS check-in app are held to ~1 min 667 paths
Backend (pytest) Spins up an ephemeral PostgreSQL 15 (pgvector image), runs pytest tests/ — unit, integration, and migration tiers 5–6 min ~450 tests
Frontend (vitest) Runs npm test in jsdom — pure JavaScript/TypeScript unit tests ~30 sec 47 tests
Type check (mypy, changed lines) mypy over the backend, reported only for lines the push changed ~45 sec —
E2E (Playwright) Brings up the full docker compose stack (postgres + api + web), mints the e2e bearer tokens (backend/scripts/mint_e2e_tokens.py), then runs the Playwright suites: smoke, the Ouch-report flow and the Sunday check-in flow. PR and manual runs only; gated on Backend and Frontend passing. 3–5 min 6 tests

The email you get on failure

GitHub sends an email to the pusher when any job fails. The subject looks like:

[billburnham/koinonia-cloud] Run failed: Test - main (abc1234)

The email body shows a green check next to passing jobs and a red X next to failures. Click the "View workflow run" button to open the full run output in the Actions tab. Each job has its own collapsible log; click into the failing one to see the error.

Successful runs are silent — no email, no notification. If you don't get an email within ~3 minutes of a push, that's the all-clear.

Important: Gate B does not block deploys. You can still gcloud builds submit on a red main. CI is informational; the discipline of "don't deploy when CI is red" is on you. The good news: Gate B catches frontend production-build errors that npm run dev tolerates — if the email comes in red, the next deploy probably would have failed at the build stage anyway.

5b.4 Gate C — Post-deploy smoke

Run manually after every deploy. The fast path: Command Center → Quality tab → pick target → Run Smoke Test. The new run shows up in the status strip 30–90 seconds later. See Section 6a for the click-by-click and the GitHub-UI fallback when Command Center is unreachable, and Section 17.4 for the Quality tab anatomy.

5b.5 What the suite covers

The 220 tests are organized into five tiers. The full per-test breakdown is in docs/test_inventory.md; this table is the high-level summary.

Tier Count What it validates
Backend unit 34 Pure logic: RBAC role × module × level matrix, backup-export registry drift, CM check-in window math (the [start − 3h, end + 20min] roster gate), and the input-whitespace strip contract pinning the shared BaseSchema config (Move A). No DB, no network. Fast (under a second).
Backend integration 159 Real PostgreSQL + FastAPI TestClient. Auth flows (login, refresh, role denial), individuals/families/groups/events CRUD, the leader-auto-volunteer-role logic, schema drift, seeded-row counts (17 tables), end-to-end CM check-in and volunteer-roster workflows, walk-in check-in + pickup code + checkout, CM override persistence, total-church backup round-trip including verification that all 93 registered tables appear in the export and that user passwords are preserved across restore, unified-import data ingest with provenance + idempotency, public-event registration including the member-match preflight privacy gate (preflight returns no PII even on a match) and the corruption gate (anonymous registrants cannot mutate canonical Individual records), the event-lifecycle workflow (create → submit → approve via both admin-bypass and staff-workflow paths), roster + volunteer-slot ordering rules (filled-before-open, fill-time order, slot_number tiebreaker), volunteer compliance gate (Background Check + Ministry Safe amber/red status, minor exemption), buddy-pair clustering (same-group invariant, walk-in auto-wrap), VBS series cross-night resolution (template_group_id mapping across nights, per-night overrides, "removed" sentinel, series-scoped buddy pair persistence), and the CM Roster propagation matrix (21 tests, 2026-05-19) — every combination of source-tier × target-tier × series/single-event for moves, assigns, removes, walk-in promotions, slot-note edits, cohort leader management, section coach moves, child-attendee moves (pre-reg + checked-in), family cohort cascades, and buddy break propagation. This is the regression net for the whack-a-mole bug class that previously kept surfacing one-off propagation failures on the CM Roster page; see the audit doc at docs/audit_roster_propagation.md in koinonia-cloud.
Backend migration 4 Fresh-DB upgrade, idempotency (run twice), latest-migration round-trip, plus the destructive-DDL AST scanner that fails CI on any unacknowledged op.drop_column/op.drop_table/op.alter_column(..., type_=...) in an upgrade() body. Catches the migration bug class that historically caused production outages on this codebase.
Frontend unit + component 20 getApiBase() URL resolution (SSR vs client, env-var override), plus PersonForm controlled-component contract (the capFirst auto-capitalize UX rule, the showExtendedFields toggle, the hideRoleInFamily flag) and VisitorEntryModal validation gate + API submit flow (required-field gate, whitespace-only rejection, success and failure paths).
E2E smoke 3 Read-only health probes against a deployed environment: /api/health, /, homepage console-error check. Run automatically in CI against the local Docker stack (Gate B) and manually after deploy via Gate C.
Total 220 ~240 seconds backend suite + ~1 second frontend in CI (the 5 backup round-trip tests dominate at ~190s for their alembic-upgrade-head bootstrap; everything else runs in ~100s; the propagation matrix harness adds ~7s).

5b.6 What to do when tests fail

This is the action table for platform administrators: given a specific failure signal, what's the fix? Listed in roughly decreasing order of how often each shows up in practice.

Failure signal What it means What to do
E2E job fails at "Bring up application stack" with npm run build exit code 1 Production TypeScript build failed. The strict npm run build is catching something that the lenient npm run dev tolerates — usually a "block-scoped variable used before declaration" or a missing import. The deployed frontend would have failed too. Click into the run log. Find the line beginning Type error:. Open the named file in your editor, fix the error, push the fix. CI re-runs automatically.
Backend job fails on test_models_match_test_db_schema Schema drift — models.py declares a column that doesn't exist in the migrated test DB, or vice versa, or types don't match. Per CLAUDE.md this is the failure class that has caused every prior production outage on this codebase. The error names the table and column. Either:
  1. If models.py was changed and no migration was added: run alembic revision --autogenerate -m "describe change", review the file, push.
  2. If a migration changed the schema but the model wasn't updated: edit models.py to match.
Backend job fails on test_platform_seed_row_count[table-n] A seed migration was edited (rows added/removed) but the expected row count in tests/integration/test_seed_data.py wasn't updated. Two cases:
  1. If the seed change is intentional, update the constant in EXPECTED_SEED_COUNTS in the same PR. The pin is meant to track real changes, not block them.
  2. If the row delta is unexpected, the seed migration has a bug — revert and write a follow-up.
Backend job fails on test_upgrade_head_succeeds_on_fresh_database The full migration chain crashed when run against an empty database. Means a new church cannot be provisioned in its current state. Read the traceback. Almost always the latest migration: missing column in an ALTER, FK reference to a non-existent row, etc. Do not deploy until this is green — new church provisioning is broken.
Backend job fails on test_upgrade_head_is_idempotent or test_latest_migration_round_trips The latest migration either crashes on second run (non-idempotent) or doesn't downgrade cleanly. Per CLAUDE.md: a church OOM-restarting mid-migration must be able to retry without bricking its DB. Edit the failing migration:
  • For idempotency: wrap each op.create_table in if not _table_exists(...) and each op.add_column in if not _column_exists(...).
  • For round-trip: write or fix the downgrade() function so it reverses upgrade().
Backend job fails on a specific endpoint test (e.g. test_create_group_with_leader_auto_adds_membership_and_role) A behavior change in the endpoint broke its test. Either the test pin is stale (intentional product change) or the endpoint regressed (bug). Read the assertion that failed. Match the new endpoint behavior against the test expectation. If the new behavior is correct, update the test in the same PR. If the test is correct, the endpoint has a bug — fix it.
Frontend job fails on api.test.ts The getApiBase() URL resolution logic changed in a way that breaks SSR or client-side fallback. Open frontend/src/lib/api.ts and the matching test. If the change to getApiBase() is intentional, update the test. If unintentional, revert api.ts.
E2E job fails on Playwright assertion (after the stack came up successfully) The deployed-app smoke test failed against the local CI stack. Usually means the app does run but is missing an expected response (e.g. /api/health returns 500 instead of 200). Download the Playwright report artifact from the run page. Look at the failed test's screenshot and trace. Reproduce locally with cd e2e && npm run test:smoke against your Docker stack.
Gate C smoke against baylife-test fails The deployed environment is unhealthy. Either the deploy didn't actually succeed, or Cloud Run is not routing traffic to the new revision, or a runtime config (env var, secret) is missing. Run gcloud run services describe koinonia-baylife-test-{api,web} --region=us-central1 --format='value(status.conditions)' to see Cloud Run's status. Check the api service's recent logs: gcloud run services logs read koinonia-baylife-test-api --limit=50. Common fixes: rerun the deploy, verify --update-secrets matched, run gcloud run services update-traffic --to-latest.
Backend job fails on test_export_zip_contains_csv_for_every_registered_table The backup export is silently dropping a table from the ZIP — meaning a restore from this backup would NOT bring that table's data back. This is silent data loss on every backup taken until it's fixed. Almost always: a model added to models.py was not registered in ALL_TABLES in backend/app/api/endpoints/export.py. Open backend/app/api/endpoints/export.py, find the ALL_TABLES list, add an entry for the missing table: ("table_name", ModelClass, set()). Re-run the test — should go green. Also re-run test_backup_registry_in_sync (unit) which catches the same gap from the model side.
Backend job fails on test_user_password_preserved_through_full_backup_roundtrip Severe. A backup taken with redact_credentials=False (the total-church-backup mode) is not preserving user passwords through restore. Every member on a restored church loses the ability to log in with their existing password. They'd have to use password reset. Read the traceback. Likely culprits: the bcrypt hash got CSV-mangled (newlines / quotes broke the field), the redaction sentinel is incorrectly applied even with redact_credentials=False, or the CSV reader is trimming whitespace from the hash. Do not deploy a backup feature change until this is green.
Backend job fails on test_redact_credentials_replaces_password_hash_with_sentinel The OPPOSITE failure mode: a backup taken with redact_credentials=True (the default, sharing-safe mode) is leaking real bcrypt hashes instead of replacing them with the redaction sentinel. This is a credential disclosure risk — an export shared with an accountant or auditor would expose every member's password hash. Audit _table_to_csv() in export.py and the redact_pwd branch. Confirm the sentinel constant REDACTED_PASSWORD_SENTINEL is being written. Until fixed, do not let anyone share a backup outside the team.
Backend job fails on a CM-specific test (test_walkin_checkin_*, test_pickup_code_*, test_checkout_*, etc.) The Sunday-morning critical path has a regression. Walk-in check-in for visitor families, pickup code lookup, child checkout, or the persistent classroom override (cm_override_group_id) is broken. This is the path that hurts most when it breaks live — volunteers can't check kids in or pick them up. Read the assertion. The test names in tests/integration/test_workflow_cm_depth.py describe the exact behavior asserted (e.g. allergy notes persisted, pickup code case-insensitive, checkout marks checked_out_at). If the change to the endpoint is intentional, update the test; if not, revert the endpoint change. Never deploy on Saturday with a red CM test.
Backend job fails on test_anon_public_post_with_match_token_does_not_mutate_matched_individual SEVERE. The corruption gate has fallen. An anonymous registrant submitting a public event registration with altered email / phone / address can now overwrite the matched Individual's canonical contact info. This is a directory-tampering attack surface — any member's record can be rewritten by anyone with their name + the public event URL. Read the diff that produced this failure. The unauthenticated path (POST /events/{id}/registrations/public) must NEVER call db.commit() on a mutation to Individual rows. Submitted contact info goes into the registration's audit data only. Block any deploy with this test red until the write path is removed.
Backend job fails on test_preflight_response_contains_no_pii The privacy gate has been weakened. The member-match preflight response is now leaking PII fragments (name, email, phone, address) back to the unauthenticated caller. An attacker can now confirm member identity by trying name + email combos and reading the response. This violates the privacy-by-construction design Bill specifically called out. The preflight response shape must be exactly {match_token, skippable_fields}. Any new keys or any value containing PII is a regression. Revert the change that added them. The skippable_fields array is a list of field NAMES like ["email", "phone"], not values.
Backend job fails on test_preflight_response_time_floor_is_at_least_500ms The 500ms minimum response time on the preflight endpoint has been removed. An attacker can now distinguish "match found" from "no match" by measuring response time, leaking which emails are in the church directory. Re-add the time.sleep(0.5 - elapsed) guard at the bottom of registration_preflight() in backend/app/api/endpoints/event_registrations.py.
Backend job fails on test_process_commit_then_re_import_does_not_double_create The unified-import idempotency property is broken. Re-importing the same CSV is now creating duplicate Individuals. Every double-click on the import button now doubles a church's directory. An accidental re-import during onboarding becomes a data-cleanup project. The matching logic uses legacy_individual_id (sourced from the CSV's person_id_column when id_namespace=same_system) to detect existing rows. Audit backend/app/api/endpoints/unified_import.py:_process_people() for the legacy-id lookup and ensure it's not silently bypassed. Catch this BEFORE a real church hits it — cleaning up duplicate Individuals across joined Families is hours of work.

The "deprecation warnings" annotation

Sometimes a run is green but shows a yellow "1 annotation" badge. This is GitHub flagging that an Action version we use is approaching deprecation (e.g. "Node.js 20 actions are deprecated, will be forced to Node 24 starting June 2nd, 2026"). Not urgent — bump the action versions in .github/workflows/test.yml when convenient. The run still succeeded.

5b.7 Adding a new test

The recipe for extending coverage. Pick the tier that matches what you're testing:

  • Pure logic / RBAC matrix → copy the pattern in backend/tests/unit/test_permissions.py
  • API endpoint behavior → copy the pattern in backend/tests/integration/test_groups.py (uses the as_superadmin / as_staff / as_member auth fixtures)
  • End-to-end backend workflow (multi-step API flow) → copy backend/tests/integration/test_workflow_cm_checkin.py
  • A new seed-data pin → add a row to EXPECTED_SEED_COUNTS in backend/tests/integration/test_seed_data.py
  • Frontend pure logic (utility, formatter) → copy frontend/src/__tests__/api.test.ts
  • E2E read-only smoke (UI flow safe to run against shared infra) → copy a @smoke-tagged test in e2e/tests/smoke.spec.ts

Workflow:

  1. Copy a similar test, change the assertion, save.
  2. Run locally to verify it actually catches the bug it's supposed to: sg docker -c "docker exec koinonia_api pytest tests/integration/test_your_file.py -v".
  3. Push. Gate B re-runs everything; if your test passes locally and on CI, you're done.
  4. If you added a test for a new endpoint or migration, also update docs/test_inventory.md so future administrators see it in the canonical list.

5b.8 What this suite does NOT catch

Honest limits, so administrators don't develop false confidence:

  • Most frontend rendering bugs — component tests now exist for PersonForm and VisitorEntryModal (Phase 2.5.E, 2026-05-14), but the other ~83 frontend components don't yet have component tests. The E2E smoke loads the homepage and checks for console errors, but does not click through every modal or validate visual output. A broken modal outside the two tested components can still ship without CI flagging it.
  • The long tail of API endpoints — the daily-use surface (people/families/groups/events/registration/check-in/volunteers/CM roster/series cross-night/buddy-pair) is covered after the Phase 2.5 work; Communications (SMTP/SMS/webhooks), Finance (giving/payables/sales), and Reports remain uncovered. See docs/automated_test_plan.md Phase 3 for the queue.
  • Real Playwright browser-driven E2E flows — the E2E suite is API-only smoke. Component tests now cover the controlled-component contracts (input handling, validation gates) but don't exercise full click-through journeys in a real browser. Deferred until the UI stabilizes post-PWA work.
  • Per-church post-deploy probes — Gate D in the model. After a fleet rollout to many churches, there's no automated probe of each instance. Admins still need to spot-check individual operational churches manually. Phase 3.F candidate; defer until fleet grows past ~10 churches.
  • Performance regressions — nothing in the suite measures response time. A change that makes /api/individuals 10x slower passes CI silently. Phase 3.C candidate (k6 or locust against the 5 highest-traffic endpoints with a >20% latency regression gate).

None of these are bugs in the test suite — they're known gaps that reflect deliberate scope choices. Track them in docs/automated_test_plan.md and prioritize as the platform grows.


6a. Updating an Existing Deployment

Backend-only update (Python code changes)

# Build and push new backend image
gcloud builds submit backend \
  --config=backend/cloudbuild.yaml \
  --substitutions="_IMAGE=us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-api" \
  --quiet

# Deploy new revision (all churches share the same image)
gcloud run deploy koinonia-{church-id}-api \
  --image="us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-api:latest" \
  --region=us-central1 \
  --quiet

Frontend-only update (Next.js code changes)

BACKEND_URL=$(gcloud run services describe koinonia-{church-id}-api \
  --region=us-central1 --format="value(status.url)")

gcloud builds submit frontend \
  --config=frontend/cloudbuild.yaml \
  --substitutions="_IMAGE=us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-frontend,_API_URL=${BACKEND_URL}" \
  --quiet

gcloud run deploy koinonia-{church-id}-web \
  --image="us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-frontend:latest" \
  --region=us-central1 \
  --quiet

Full redeploy (use deploy.sh)

./deploy/deploy.sh --church-id {church-id}

deploy.sh is idempotent — it skips resources that already exist and only creates what's missing.

What deploy.sh enforces since 2026-09-09

Clean working tree (or --allow-dirty)

The images are built from the working tree, not from a commit. On 2026-09-09 a production deploy quietly shipped a batch of uncommitted, still-under-test changes that happened to be on disk when the build ran. deploy.sh now refuses to start when git status shows any change — tracked or untracked — under backend/ or frontend/ (the two build contexts), and lists them. Commit or stash first. --allow-dirty builds anyway and prints what is going out uncommitted, so it is a choice, not an accident. deploy/ itself is not checked; scripts there never enter an image.

Every deploy also stamps DEPLOY_COMMIT=<short sha>[-dirty] on the API service beside LAST_DEPLOY, so the Command Center's Configuration Drift panel shows which commit each church actually runs.

Configuration check at boot

backend/app/core/settings.py is the registry of every environment variable the backend reads (a unit test fails if code reads one that is not declared there). At boot on Cloud Run the API refuses to serve when a load-bearing value is missing — DATABASE_URL, SECRET_KEY, CHURCH_ID, CORS_ORIGINS, PUBLIC_URL, GCS_BUCKET_NAME — so the new revision never becomes ready, the deploy fails with the reason in the log, and the previous revision keeps serving. A half-configured feature (Twilio with no number, one VAPID key, a Postmark token without a From address) only logs a warning naming what is missing; a feature being off must never take a church down. The boot log also lists which optional features are configured.

Pinned dependencies

backend/requirements.txt is now the full pinned set (every transitive package, exact versions) that the Dockerfile and CI install; backend/requirements.in is the short list humans edit. Until 2026-09-09 the requirements were unpinned, so each church image resolved whatever was newest on its build day and two churches provisioned a week apart could run different SQLAlchemy or Pydantic versions. To change a dependency: edit requirements.in, rebuild locally (docker compose build api-server), run docker exec koinonia_api pip freeze, paste the result over requirements.txt, run the full test suite, commit both files.

Worker job for export, backup and restore

deploy.sh now provisions a Cloud Run Job, koinonia-{id}-worker, from the same image as the API (step 8b), and sets WORKER_JOB on the API service. Starting an export, a Cloud SQL backup or a restore no longer spawns a thread inside the API container — which loses its CPU the moment the response returns and can be reaped mid-job — but starts one execution of the worker job (python -m app.jobs.run_one <job_id>): its own container, up to an hour, 4 GiB. The job's parameters (the passphrase above all) travel sealed in the export_jobs row, never as an execution argument. Watch executions under Cloud Run → Jobs → koinonia-{id}-worker; a failed execution also marks the job row phase=error so the UI stops polling.

A church deployed before this exists (no WORKER_JOB on its API service) keeps the old in-process behaviour until its next deploy.sh run. Restore progress is kept in blob storage (restores/{job_id}.progress.json) rather than any table, because a restore truncates and replaces every table — including the job table — while it runs.

API contract (docs/openapi.json)

koinonia-cloud/docs/openapi.json is the API as the backend actually serves it (667 paths), written by backend/scripts/export_openapi.py. CI regenerates it and fails when the committed copy is stale, so a route change is never invisible. Two consumers are held to it:

  • Web app — frontend/src/lib/api-types.d.ts is generated from it (npm run api:types); hooks/useApiQuery.ts types requests and responses from those definitions, so a renamed route is a type error, not a 404.
  • iOS check-in app — koinonia-checkin-ios/docs/koinonia-api-v1.json is a copy; scripts/check_api_contract.py there fails when any /api/… path in the Swift sources is missing from it (--refresh copies a fresh document from the sibling checkout). Run it before every TestFlight build.

After a backend route change: docker exec koinonia_api python /app/scripts/export_openapi.py /tmp/openapi.json && docker cp koinonia_api:/tmp/openapi.json docs/openapi.json, then npm run api:types in frontend/, and commit all three.

Which jobs the worker runs

Measured on baylife-test: a worker execution takes about two minutes to start (image pull plus Cloud SQL attach for a ~3 GB image) and then ran a full export in 28 s — the same export ran in 32 s in-process, and the modal sat at 2% for the two minutes. So by default only backup and restore go to the worker (long, and must not be interrupted); a plain export runs in-process as before, and an export that packs photos/documents goes to the worker because it can run for many minutes. WORKER_JOB_KINDS on the API service overrides the default (backup,restore) per church. While a worker execution is starting, the job's status reads “Starting a worker (about two minutes)…”.

Post-deploy verification (automated)

After deploying both services, deploy.sh automatically runs two verification steps:

  1. Traffic routing check — Confirms that 100% of traffic is routed to the latest revision. If a service is not routing traffic to its latest revision, the script auto-fixes it by running gcloud run services update-traffic --to-latest.
  2. HTTP health check — Sends a request to the frontend URL and the backend's /api/health endpoint. A 200, 307, or 308 is considered healthy.
Important: Always review the deploy output for warnings before considering a deployment complete. Lines starting with ⚠ indicate problems.

Post-deploy smoke tests (Gate C)

The deploy.sh health check above only verifies the services are reachable. After every deploy you should also run the Post-Deploy Smoke CI workflow, which exercises real endpoints against the deployed environment and uploads a Playwright report on failure. This is Gate C of the three-gate test model — see Section 5b — Automated Testing for the full model and what to do when each gate fails.

How to run it (preferred — Command Center)

  1. Finish your deploy as usual (deploy.sh or the manual gcloud builds submit sequence above).
  2. Open the Command Center and switch to the Quality tab.
  3. In the Trigger Smoke Test row at the top, pick the target environment from the dropdown (currently baylife-test; targets come from the GATE_C_TARGETS env var on the platform service).
  4. Click Run Smoke Test, confirm the prompt. The button disables for 60 seconds to prevent double-firing.
  5. Watch the status strip. A new chip for the target appears 30–90 seconds later, green or red. The strip auto-refreshes at 30s and 90s after dispatch — you don't need to mash Refresh.

The strip shows a 30-day pass-rate sparkline below each chip. Hover any square for that day's run count and pass rate. If a chip is amber with a "Stale" tag, no run has happened in the threshold window for that gate (24h Gate B, 7d Gate C) — passing-but-ancient is a yellow flag, not green.

How to run it (fallback — GitHub UI)

When the Command Center is unreachable, or when triggering against a target not yet in GATE_C_TARGETS:

  1. Open GitHub → Actions → Post-Deploy Smoke.
  2. Click the green Run workflow button (top right).
  3. Pick the target environment from the dropdown.
  4. Leave the actor field blank — it's only set by Command Center to attribute the run to the human operator. From the GitHub UI it falls back to github.actor.
  5. Click Run workflow. The job runs in 30–60 seconds and emails on failure.

Either path produces the same result: a green check or red X in the Actions tab, plus (if Command Center is configured with PLATFORM_INGEST_TOKEN) a new row in the Quality tab.

What the smoke workflow tests

Three read-only probes against the deployed environment:

  • GET /api/health → responds 200 with {"status": "healthy"} — verifies the api service is up, the database is reachable, and Alembic migrations finished
  • GET / → responds 200 with the welcome payload — verifies the api root is routing correctly through Cloud Run
  • Frontend homepage loads without console errors — verifies the web service built correctly, the JavaScript bundle parses, and there are no console.error calls from app code (third-party noise like extensions and favicons is filtered out)

All three tests are tagged @smoke in e2e/tests/smoke.spec.ts and are explicitly safe to run against shared infrastructure. They never mutate state.

Adding a new church to the smoke target list

When a new operational church is provisioned, add a case arm to the URL-resolve step in .github/workflows/smoke.yml. Get the deployed Cloud Run URLs first:

gcloud run services list \
  --filter='metadata.name ~ {church-id}' \
  --region=us-central1 \
  --format='value(metadata.name,status.url)'

Then in .github/workflows/smoke.yml, add the new option to the type: choice list AND a new case arm with the resolved URLs. Commit and push — the new church will appear in the workflow's target dropdown immediately.

Local fallback

Playwright specs that mutate data (incidents.spec.ts, checkin.spec.ts — the Sunday check-in flow) self-skip unless INCIDENTS_E2E_TOKEN / CHECKIN_E2E_TOKEN are set. CI mints one SuperAdmin bearer for both against its ephemeral stack; locally mint one with the one-liner in e2e/README-incidents.md. Never point them at a shared church.

If GitHub Actions is unavailable, you can run the same smoke tests from your laptop:

cd e2e
PLAYWRIGHT_BASE_URL=https://koinonia-{church-id}-web-{hash}-uc.a.run.app \
API_BASE_URL=https://koinonia-{church-id}-api-{hash}-uc.a.run.app \
  npm run test:smoke

(Replace {church-id} and {hash} with the actual values from gcloud run services list. Requires the koinonia-cloud repo cloned locally and Playwright installed via cd e2e && npm install && npx playwright install --with-deps chromium.)

When this catches problems: the smoke tests run against the built production frontend, which uses strict TypeScript and minified output. Bugs that npm run dev tolerates (e.g. "variable used before declaration") will fail the production build, and the smoke job will not even start because the deployed frontend won't load. Fix the build error in code, push, re-deploy, then re-run the smoke workflow.

Updating a secret value

printf 'new-value-here' | gcloud secrets versions add koinonia-{church-id}-{secret-name} \
  --project=koinoniacloud-490205 --data-file=- --quiet

# Force Cloud Run to pick up the new secret value by deploying a new revision
gcloud run services update koinonia-{church-id}-api \
  --region=us-central1 --quiet

6b. Exporting & Importing Church Data

12.0 Self-describing backups (architecture)

As of 2026-05-02, every backup ZIP is fully self-describing — it carries enough metadata to be restored to any Koinonia Cloud instance, regardless of whether the destination's schema matches the backup's schema. The principle: backup is complete, restore is complete. No silent column drops on either side.

What's in the ZIP:

  • {table}.csv — one CSV per backed-up table, with every column read from the live DB schema (not the SQLAlchemy model). Captures columns added by Alembic migrations even if the running app's models.py doesn't define them.
  • {table}.schema.csv sidecar — column-type metadata from information_schema.columns: data_type, character_maximum_length, numeric_precision, numeric_scale, is_nullable, udt_name. Sufficient to reconstruct PostgreSQL DDL for missing columns at restore time.
  • alembic_version.csv — the migration revision the source DB was at when the backup was taken. Always included regardless of whether the user chose “Export All” or “Select Tables”.
  • koinonia_version.txt — integer schema marker for compatibility checks.
  • Photos and person documents (when included).

12.0.1 Two artifacts: Export Data and Backup Database

A church has two different backups, on two different Admin cards, and the distinction matters most on the day something goes wrong:

Export Data (Admin → Export Member Data)Backup Database (Admin → Backup Database)
What it isOne CSV per table + schema sidecars + alembic_version.csv, optionally photos and documents, AES-256 ZIP (12.0)A pg_dump of the whole database produced by the Cloud SQL Admin API — every table, sequence, constraint, index and extension, exactly as Postgres holds it — wrapped in an AES-256 ZIP with manifest.json and README.txt
Who restores itThe church's SuperAdmin, in-app (12.2)Unbalanced Force only (12.2.1). There is deliberately no in-app restore: importing a dump means dropping the database the running app is connected to
PasswordsExcluded by default (redacted to an unusable placeholder; users reset via Forgot Password)Included — users keep their passwords after a restore
Photos & documentsIncluded when Also include photos & documents is ticked (a worker-job pack)Not included — the uploads bucket is versioned and recovered separately (10b)
Where it livesBrowser download; the copy in the church's uploads bucket (exports/) is swept after 6 hoursBrowser download koinonia-backup-<timestamp>.zip; the copy under dumps/ in the uploads bucket is swept after 6 hours. The unencrypted staging dump (dumps-staging/) is deleted the moment it has been wrapped
PassphraseMinimum 14 characters, typed twice, never stored — without it neither file can be opened, by the church or by us

Taking a Backup Database (SuperAdmin): Admin → Backup Database → enter and confirm the Backup passphrase → Create Encrypted Backup. The modal shows Creating database dump… (the export runs inside Cloud SQL, so the API container handles none of the data) then Encrypting…, and ends on Backup Created with a receipt: encrypted file size, dump size, schema revision, PostgreSQL version, time taken and the file's SHA-256 (verify a downloaded copy with shasum -a 256). Ask every church to keep one of these off-platform, on a schedule, with the passphrase somewhere the pastor can find it.

12.1 Export from a running instance

  1. Log in as SuperAdmin
  2. Go to Admin → Export Member Data (under Data & Structure Management); the Export Data window opens
  3. Enter the Export Passphrase twice (minimum 14 characters) — store it safely; the ZIP cannot be opened without it
  4. Under Backup contents leave every table selected for a full export (or choose tables); tick Also include photos & documents to pack the files into the ZIP instead of listing them in media_manifest.csv
  5. Click Export. A full table export runs in about half a minute in-process; a pack that embeds the files is handed to the church's worker job (koinonia-{id}-worker) and the modal says so while the worker starts (about two minutes)
  6. The modal switches to Export Complete with the filename and a passphrase reminder; click “I’ve saved my passphrase — Close”

The ZIP filename format is Koinonia_CSV_Mon_DD_YYYY.zip. Passwords are redacted unless redact credentials is switched off in the window.

12.2 Restore to any instance

  1. Log in to the target instance as SuperAdmin
  2. Go to Admin → Import Church Data → Restore from Backup
  3. Choose File (the .zip; anything over 10 MB is uploaded straight to GCS through a signed URL — the passphrase is never stored), then enter the passphrase
  4. Click Verify & Preview → — the ZIP is decrypted and parsed and a manifest appears: a Schema revision panel (Backup taken at vs This system is at; green check when they match, Schema version mismatch in amber when they differ), the Tables / Photos / Documents counts, and Table Contents with a row count per table
  5. Review it, then click Confirm & Restore Database →. The restore runs on the church's worker job: the modal reads Starting restore… for about two minutes while the execution starts, then follows the phases below. Closing the browser does not stop it
  6. Restore Complete shows the alembic transition and table count. A failure at any point rolls the whole restore back — the destination is left exactly as it was (verified on baylife-test, 2026-09-09)
What the round trip guarantees. tests/integration/ test_backup_roundtrip_production_shape.py seeds one awkward row into every registered table — '' in every NOT NULL text column, a 140,000-character text, unicode, arrays, JSON, UUIDs, foreign keys across the whole graph — exports it through the real path and restores it, and fails CI if any column changes. It exists because the first restore of a production-sized export (2026-09-09) hit three defects in one day that small fixtures could not see: the csv module's 128 KiB field limit, an empty NOT NULL subject restored as NULL, and ARRAY columns restored as lists of characters. An empty cell now restores as '' into a NOT NULL text column and NULL elsewhere; arrays are written as JSON.

Restore phases (in order, surfaced in the progress UI):

  1. Drop constraints — saves all FKs/checks for re-creation later
  2. Truncate tables — clears destination data
  3. Align schema with backup (new) — reads each table's {table}.schema.csv, runs ALTER TABLE ADD COLUMN IF NOT EXISTS for any column the destination is missing, with the correct PostgreSQL type. If the backup predates the schema-sidecar feature, columns are inferred from the CSV header and added as TEXT (data preserved, type fidelity degraded)
  4. Insert data — bulk insert in FK-safe order
  5. Backfill deferred FKs — circular references (parent_position_id, etc.)
  6. Reset sequences — advance serial sequences past max imported IDs
  7. Restore files — photos and documents into GCS or local volume
  8. Rebuild constraints — reapply saved FKs/checks
  9. Sweep empty family records (new) — idempotent cleanup of any orphan family rows the backup may have carried (older backups predating the dedup fix)
  10. Stamp alembic_version (new) — updates the destination's alembic_version row to the backup's revision IF that revision is recognized in the destination's migration files. This means future alembic upgrade head walks forward from the backup's revision, applying only newer migrations cleanly. Cross-branch restores (revision unknown to destination) leave alembic_version unchanged and log a warning.
Note: Passwords are excluded from exports for security. All imported user accounts will have their passwords replaced with an unusable placeholder. Users must reset their passwords via Forgot Password after a restore.

12.2.1 Disaster recovery: rebuilding a church under a new id

Scenario. church.koinoniacloud.com is compromised or destroyed and cannot be stood back up as itself; the church must come back as a brand-new instance (a new {newid}) with its data. Three routes, fastest and most complete first. All three end the same way: the church's staff sign in at https://{newid}.koinoniacloud.com.

Validation status. Every command below was checked against deploy.sh, secrets.sh, the platform code and gcloud's own syntax on 2026-09-09; the in-app screens were walked live. The sequence has not yet been executed end to end against a throwaway church id — do that rehearsal once, on a quiet day, before you need it.

Route A — clone the database (minutes; keeps everything, passwords included)

Use when the Cloud SQL instance (or its automated backups / PITR window) still exists in the project, which is the case for a compromised application rather than a deleted project.

# 1. Clone the database into the NEW church's instance name, optionally at a point in time
#    before the compromise (the PITR window is 7 days; automated backups are kept 30).
gcloud sql instances clone koinonia-{oldid}-db koinonia-{newid}-db \
  --project koinoniacloud-490205 [--point-in-time 2026-09-09T05:00:00Z]

# 2. Store the manual secrets for the new id (Anthropic key, admin email/password,
#    Postmark token + From address — the SAME Postmark server can serve the new id).
./deploy/secrets.sh --church-id {newid}

# 3. Deploy. Step 4 tolerates the existing instance and database; because no
#    koinonia-{newid}-db-password secret exists yet it SETS a fresh password on the
#    cloned instance's `koinonia` user; step 8a runs `alembic upgrade head` (a no-op
#    if the clone was at head); 9.5 maps {newid}.koinoniacloud.com in Cloudflare.
./deploy/deploy.sh --church-id {newid}

# 4. Bring the files across (photos, documents, event banners, church logo).
gcloud storage cp -r gs://koinoniacloud-490205-{oldid}-uploads/* \
  gs://koinoniacloud-490205-{newid}-uploads/

# 5. Protect the new instance, then remove the old church's traffic.
gcloud sql instances patch koinonia-{newid}-db --deletion-protection
./deploy/deprovision.sh --church-id {oldid}   # or pause it from the Command Center

Everything survives: people, history, permission groups, user accounts and their passwords, Alembic state. What changes: SECRET_KEY is new, so every existing session and every kiosk is signed out once (nothing at rest is encrypted with it); push subscriptions keep working only if you copy the old -vapid-public-key/-vapid-private-key secrets to the new prefix before step 3 (otherwise step 6 mints new ones and members re-enable notifications).

Route B — the church's Backup Database file (passwords included)

Use when the project's Cloud SQL data is gone or untrusted and the church has a koinonia-backup-<timestamp>.zip and its passphrase (12.0.1).

From the Command Center (since 2026-09-09): Operations → pick the church → Recover from Complete Backup → choose the file (the church's recent dumps/ copies, swept 6 h after creation, or anything copied to gs://koinoniacloud-490205-db-exports/<church>/) → passphrase → new church id → Recover into a new instance. The platform checks the passphrase, unwraps the dump to db-exports/<newid>/, copies the church's secrets to the new prefix and dispatches provision-church.yml, whose deploy.sh --restore-dump imports the dump into the fresh instance before the app boots (step 4b) and deletes the plaintext. The modal follows the GitHub run and ends with the new URL. Everything below is the same procedure by hand.
# 1. Create the empty instance + database WITHOUT deploying the app yet
#    (the dump carries the schema; alembic must not build one first).
gcloud sql instances create koinonia-{newid}-db --database-version=POSTGRES_15 \
  --region=us-central1 --tier=db-custom-1-3840 --enable-point-in-time-recovery \
  --storage-auto-increase --project koinoniacloud-490205   # the flags deploy.sh step 4 uses
gcloud sql databases create koinoniacloud --instance koinonia-{newid}-db

# 2. Unwrap the backup (AES ZIP: WinZip AES, e.g. 7-Zip or python pyzipper) and
#    stage the dump where Cloud SQL can read it.
7z x koinonia-backup-<stamp>.zip            # prompts for the passphrase → *.sql.gz, manifest.json, README.txt
gcloud storage cp *.sql.gz gs://koinoniacloud-490205-db-exports/{newid}/restore.sql.gz
gcloud storage buckets add-iam-policy-binding gs://koinoniacloud-490205-db-exports \
  --member=serviceAccount:$(gcloud sql instances describe koinonia-{newid}-db --format='value(serviceAccountEmailAddress)') \
  --role=roles/storage.objectViewer

# 3. Import, then delete the plaintext dump from the bucket.
gcloud sql import sql koinonia-{newid}-db gs://koinoniacloud-490205-db-exports/{newid}/restore.sql.gz \
  --database=koinoniacloud --project koinoniacloud-490205
gcloud storage rm gs://koinoniacloud-490205-db-exports/{newid}/restore.sql.gz

# 4. Secrets, deploy, files, protection — as Route A steps 2–5.
./deploy/secrets.sh --church-id {newid} && ./deploy/deploy.sh --church-id {newid}

The dump was taken as Cloud SQL's export user, so imported objects may be owned by cloudsqlsuperuser; if the app's first boot fails on permissions, run REASSIGN OWNED BY cloudsqlsuperuser TO koinonia; as postgres. Photos and documents come from the old uploads bucket if it still exists (Route A step 4) or from the church's Export Data pack.

Route C — the church's Export Data ZIP (hours; passwords lost)

  1. ./deploy/secrets.sh --church-id {newid} then ./deploy/deploy.sh --church-id {newid} — a fresh church at the latest migration head with the seeded reference data.
  2. Sign in with the admin credentials from secrets.sh, then Admin → Import Church Data → Restore from Backup exactly as in 12.2. If the export was taken at an older revision, phase 3 adds missing columns and phase 10 stamps the backup's revision so the next boot walks forward.
  3. Restore photos and documents: if the export was made with Also include photos & documents they are restored by the same run; otherwise copy the old uploads bucket as in Route A step 4.
  4. Passwords were redacted in the export: every user signs in with Email me a sign-in code or Forgot passphrase?. Tell the church before you hand it back.

After any route

  • Postmark: the sender domain is unchanged; only the webhook URL moves — repeat 9.2 for https://postmark:<pw>@{newid}-api.koinoniacloud.com/api/communications/postmark-webhook (step 6 minted the new -postmark-webhook-* secrets). Twilio: repeat 9.3.
  • Kiosks and the iOS check-in app resolve the church by its code; confirm the code now points at the new API host before Sunday.
  • Set Public URL (9.1) so QR codes and emails link to {newid}.koinoniacloud.com.
  • Run a Data Health scan and a test check-in; take a fresh Backup Database from the new instance and file its passphrase.

12.3 Handling Large Data Migration (Cloud Run Limits)

Google Cloud Run enforces a hard 32 MB request body limit. Standard HTTP POST uploads for large legacy ChMS CSV files (often 30MB–100MB) will fail before they even reach the Koinonia API.

The Solution: GCS Signed URL Workflow

All four CSV import functions use the same GCS bypass pattern automatically when the file exceeds 10 MB:

Import Function Frontend Component Backend Endpoint
Members & Families BulkImportModal.tsx /api/ingestion/analyze
Volunteer Role Qualifications PrereqImportWizard.tsx /api/prereq-import/analyze
Groups & Memberships GroupImportModal.tsx /api/groups/import-groups-csv
Class Attendance ClassImportWizard.tsx /api/class-import/analyze

How it works

  1. When the user selects a file larger than 10 MB, the frontend calls /api/ingestion/upload-url to get a GCS signed URL.
  2. The browser uploads the file directly to GCS, bypassing Cloud Run's 32 MB limit entirely.
  3. The browser sends the GCS object key to the relevant analyze endpoint via a gcs_key form field (instead of the file).
  4. The backend reads the CSV from GCS, deletes the temporary object, and proceeds normally.
  5. For files under 10 MB (or on local dev where GCS is not configured), the standard direct upload is used as a fallback.

GCP Requirements & Performance Tuning

  • IAM Permissions: The Service Account must have the role roles/iam.serviceAccountTokenCreator granted to itself.
  • Memory Allocation: Ingestion of 40k+ rows requires at least 2Gi of Memory.
  • Timeout Allocation: Set the Cloud Run request timeout to 600 seconds (10 minutes) minimum.
  • CORS Config: The GCS bucket must have a CORS policy allowing PUT from the frontend domain. deploy.sh configures this automatically.

12.4 Post-import de-duplication (Fellowship One → F1Go)

A church onboarded from a Fellowship One / F1Go export arrives with duplicate people. The two systems were reconciled by hand upstream and the seams surface on our ingest, so the first Data Health scan on a new church typically raises dozens of CRITICAL duplicate findings. Clicking “Merge” on each one is not a plan — Bay Life had 28.

This is a required onboarding step. Run it after the first Data Health scan on every newly imported church, before the church starts using the directory. Duplicates that survive into daily use accumulate attendance, giving and volunteer history on both records, and merging gets harder the longer you wait.

The tool is backend/scripts/merge_import_duplicates.py. It calls the same merge_individuals() function the staff Merge button runs, so FK re-pointing, field fill, household relocation, archiving and finding-resolution all behave identically. Dry run is the default — it prints the full keep/archive plan and changes nothing until you add --execute.

INST=koinoniacloud-490205:us-central1:koinonia-<church>-db
cloud-sql-proxy --unix-socket /tmp/cloudsql "$INST" &

PASS=$(gcloud secrets versions access latest \
         --secret=koinonia-<church>-database-url --project koinoniacloud-490205 \
       | sed -E 's|.*://[^:]+:([^@]+)@.*|\1|')

sg docker -c "docker run --rm \
  -v $PWD/backend/app:/app/app \
  -v $PWD/backend/scripts:/app/scripts \
  -v /tmp/cloudsql:/tmp/cloudsql \
  -e SECRET_KEY=unused-this-container-only-touches-the-db \
  -e DATABASE_URL='postgresql://koinonia:$PASS@/koinoniacloud?host=/tmp/cloudsql/$INST' \
  koinonia-cloud-api-server python /app/scripts/merge_import_duplicates.py \
    --actor-user-id <your users.id in THAT church>"

--actor-user-id must be a real users.id in that church's database — every merge is attributed to it in the audit trail. There is deliberately no default.

It merges only exact_name_dob, and that limit is not conservatism — it is correctness. The same_name_email check matches on name plus email alone, and a household shares one mailbox while a junior shares his father's full name. On Bay Life, 7 of 12 such findings were provably two different people: a mother and daughter 22 years apart, a father and his 13-year-old. Merging those would have deleted a human being. The script refuses them and prints the evidence per pair so a person can judge the leftovers by hand.

Which record survives is decided by evidence, not by which id is lower: the script counts inbound references across every foreign key to individuals. (Since 2026-09-09 the merge itself re-points every foreign key it finds in pg_constraint, so nothing is lost on the archived side any more; the reference count is still the fairest tie-breaker for which record to keep.) Ties fall back to the fuller profile, then to the older record.

Afterwards, expect a small tail of findings that are genuinely ambiguous — same name and email, no birth date on either side. Leave those open, or dismiss and suppress them so the next scan does not raise them again. Bay Life finished at 3 out of the original 28.


12.5 Post-import family-position mapping

The second required cleanup on a newly imported church, and it belongs immediately after the de-duplication in 12.4 — dedup first, so you are not mapping the same person twice.

Every ChMS disagrees about what a person is to their household. An F1Go export arrives carrying HEAD, Head of Household, Husband, Son, Grandma, Visitor and a long tail besides. Koinonia Cloud stores that raw string untouched in individuals.role_in_family and never rejects it, but the string is not what the platform reads. The platform reads individuals.family_position — a closed eight-value enum (PRIMARY, SPOUSE, CHILD, GRANDCHILD, FOSTER_CHILD, DEPENDENT, OTHER_ADULT, OTHER) plus household_attachment (FRIEND / GUEST) for people attached to a home without being family.

This is a required onboarding step. Until it is done, everyone still unmapped is invisible to every surface that asks whether a person is a child or an adult of their household: check-in placement, the member’s Kids widget, the heads-only map filter, the guardian contact on a child’s event notice, and the family demographics in Groups. They do not error — they are simply left out, which is why nobody notices unless you check.

The church does the work themselves, in their own instance: Admin › Family Positions (SuperAdmin only). Three tabs — Labels (their wording for the eight), Mapping (their legacy words → a position, commonest first, with row counts), Review (per-person decisions). See 5r-3. Family Positions in the User Guide, which is the audience-appropriate walkthrough to hand them.

What UF needs to check. The migration seeds an alias map and backfills every unambiguous value, so most churches arrive largely done — Bay Life’s ~66k import resolved to 12 unmapped people plus one 700-row judgement call. Confirm the tail is small and that the church knows the screen exists:

SELECT COUNT(*) FROM individuals
 WHERE archived_at IS NULL
   AND family_position IS NULL AND household_attachment IS NULL
   AND role_in_family IS NOT NULL AND btrim(role_in_family) <> '';

The same number surfaces as a family_structure / unmapped_family_position finding on the church’s next Data Health scan, grouped one row per distinct word rather than per person.

Do not map the ambiguous values on the church’s behalf, and do not add a default for them in the seed. Father, Mother, Parent, Adult and Guardian are seeded as ambiguous on purpose: in a two-parent household exactly one adult is PRIMARY and the other is SPOUSE, and the word cannot say which. The importer this replaced mapped all of them — and a blank cell — to Head, which produced two heads of household in every imported family, silently. Visitor is ambiguous for a different reason: some exports use that column for membership status, so those rows may be ordinary family members and detaching them as Guests would drop them out of every household count. A human decides.

Nothing here is destructive and nothing is one-way. role_in_family keeps the original string on every record forever, so any mapping can be re-decided later; Apply to people is re-runnable after every subsequent import and picks up the church’s existing decisions automatically, without overturning anything set by hand on the Review tab.


12.6 Post-deploy: ESE room placements from Sunday pins

One-off after the first deploy that carries migration 8d4bc7d79d9f (individual_support_needs + is_exceptional on template/event groups — docs/plan_exceptional_kids_routing.md in koinonia-cloud). Before it, the only way to keep a child in the ESE room was individuals.cm_override_group_id, a pin to one template room; each such pin means “this child needs the ESE room” and is converted to an individual_support_needs row. Pins are left in place.

Two steps, same DB-as-koinonia pattern as 12.4 (proxy on a UNIX socket, never the app login):

  1. Find the church’s ESE template groups (Bay Life: Toy Store ×2 = 42, 102; Exceptional Kids = 187):
    SELECT tg.id, tg.name, t.name AS template FROM event_template_groups tg
      JOIN event_templates t ON t.id = tg.template_id
     WHERE tg.name ILIKE '%exception%' OR tg.name ILIKE '%toy store%';
  2. Dry-run, then run, marking those groups (which also marks their rooms on every event dated today or later — the same propagation the template editor does):
    ... koinonia-cloud-api-server python /app/scripts/ese_needs_from_pins.py --dry-run --mark 42,102,187
    ... koinonia-cloud-api-server python /app/scripts/ese_needs_from_pins.py --mark 42,102,187

The script prints each pinned child as ADD or already. It is idempotent. Staff can also tick ESE room on the group in the template editor instead of --mark; the script then converts pins without it.

The need is silent by design: it is never rendered as a badge, never sent to the CHECKIN role or to members, and the table is absent from NL Reports. The only visible trace is one staff-only line on the person card.

6c. Source Control & Branch Management

Koinonia Cloud is split across two GitHub repositories. Most day-to-day work happens on main in koinonia-cloud, but larger features often live on a long-running feature branch for weeks before they're ready to ship. This section explains how to manage those branches without accidentally exposing unfinished work to beta testers.

Core rule: Anything merged to main ships on the next deploy.sh run. If a feature is not ready for users, it must stay on its own branch — not on main.

6c.1 Repository Overview

Repo What it contains Production deploy
billburnham/koinonia-cloud The church platform: FastAPI backend, Next.js frontend, Alembic migrations, deploy.sh. One repo, deployed per-church to GCP Cloud Run. Daily, via ./deploy/deploy.sh --church-id {id}
billburnham/koinonia-geocoder On-premises Pelias geocoder: docker-compose.yml, pelias.json, import scripts. The 67 GB data/ directory is not in git (excluded via .gitignore) — it lives on the NAS RAID and is regeneratable from upstream OSM/WhosOnFirst. Run on-prem only; not deployed to GCP. See Section 11a.
billburnham/koinonia-poi On-premises PostGIS POI extract: PostgreSQL + PostGIS, osm2pgsql importer, FastAPI counting proxy on :8007. Holds the curated US OSM POI dataset (~6.4M points, ~2–3 GB) that powers the Member Map's rich-popup-on-click feature without sending coordinates to a third-party API. The POI_DATA_DIR on local NVMe is not in git; regeneratable from the OSM PBF. Run on-prem only; not deployed per-church to GCP (POI data is public OSM and is shared across all church instances). See Section 11d.
billburnham/koinonia-tiles On-premises vector tile service: Caddy + PMTiles (planet-wide world.pmtiles, ~77 GB), Planetiler build pipeline (planetiler/), map styles (styles/ — standard + parchment), and the aggregator/ service that tails Caddy's access log to produce per-church tile counts for Command Center. world.pmtiles itself is not in git; lives at /home/kyfakt/koinonia-tiles-static/ on local NVMe and is regeneratable from OSM via the Planetiler script. Run on-prem only; serves browser tile requests at tiles.koinoniacloud.com (prod) and tiles-dev.koinoniacloud.com (dev) through the Cloudflare Tunnel. Per-church attribution via URL prefix (/<church-id>/…); see §17.2.
billburnham/koinonia-routing On-premises routing services: Valhalla turn-by-turn routing engine (docker-compose.yml) + VROOM vehicle-routing-problem solver (vroom/, VROOM.md) + FastAPI counting proxy (proxy/) on :8003. Powers the Pastoral Visit Planner's route optimization, the Member Map's Get Directions, and (when shipped) the multi-visitor pastoral-care dispatch via VROOM. The routing tiles (tens of GB built from us-latest.osm.pbf) live in VALHALLA_DATA_DIR on local NVMe and are not in git; regeneratable from the OSM PBF (~8–12 h single-threaded; see plan_valhalla_routing.md for the heap-race warning on multi-threaded builds). Run on-prem only; exposed at routing.koinoniacloud.com / routing-dev.koinoniacloud.com through the Cloudflare Tunnel with per-church service-token attribution. VROOM has its own future tunnel hostname planned (routing-opt-dev.koinoniacloud.com) once VROOM Phase 2 ships.
billburnham/koinonia-platform The Unbalanced Force operator infrastructure: FastAPI backend (backend/), admin frontend (frontend/admin.html — the Command Center / Fleet Monitoring UI), this manual (frontend/admin-manual.html), platform-wide deploy scripts (deploy/), and operator scripts (scripts/). One repo, one GCP deploy — serves all churches (not per-church like koinonia-cloud). Owns the onprem_activity table that aggregates the on-prem services' attribution data. Daily, via the platform-side deploy script. Currently the only consumer of the on-prem services' ingest endpoint at /api/admin/onprem-activity/ingest; the allowlist + summary determine which sources surface in the Fleet Monitoring tab. See Section 9b.

6c.2 Daily Workflow on main

For any feature that is ready to ship to beta testers as soon as it's done:

# Make sure you're on main and up to date
git checkout main
git pull origin main

# Edit code, run tests locally
# ...

# Commit and push
git add <files>
git commit -m "feat: short description"
git push origin main

# Deploy when ready
./deploy/deploy.sh --church-id {church-id}
Warning: Never commit a half-finished feature to main. Anything on main can ship the moment someone runs deploy.sh.

6c.3 Long-Lived Feature Branches

Use a feature branch when:

  • The feature will take more than a day or two to complete
  • You don't want beta testers to see it until you've polished it
  • It's experimental and might be abandoned
  • Multiple people need to collaborate before merge

Creating a new feature branch

git checkout main
git pull origin main
git checkout -b feature/short-name

# Make commits, then back up to GitHub:
git push -u origin feature/short-name

Use feature/<name> as the naming convention. Examples already in the repo: feature/member-map, feature/member-map-v2.

6c.4 Switching Between Branches

Before switching, check for uncommitted work:

git status

If git status shows modified files (M filename), you have three options:

  1. Commit them (preferred if the change is complete):
    git add <files>
    git commit -m "wip: short description"
  2. Stash them (preferred if you're mid-edit):
    git stash push -m "describe what's stashed"
    
    # When you come back later:
    git stash pop
  3. Bring them along — if the file you edited is identical on both branches, git checkout will carry your edits across automatically. If the file differs, git will block the switch and tell you.

Switch and restart Docker

git checkout feature/branch-name

# Restart Docker — different branches may have different deps, migrations,
# or env vars. Skipping this can cause confusing errors.
sg docker -c "docker compose up -d"
Note: The api-server container will run alembic upgrade head on startup. If the branch has migrations main doesn't (or vice-versa), Alembic auto-generates a merge migration and applies the new schema. Watch the logs the first time you switch to a new branch.

6c.5 Weekly Sync (Rebase Onto main)

Long-lived feature branches drift from main as commits land on main daily. The longer you wait, the worse the merge conflicts. Rebase weekly to keep conflicts tiny:

git checkout feature/branch-name
git fetch origin
git rebase origin/main

If conflicts come up during rebase

Git stops at the first conflicting commit and tells you which files. For each:

  1. Open the file. Look for <<<<<<< HEAD markers.
  2. Edit the file to combine both sides correctly. Remove the <<<<<<<, =======, and >>>>>>> marker lines.
  3. Stage: git add <file>
  4. Continue: git rebase --continue

If it gets ugly and you want to start over:

git rebase --abort   # safe — fully reverts to pre-rebase state

Push the rebased branch back to GitHub

Rebase rewrites commit history, so a normal git push will be rejected. Use --force-with-lease (safer than plain --force):

git push --force-with-lease origin feature/branch-name
Warning: --force-with-lease is only safe on branches you own. Never force-push to main or any shared branch — you can erase other people's commits.

6c.6 Backing Up a Branch Without Shipping It

Pushing a feature branch to GitHub backs it up off your laptop but does not ship to production. Production only sees code that has been (a) merged into main AND (b) deployed via deploy.sh. Both require deliberate action.

git push -u origin feature/branch-name

What's visible to beta testers, by stage:

Action Visible in production?
Commit locally No
Push branch to GitHub No
Open Pull Request No
Merge PR into main No (until next deploy)
Run deploy.sh against GCP Yes

6c.7 Merging the Branch When Ready

Sequence:

  1. Sync one last time — rebase onto current main per 6c.5 so the merge will be a fast-forward.
  2. Verify schema — if the branch added migrations:
    sg docker -c "docker exec koinonia_api alembic heads"
    sg docker -c "docker exec koinonia_api python /app/scripts/compare_schemas.py"
    Single head + zero schema drift = good to merge.
  3. Open a Pull Request:
    gh pr create --base main --head feature/branch-name \
      --title "feat: short description" \
      --body "What changed and why"
  4. Review and merge via the GitHub web UI, or:
    gh pr merge --squash --delete-branch
  5. Deploy on your own schedule:
    git checkout main
    git pull origin main
    ./deploy/deploy.sh --church-id {church-id}

Cleanup after merge

# Local cleanup
git checkout main
git pull
git branch -d feature/branch-name              # safe — only deletes if merged

# Remote cleanup (skip if you used --delete-branch above)
git push origin --delete feature/branch-name

6c.8 The Geocoder Repo

The geocoder lives in its own repo and follows the same workflow, with two caveats:

  • The 67 GB data/ directory is gitignored. It contains OpenStreetMap, WhosOnFirst, OpenAddresses, Elasticsearch indices, and Pelias placeholder data — all regeneratable. Do not attempt to commit it.
  • .env is gitignored because it has host-specific paths. A .env.example template ships in the repo — copy it and adjust:
# Cloning the geocoder fresh on a new machine
git clone https://github.com/billburnham/koinonia-geocoder.git
cd koinonia-geocoder
cp .env.example .env
# Edit .env: set DATA_DIR and PELIAS_CONFIG to absolute paths on this host

# Regenerate the data directory (~67 GB download + processing — takes hours)
./setup.sh
./run_import.sh

For full geocoder operations — running, troubleshooting, updating data sources — see Section 11a.

6c.9 Pitfalls & Lessons Learned

  • Don't let a branch sit for over 2 weeks without rebasing. The feature/member-map branch went 2+ weeks without sync, accumulated 197 commits of drift, and required a full cherry-pick rebuild onto a new feature/member-map-v2 branch to recover. Weekly rebase prevents this.
  • Never merge a feature branch into main until you're ready for users to see it. deploy.sh ships whatever is on main. There is no staging gate.
  • Never edit a migration file after it's been deployed to GCP. If a schema change is needed, create a new migration. Editing a deployed migration's down_revision can leave church databases stranded with missing columns.
  • Restart Docker after switching branches. Different branches can have different requirements.txt, package.json, or migration files. Failing to restart can produce phantom errors that look like bugs but are just stale containers.
  • Don't git push --force on shared branches. Use --force-with-lease on your own feature branches; never force-push main.
  • If two feature branches add Alembic migrations, you'll get a parallel-heads situation. The app's run_migrations() function in backend/app/main.py auto-generates a merge migration on startup, but commit it to the branch (not just the working tree) so every church gets the same merge revision ID. See Section 5a.3.
  • The original feature/member-map branch is kept on origin as a safety net. Don't delete it until feature/member-map-v2 is fully merged and verified in production.

7a. Troubleshooting

Emails not sending

  1. Check that POSTMARK_SERVER_TOKEN and SMTP_FROM are set on the Cloud Run service:
gcloud run services describe koinonia-{id}-api --region=us-central1 \
  --format="json" | python3 -c "
import json,sys
svc=json.load(sys.stdin)
for e in svc['spec']['template']['spec']['containers'][0].get('env',[]): print(e.get('name'),e.get('value','[secret]'))
"
  1. Check Cloud Run logs for [EMAIL] or [POSTMARK] log lines:
gcloud run services logs read koinonia-{id}-api --region=us-central1 --limit=50
  1. Verify the From address is a verified Sender Signature in the church's Postmark server

CORS errors in the browser

The frontend and backend URLs must match the CORS_ORIGINS environment variable or secret.

CRITICAL: Do NOT use * (wildcard). Our app uses allow_credentials=True for browser session security, and browsers will block requests if the origin is a wildcard.

Format: Use a comma-separated list of exact origins (including https://).
Example: https://demo.koinoniacloud.com,https://koinonia-demo-web-hash.us-central1.run.app

Check the current value:

gcloud run services describe koinonia-{id}-api --region=us-central1 --format="value(spec.template.spec.containers[0].env)"

If you add a custom domain, update the env var and redeploy.

Import fails with FK violation

This usually means the ZIP was exported from a newer version of Koinonia than the target instance is running. Update the backend first, then retry the import.

Cloud Run service won't start

Check the startup logs:

gcloud run services logs read koinonia-{id}-api --region=us-central1 --limit=100

Common causes: missing required secret (DATABASE_URL, SECRET_KEY), Cloud SQL connection name mismatch, or a failed database migration.

Frontend shows old version after deploy

Symptom: You deploy a new version, the deploy completes successfully, but the live site still shows the old UI.

Root cause: Cloud Run's --tag flag. If a gcloud run deploy command includes --tag=<name>, Cloud Run deploys the new revision with 0% of regular traffic.

How to diagnose

# Check what revision is serving traffic
gcloud run services describe koinonia-{id}-web \
  --region=us-central1 --project=koinoniacloud-490205 \
  --format="yaml(status.traffic)"

Look for percent: 100 on the latest revision. If the latest revision shows percent: 0, fix it:

# Route 100% traffic to the latest revision
gcloud run services update-traffic koinonia-{id}-web \
  --to-latest \
  --region=us-central1 --project=koinoniacloud-490205

At scale (many churches)

# Check all frontend services for traffic misroutes
for svc in $(gcloud run services list --region=us-central1 \
  --format="value(name)" --filter="name~koinonia-.*-web"); do
  PCT=$(gcloud run services describe "$svc" --region=us-central1 \
    --format="value(status.traffic[0].percent)")
  LATEST=$(gcloud run services describe "$svc" --region=us-central1 \
    --format="value(status.traffic[0].latestRevision)")
  if [[ "$PCT" != "100" || "$LATEST" != "True" ]]; then
    echo "PROBLEM: $svc -- ${PCT}% on latest (latestRevision=${LATEST})"
  fi
done
Prevention: The current deploy.sh runs this check automatically. If you ever modify the deploy script, never add --tag to gcloud run deploy unless you explicitly want canary behavior.

Large ZIP / CSV upload fails (> 32 MB)

Symptom: The browser shows "NetworkError when attempting to fetch resource" and the Network tab shows "CORS Missing Allow Origin" on the POST request. This happens because Cloud Run rejects the oversized request before the backend can add CORS headers.

If uploads fail for large files:

  1. Verify GCS_BUCKET_NAME: Ensure the backend has this env var set.
  2. Check IAM Identity: The Service Account must have the Service Account Token Creator role granted to itself:
gcloud iam service-accounts add-iam-policy-binding koinonia-{id}-sa@PROJECT_ID.iam.gserviceaccount.com \
  --member="serviceAccount:koinonia-{id}-sa@PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/iam.serviceAccountTokenCreator"
  1. Memory/Timeout: Ensure the backend has Memory=2Gi and Timeout=600.
  2. GCS Bucket CORS: Verify the bucket allows PUT and OPTIONS from the frontend origin:
gcloud storage buckets describe gs://koinoniacloud-490205-{id}-uploads --format="json(cors_config)"

Cloud SQL Proxy — password authentication failed

Use the proxy directly instead of gcloud sql connect:

# 1. Ensure Application Default Credentials are active (one-time setup)
gcloud auth application-default login

# 2. Kill any stale proxy, start fresh
kill $(pgrep cloud-sql-proxy) 2>/dev/null; sleep 1
~/bin/cloud-sql-proxy koinoniacloud-490205:us-central1:koinonia-{id}-db --port 5434 &
sleep 2

# 3. Fetch the current password (it rotates -- always re-fetch)
gcloud secrets versions access latest --secret="koinonia-{id}-db-password" \
  --project=koinoniacloud-490205 && echo ""

# 4. Connect
PGSSLMODE=disable PGPASSWORD='<password>' psql -h 127.0.0.1 -p 5434 -U koinonia -d koinoniacloud

If you get port already in use: kill $(pgrep cloud-sql-proxy) and retry from step 2.
If you get invalid_rapt or credential errors: re-run gcloud auth application-default login.


7b. Stuck Migrations & DB Locks

If a Cloud Run deploy keeps timing out at the same migration line (e.g., Running upgrade X -> Y, ... followed by silence and a 4-minute startup probe failure), the most likely cause is another long-running query holding locks the migration needs. This section captures the diagnostic and recovery pattern from the 2026-05-02 incident.

7b.1 Diagnostic flow

  1. Confirm the deploy is hanging on a specific migration by tailing the failed revision's logs:
    LATEST_REV=$(gcloud run revisions list --service=koinonia-{id}-api \
      --region=us-central1 --project=koinoniacloud-490205 \
      --limit=1 --format='value(name)')
    
    gcloud logging read "resource.type=\"cloud_run_revision\" AND resource.labels.revision_name=\"$LATEST_REV\"" \
      --limit=50 --order=asc --project=koinoniacloud-490205 --freshness=15m \
      --format='value(timestamp,textPayload)'
    Look for repeated Running upgrade ... lines without matching INFO [alembic.runtime.migration] Done.
  2. Connect to the church's Cloud SQL via cloud-sql-proxy (per Section 7a's setup):
    ./cloud-sql-proxy --unix-socket /tmp/cloudsql \
      koinoniacloud-490205:us-central1:koinonia-{id}-db &
  3. Inspect active sessions to find the blocker:
    DB_PASSWORD=$(gcloud secrets versions access latest \
      --secret=koinonia-{id}-db-password --project=koinoniacloud-490205)
    SOCKET="/tmp/cloudsql/koinoniacloud-490205:us-central1:koinonia-{id}-db"
    
    PGPASSWORD="$DB_PASSWORD" psql "host=$SOCKET user=koinonia dbname=koinoniacloud" -c "
    SELECT pid, usename, state, wait_event_type, wait_event,
           NOW() - query_start AS duration,
           substring(query, 1, 80) AS query
    FROM pg_stat_activity
    WHERE backend_type = 'client backend'
      AND state != 'idle'
    ORDER BY query_start NULLS LAST;"
  4. Look for queries with multi-minute durations. Common offenders:
    • A user-clicked admin action (DELETE / UPDATE / cleanup) that's running slowly because of missing indexes
    • An idle-in-transaction session held by an SSE/long-poll endpoint that didn't release its connection
    • Zombie CREATE INDEX queries from previous failed deploys, queued behind other locks

7b.2 Terminating stuck sessions

Once the offender is identified, terminate it (and any zombies that piled up behind it):

PGPASSWORD="$DB_PASSWORD" psql "host=$SOCKET user=koinonia dbname=koinoniacloud" -c "
SELECT pg_terminate_backend(pid) AS terminated, pid,
       NOW() - query_start AS duration,
       substring(query, 1, 60) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state != 'idle'
  AND pid != pg_backend_pid()
  AND query_start < NOW() - INTERVAL '30 seconds';"
Caveat: pg_terminate_backend rolls back any in-flight transaction. For a stuck cleanup query, the partial work is rolled back — this is usually what you want (the alternative is waiting hours for the slow query to finish). For a stuck application query, the user might see an error in their UI.

7b.3 Applying the migration manually (when the deploy can't)

After terminating the blockers, the migration may still need to run. Two options:

Option A — redeploy and let alembic try again. If the migration is well-formed (e.g., uses CONCURRENTLY for indexes per Section 5a.8), it should now complete within the startup probe window.

Option B — apply manually, then stamp alembic forward. Useful when the migration is slow even uncontested, or when you want to avoid another deploy cycle. Run the DDL via psql, then update alembic_version so the next deploy skips the migration:

# 1. Apply the migration's DDL (extracted from the migration file, with
#    CONCURRENTLY where appropriate). For a CREATE INDEX migration:

PGPASSWORD="$DB_PASSWORD" psql "host=$SOCKET user=koinonia dbname=koinoniacloud" -v ON_ERROR_STOP=1 <<'EOF'
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_{table}_{col} ON {table} ({col});
-- one statement per index
EOF

# 2. Stamp alembic_version forward to the migration's revision ID:
PGPASSWORD="$DB_PASSWORD" psql "host=$SOCKET user=koinonia dbname=koinoniacloud" -c \
  "UPDATE alembic_version SET version_num = '{revision_id}';"

# 3. Verify:
PGPASSWORD="$DB_PASSWORD" psql "host=$SOCKET user=koinonia dbname=koinoniacloud" -c \
  "SELECT version_num FROM alembic_version;"

Then redeploy — the container's startup alembic upgrade head will see the version is already at the migration's revision and continue past it cleanly.

7b.4 Incident reference: 2026-05-02

The pattern in this section came from a real incident. Sequence of events:

  1. User clicked “Clean Up Empty Family Records” in Data Health UI — the cleanup DELETE was painfully slow because individuals.family_id lacked an index, forcing per-row FK validation seq-scans
  2. Cloud Run timed out the HTTP response after 5 minutes, but the postgres backend kept executing the DELETE
  3. Multiple deploys of PR #9 (which adds the missing FK indexes) all hung at the same migration line because plain CREATE INDEX needs locks the DELETE was holding
  4. Each failed deploy left a zombie CREATE INDEX query in the lock queue
  5. 2.5 hours later: 1 stuck DELETE + 6 zombie CREATE INDEX queries on baylife-test, all blocking each other
  6. Recovery: cloud-sql-proxy + pg_terminate_backend() on all stuck PIDs, then manual CREATE INDEX CONCURRENTLY IF NOT EXISTS for each (completed in 0.85 sec total once uncontested), then UPDATE alembic_version, then redeploy — succeeded

Two lessons from this incident, captured elsewhere:

  • Index migrations on production-deployed Cloud Run must use CONCURRENTLY (Section 5a.8)
  • FK columns should be indexed by default — without indexes, cascade-validation seq-scans turn multi-row DELETEs into hours-long operations on Cloud SQL (PR #9 added five such indexes)

7c. Map Tile & 5G Connectivity

This section documents the "Stale Map Incident" of 2026-05-10, where map tiles failed to load over 5G/cellular networks while working perfectly on local office Wi-Fi. It covers the interaction between mobile carriers, Cloudflare WAF, and Caddy security guards.

7c.1 The "Privacy Header" Trap (5G/Mobile)

Many modern 5G carriers and mobile browsers (especially on iOS) strip the Referer header from requests for privacy reasons. If your Cloudflare WAF or Caddy rules expect a specific "allow koinoniacloud.com" referer, all mobile traffic will fail silently.

Hardened WAF Logic: When setting up origin protection in Cloudflare, do not just check for a match. Allow empty referers but block incorrect ones to prevent bandwidth theft: (http.referer ne "" and not http.referer contains "koinoniacloud.com")

7c.2 Handshake Failures (OPTIONS and HEAD)

MapLibre and the PMTiles protocol perform "handshakes" before downloading map data:

  1. A HEAD request to read the file metadata (size, version, bounds).
  2. An OPTIONS request (CORS preflight) to verify byte-range permissions.

If you implement a Caddy security guard that requires a Range header for all *.pmtiles requests, you must explicitly exempt these methods. Otherwise, the handshake fails with a 400 Bad Request before the data download ever starts.

@pmtiles_no_range {
    path *.pmtiles
    not method OPTIONS  # Allows the browser handshake
    not method HEAD     # Allows metadata checks
    not header Range *  # Blocks the 82GB browser download bots
}

7c.3 The "Double Prefix" Collision

The Koinonia Cloud frontend includes a "Transformer" that automatically injects the correct Church ID (e.g., /baylife-test/) into resource URLs. If your server-side style.json template also injects the prefix for the same resources, you create a non-existent path: /baylife-test/baylife-test/world.pmtiles.

Rule of Thumb: Only prefix the pmtiles:// URLs in the style file (as the app's standard transformer currently skips these), but keep sprite and glyph URLs "bare" to avoid duplication.

7c.4 Cloudflare Cache Persistence

Cloudflare caches "400 Bad Request" errors. During troubleshooting, if you fix a server setting, Cloudflare may still serve the old "400" error to your laptop or phone from its Edge locations.

Cache Bypassing: Always test with a version query parameter on the end of the URL (e.g., ?v=force_refresh) to force Cloudflare to fetch a fresh copy from your workstation. Use Purge Everything in the Cloudflare dashboard once the fix is confirmed.

7c.5 The AI Labyrinth Bot Trap (2026-05-12 incident)

Cloudflare's AI Labyrinth feature (Security → Settings, Beta-tagged, available on free tier) classifies traffic as bot-like using heuristics and either serves AI-generated decoy content or interrupts the handshake. MapLibre's PMTiles client sends a HEAD → OPTIONS → Range-GET sequence that Cloudflare's heuristic classifies as a bot. When AI Labyrinth is on, tile rendering breaks across all mobile clients (browser tab and installed PWA, on every network) while desktop browser may or may not work depending on which Cloudflare POP cache state the laptop happens to hit.

Diagnostic signature: Open Cloudflare → Security → Events for the koinoniacloud.com zone, filter by hostname tiles-dev.koinoniacloud.com. Look for rows where:

  • Service: AI Labyrinth
  • Action taken: AI Labyrinth Served
  • Method: HEAD
  • Path: /<church-id>/world.pmtiles or /<church-id>/style.json
One-toggle fix: Cloudflare dashboard → Security → Settings → find the AI Labyrinth card → toggle OFF. Allow ~30 seconds for the change to propagate to Cloudflare's edge POPs, then re-test. After the fix, also Purge Everything (§7c.4) so phones at distant POPs stop getting cached failure responses.

What stays on: Block AI Bots (also under Security → Settings) is safe and should stay on. It blocks requests based on the request's User-Agent header against a known-AI-bot allowlist (ChatGPT-User, Claude-User, GPTBot, Bytespider, etc.) — deterministic, narrow, and impossible for MapLibre to trip (MapLibre sends Chrome's UA). This is your actual defense against AI training scrapers; AI Labyrinth's heuristic approach was the conflict, not the blocklist approach.

What also stays off: Bot Fight Mode (same Security → Settings page) is a free-tier sibling of AI Labyrinth that JavaScript-challenges suspected automated traffic. It has the same heuristic-conflict risk against MapLibre and any other programmatic browser-side fetcher. Leave it off for the koinoniacloud.com zone.

Long-term defense: This kind of silent breakage by a managed-service toggle is exactly the failure class that §7d Cloudflare Zone Hardening exists to prevent. Once that section is implemented (Terraform-managed zone config), every one of these toggles is pinned in version control with an inline comment citing this incident, and any future drift becomes a PR diff rather than a phone-tested outage.

7d. Cloudflare Zone Hardening & Config-as-Code

The koinoniacloud.com Cloudflare zone hosts every church's frontend CNAME, both on-prem tunnel routes (tile server, geocoder), and the WAF / cache / Access rules that protect them. Every setting that affects operational behavior must live in version control. Two incidents in three days — a rate-limit rule blocking cellular traffic via CGNAT (2026-05-09) and AI Labyrinth eating MapLibre handshakes (2026-05-12) — established the rule: managed-service toggles change silently, and the only way to insulate a multi-church platform from that is to codify the expected state.

7d.1 The pinned-toggle inventory

These are the Cloudflare zone settings whose value (and the reason for that value) every system administrator needs to know. They are owned by Terraform once Phase 9 of plan_self_hosted_tiles.md ships; before that, they are tribal knowledge enforced by this section.

Setting Required value Reason
AI Labyrinth OFF Heuristic classifier matches MapLibre's PMTiles HEAD+Range handshake as bot traffic (§7c.5)
Bot Fight Mode OFF Same heuristic-conflict risk as AI Labyrinth against any programmatic browser-side fetcher
Block AI Bots ON (scope: Block on all pages) UA-allowlist blocker for known AI training crawlers; deterministic, no MapLibre conflict
Browser Integrity Check ON Header-based filter for known-bad signatures; long-standing, low false-positive risk
Cloudflare Managed Ruleset ON (Always active) Broad WAF protection; no MapLibre or tile-traffic conflict observed
Network-Layer DDoS Protection ON (Always active) Free-tier defensive layer for SYN/UDP/ICMP attacks; no behavioral risk
Replace Insecure JS Libraries ON (current scope: polyfill.io only) Defensive substitution for the compromised polyfill.io CDN. Watch the library list; if Cloudflare expands scope, re-evaluate.
Rate-limit rule on *.pmtiles ABSENT (do not re-add) 2026-05-09: 300 req/10s rule blocked legitimate cellular users due to CGNAT shared IPs. Re-add only with ≥5000/10s threshold or paid-plan Managed Challenge action.
Custom WAF rule: Referer-based scraper block PRESENT: (http.referer ne "" and not http.referer contains "koinoniacloud.com") Blocks scrapers with mismatched Referer; allows empty Referer (5G/mobile compatibility per §7c.1). Free tier requires contains not matches.
Cache rule: bypass cache for *.pmtiles PRESENT Cloudflare free-tier won't cache files larger than 512 MB; the 82 GB world.pmtiles tries and produces malformed range responses. Bypass is the documented workaround.

7d.2 The config-as-code plan (Terraform)

The complete implementation phase — provider bootstrap, state backend in GCS, import workflow for the existing zone, security-baseline module, drift detection, per-church provisioning hook — is documented in Phase 9 of plan_self_hosted_tiles.md (in the koinonia-cloud repo). That phase is shared between the tile server and the geocoder, since both live in the same Cloudflare zone. The geocoder plan (plan_cloudflare_pelias_tunnel.md) cross-references it from the geocoder side.

The deliverable, once Phase 9 ships, is:

  • An infra/cloudflare/ directory in the repo with every Cloudflare resource declared.
  • A scheduled drift-detection job (Cloud Run cron or GitHub Actions) that runs terraform plan daily and alerts on any non-empty diff.
  • An extension to deploy/deploy.sh so provisioning a new church adds its DNS record via terraform apply rather than a manual dashboard click.
  • A README in infra/cloudflare/ documenting the change workflow: always PR → review → terraform apply; never click in the Cloudflare dashboard.
Mandatory before paying churches: Phase 9 must ship before the platform onboards its first paying church. The 2026-05-12 incident was discovered during developer testing on the dev church (baylife-test); on a paying church it would have meant tile failures for every mobile congregant on Sunday morning, with no visibility from the SaaS provider's side until someone phoned.

7d.3 What this section does NOT prevent

Be honest about residual risk so future-you doesn't get caught believing the Terraform module is a complete shield:

  • Cloudflare can roll out a new managed feature default-on at the account level. If the feature isn't yet covered by a Terraform-managed resource, drift detection won't catch it. Mitigation: subscribe to Cloudflare's product changelog and review monthly.
  • A human with dashboard write access can still click around and create drift. Drift detection is the safety net, not a hard prevention. Long-term mitigation: lock dashboard write access to break-glass-only, all changes via PR.
  • Beta-tagged features have no opt-out switch on free tier. Free tier is Cloudflare's beta-test population. The defense is monitoring + alerting + audit-log review — not the ability to refuse beta participation.

7d.4 The audit log: knowing who flipped what

Cloudflare logs every configuration change with timestamp and actor. To investigate any suspected drift or incident:

  1. Click the top-right account menu → Manage Account → Audit Log. This is account-level, not zone-level — it lives outside the per-zone sidebar.
  2. Filter by date range (last 7 days is usually enough) and by the resource keyword (e.g., AI Labyrinth, WAF rule, DNS record).
  3. The Actor column tells you whether the change came from a named human, an API token, or Cloudflare itself (the last case = a managed-service automatic rollout, no human accountable).

Routine: any reported anomaly affecting Cloudflare-served traffic begins with an Audit Log review.

7d.5 External synthetic monitoring

Independent of zone hardening, an external HTTP probe that runs every 5 minutes and alerts on failure is the fastest way to learn that a Cloudflare-side change broke production. Recommended checks:

  • HEAD https://tiles-dev.koinoniacloud.com/baylife-test/world.pmtiles with Range: bytes=0-1023 → expect 206.
  • GET https://tiles-dev.koinoniacloud.com/baylife-test/style.json → expect 200 with body containing "version":8.
  • Authenticated GET on the geocoder endpoint (using a service token) → expect 200.

UptimeRobot's free tier handles all three. Long-term, the checks belong in §17 On-Prem Activity alongside the other fleet-health signals so they appear in Command Center rather than in a separate dashboard.


7e. On-Prem Proxy Gotchas

Both real lessons documented here surfaced on 2026-05-23 during the PostGIS POI service rollout. Both are SILENT-FAILURE patterns — the service appears up, requests appear to land, and the only symptom is "the Command Center counter is stuck at zero." Knowing where to look saves the next operator hours.

7e.1 Empty .env placeholder → silent flush failure

Symptom: a new on-prem proxy (POI in this case, or any future koinonia-*-proxy) appears healthy — systemctl is-active is green, /healthz returns 200, requests come in and increment the local SQLite counter — but the Command Center's tile for that service stays at 0. Refresh, wait, refresh, still 0.

Root cause: the proxy's proxy/.env file ships as an empty placeholder (deliberately, to let the container start for smoke-testing). If the operator doesn't immediately replace it with real values, the proxy starts up with empty PLATFORM_INGEST_URL / PLATFORM_ONPREM_INGEST_TOKEN, the flush loop logs a one-time WARNING and silently skips every subsequent flush. Additionally, the empty CF_CLIENT_TO_CHURCH means every incoming request resolves to church_id='unknown'.

Diagnostic:

# For systemd-style proxies (geocoder, routing):
journalctl -u koinonia-geocoder-proxy --no-pager -n 30 | grep PLATFORM_INGEST_URL

# For compose-style proxies (POI):
sg docker -c "docker logs koinonia_poi_proxy --tail 30" | grep PLATFORM_INGEST_URL

# If you see:  WARNING PLATFORM_INGEST_URL or PLATFORM_ONPREM_INGEST_TOKEN missing
# the proxy.env is still the placeholder.

Fix: copy the three shared values from a known-good proxy's .env (the Geocoder's is the canonical source). Pipe directly so the secret values never echo to the terminal:

SOURCE=/mnt/AntiGravity/KoinoniaCloud/koinonia-geocoder/proxy/.env
TARGET=/mnt/AntiGravity/KoinoniaCloud/koinonia-poi/proxy/.env  # adjust for the failing proxy
{
  grep -E '^(PLATFORM_INGEST_URL|PLATFORM_ONPREM_INGEST_TOKEN|CF_CLIENT_TO_CHURCH)=' "$SOURCE"
  echo 'FLUSH_EVERY_SEC=300'
} > "$TARGET"
chmod 600 "$TARGET"
# Restart the proxy:
sg docker -c "docker compose -f /mnt/AntiGravity/KoinoniaCloud/koinonia-poi/docker-compose.yml restart proxy"

Within one flush cycle (~5 min), the Command Center counter should bump. Counts queued under unknown from BEFORE the fix stay attributed to unknown — cosmetic, but surfaces as a row in the per-church table. Mention to the church if they care.

7e.2 SQLite schema drift → OperationalError loops

Symptom: an on-prem aggregator service (e.g. koinonia-tile-aggregator) runs cleanly per systemctl is-active, but the corresponding Command Center tile is frozen at counts from a few days ago. Today's activity isn't landing despite obvious traffic.

Root cause: the aggregator's SQLite schema was extended in the source code (e.g., a new blocked column) but the existing /var/lib/koinonia-onprem-activity/*.sqlite file pre-dates the change. CREATE TABLE IF NOT EXISTS does NOT add columns to an already-existing table, so every INSERT now fails with sqlite3.OperationalError: table counts has no column named <col>. The service stays "up" because each cycle's exception is logged and the next cycle scheduled normally — but no data is written, ever.

Diagnostic:

# Check the file's mtime (it should be "minutes ago" for an active service):
stat -c '%y %n' /var/lib/koinonia-onprem-activity/*.sqlite

# Recent errors in the journal:
journalctl -u koinonia-tile-aggregator --no-pager -n 30 | grep -i "OperationalError\|no column"

Fix: sqlite3 CLI isn't installed on the workstation, so use Python's stdlib to add the missing column non-destructively (preserves any rows that were written before the mismatch):

python3 -c "
import sqlite3
db = sqlite3.connect('/var/lib/koinonia-onprem-activity/tiles.sqlite')
cur = db.execute('PRAGMA table_info(counts)')
cols = [r[1] for r in cur.fetchall()]
if 'blocked' not in cols:
    db.execute('ALTER TABLE counts ADD COLUMN blocked INTEGER NOT NULL DEFAULT 0')
    db.commit()
    print('added blocked column')
"
sudo systemctl restart koinonia-tile-aggregator
journalctl -u koinonia-tile-aggregator --no-pager -n 5  # should show clean run

Within one cycle the aggregator will catch up reading whatever access-log lines accumulated during the broken window, so expect a backlog burst on the next flush (the May 16–23 outage produced a ~6,000-request bump when re-enabled).

6e. External System Integrations (Planning Center, QuickBooks, Stripe)

This section describes the per-church integration plumbing pattern used by every third-party integration on the platform — Planning Center Online (PCO Services), Intuit QuickBooks Online, Stripe Connect, and any future system added to the integrations catalog. Read this before wiring up a specific integration for the first time so you reuse the existing shape instead of inventing parallel infrastructure.

The pattern was pre-plumbed into the church-side baseline schema (pre-baseline scaffolding §13.11) so the first real integration to ship — likely QuickBooks at Baylife post-launch when the church's treasurer asks for it — does not require a fleet-wide migration to create connection tables. Four church-side tables carry the pattern; no integration-specific tables (e.g., pco_songs, qbo_journal_entries) exist in the baseline. Those land alongside the first sync engine that needs them.

6e.1 The four scaffolding tables

external_systems — Data-driven catalog of supported integrations. Same pattern as permission_module_catalog. Seeded at baseline time with three rows: planning_center, quickbooks_online, stripe. New integrations are added by editing this table — no code release required to expose a new integration in the connection UI.

external_connections — Per-church connection state. One row per (integration this church has set up). In single-tenant land that's "is QuickBooks turned on at this church, and where do its tokens live?"

OAuth tokens NEVER live in the database. The columns oauth_token_secret_ref and oauth_refresh_secret_ref store the Secret Manager secret name, not the secret value. Same pattern as VAPID keys today. When the sync engine needs to make an authenticated request, it reads the secret name from external_connections, fetches the actual token from Secret Manager, and uses it for the one call. Never store the token bytes themselves in external_connections.

external_id_map — Polymorphic mapping between Koinonia records and external-system records. One row per mapped record. Without this table, every business table would need its own per-integration *_external_id columns (pco_song_id, qbo_account_id, stripe_customer_id, etc.) — those would proliferate. With it, the mapping lives in one polymorphic table that handles every integration the same way:

external_system_key koinonia_table koinonia_id external_id sync_direction
planning_centersongs142abc123-pcopull
quickbooks_onlinegiving8801journal-2026-558push
quickbooks_onlineaccounts124-accountbidirectional
stripeindividuals91cus_AbCdEf123bidirectional

Unique indexes are defined on both (external_system_key, koinonia_table, koinonia_id) and (external_system_key, external_id) so lookup is O(log n) in either direction.

integration_sync_log — Append-only diagnostic log of sync runs. When "QuickBooks sync didn't update last night" comes in as a support question, this table is the first place to look. Mirrors the existing onprem_activity diagnostic pattern. Includes started_at, finished_at, status, records_pulled, records_pushed, error_message, and an integration-specific details JSONB column.

6e.2 What is intentionally NOT included in the scaffolding

  • No integration-specific tables. No pco_songs, no qbo_journal_entries, no stripe_subscriptions. Those land alongside the first sync engine that needs them.
  • No sync engine implementation. The scaffolding tracks that a church has an integration set up; it does not yet do anything with it. The first integration's engine code adds the church-side endpoint, the OAuth flow, and the actual pull/push logic.
  • No UI for connection management. The first integration to ship gets the connection-management UI as part of its delivery — at which point the screen is generic enough (driven by the external_systems catalog) to handle every subsequent integration.
  • No actual OAuth flow code. Same — comes with the first integration.

6e.3 Audit coverage

Three of the four tables — external_systems, external_connections, and external_id_map — are included in the request/UI mutation audit log (AUDITED_TABLES in backend/app/core/audit_hooks.py). OAuth token rotations, connection enable/disable, and ID-mapping changes are all audit-worthy. The actual secret values never appear in audit rows because only Secret Manager pointers are stored in external_connections.

integration_sync_log is intentionally not audited — it is itself an append-only diagnostic log, and auditing it would inflate audit_log ~1:1 with sync runs while adding no governance signal.

6e.4 When the first integration ships

Step-by-step pattern for the first time you wire up (e.g.) QuickBooks Online for a real church:

  1. Verify the catalog row. The seeded external_systems row for quickbooks_online should already exist with oauth_kind = 'oauth2'. Edit label / description if QuickBooks has rebranded since the baseline; the key itself is referentially stable.
  2. Provision the OAuth secrets. Store the church's QuickBooks access token and refresh token as two Secret Manager entries named e.g. koinonia-{church-id}-qbo-access-token and koinonia-{church-id}-qbo-refresh-token. The DB never sees the values.
  3. Insert the connection row. One INSERT into external_connections with external_system_key = 'quickbooks_online', oauth_token_secret_ref / oauth_refresh_secret_ref pointing at the secret names from step 2, and any integration-specific config in the config JSONB column.
  4. Build the church-side sync engine. New module under backend/app/integrations/quickbooks/ (suggested layout) with OAuth refresh logic, the QuickBooks API client, and the pull/push entry points.
  5. Populate external_id_map as records get mapped. Every Koinonia record that has a QuickBooks counterpart gets a row. Use the unique indexes to enforce one mapping per (system, koinonia record) and per (system, external id).
  6. Write one row to integration_sync_log per sync run. Even short sync runs should leave a breadcrumb so operators can answer "did it sync last night?" without reading application logs.
  7. Add the connection-management UI. The first integration's UI becomes the generic connection screen for every subsequent integration — drive it from the external_systems catalog so adding the second integration is a catalog-row edit, not a UI rebuild.
Pattern reuse check: if you find yourself writing per-integration code that should obviously work the same way for the second integration (token refresh scheduling, sync-log formatting, error-surfacing UI), pull it into a shared helper rather than duplicating. The whole point of the scaffolding is that the second integration is dramatically cheaper to ship than the first.

7f. Offline Check-In Stations

A church's check-in laptops, tablets and iPads can become offline-ready stations: they keep a saved copy of the family list and today's rooms, keep checking children in and printing tags when the church's internet or the instance is down, and replay what they did when it comes back. Church staff set them up and revoke them themselves (User Guide 6r; Admin → Check-In Stations). The design and build log is koinonia-cloud/docs/plan_offline_checkin.md (§13 lists every decision).

Nothing to provision

  • Stations are rows in the church's own database — check_in_stations, with the replay log in check_in_replays. Both come with the ordinary Alembic chain (38467e5ecc46), so every instance gets them on its next deploy.
  • The station's family-list refreshes are driven by checkin_changes, which database triggers fill (936f32212620, 8b3d931038b5) on individuals, families, individual_household_links, individual_support_needs, individual_volunteer_roles, volunteer_roles and event_template_groups. It is bookkeeping, pruned after 14 days and deliberately not in backups.
  • The CORS allow-list includes X-Station-Id (per-station rate limits). A custom proxy in front of an instance must pass it.

Things that bite

  • Rotating SECRET_KEY makes every browser station redo its setup: their saved copy is encrypted under a key wrapped by HMAC(SECRET_KEY, station id). Check-ins a browser station saved offline and had not sent are stranded by the rotation — drain first. iPads are unaffected.
  • Tag template. The web check-in, the iPad's offline tags and the server's PDF all print from label_html.build_label_html. After changing label_html.py, run koinonia-cloud/frontend/scripts/export_label_renderer.sh, regenerate the golden files (UPDATE_LABEL_GOLDEN=1 pytest tests/unit/test_label_template_parity.py), update frontend/src/lib/labelTemplate.ts to match, and commit the generated label_renderer.js in the iOS repo. CI fails until the three agree.
  • A church says "a station won't sync". In the instance's database (connect as koinonia, § operator access): select letter, name, last_seen_at, last_sync_at, revoked_at from check_in_stations; and select status, result->>'message', received_at from check_in_replays order by received_at desc limit 20;. A revoked station's replays are refused by design. Unresolved conflicts are what Admin → Check-In Stations / the station's Sync panel show the church.
  • Offline check-ins arrive with source = 'offline_checkin', the real check-in time and the station's code (B7KM); they never fire late walk-in pushes.

7g. Outside Hosts & the Content-Security-Policy

Rule (Bill, 2026-11-26): a church user's browser loads nothing from a host we don't run. Every outside load — a font, a script, an image, a map layer — hands that person's IP address, and which church's site they were on, to someone else. A Google Font in the User Guide and a shaded-relief map layer from klokantech.github.io both slipped in unnoticed; they are gone, and two guards stop the next one.

  1. At build time — CI. scripts/ci/check_outside_loads.py (job No loads from outside hosts in test.yml) fails when a tracked web file adds a script, stylesheet, font, image, frame, fetch or map style from a host outside *.koinoniacloud.com. Plain links aren't checked (they leave only when clicked). A deliberate exception goes in its ALLOWED list with the reason.
  2. In the browser — the Content-Security-Policy (frontend/next.config.ts). It names only our own hosts (images included, since 2026-11-26) and asks the browser to report anything else to /api/csp-report on the church's API, which logs one line per directive, outside host and page, at most once an hour:
gcloud logging read 'resource.labels.service_name=~"-api$" AND textPayload=~"^\[CSP\]"' \
  --project koinoniacloud-490205 --freshness 7d --format='value(resource.labels.service_name,textPayload)' | sort | uniq -c

The policy is report-only while it learns: a line reads [CSP] img-src would block https://… on /dashboard and nothing is blocked. After a week of clean reports from real use (a Sunday included — a wrong policy blocks the check-in desk), change the header key in next.config.ts from Content-Security-Policy-Report-Only to Content-Security-Policy and redeploy the web service. From then on the lines read blocked.

Kept on purpose: Postmark's open and click tracking in church email (staff want to know who opened and clicked) — a mail client loads Postmark's pixel, and a click passes Postmark's redirect. Outside the church app: the map tiles' own styles are checked by hand (koinonia-tiles/styles), and the Command Center loads only from itself.

8a. Resource Naming Reference

Given CHURCH_ID=firstbaptist:

Resource Full Name
Cloud Run backend koinonia-firstbaptist-api
Cloud Run frontend koinonia-firstbaptist-web
Cloud SQL instance koinonia-firstbaptist-db
GCS bucket koinoniacloud-490205-firstbaptist-uploads
Service account koinonia-firstbaptist-sa@koinoniacloud-490205.iam.gserviceaccount.com
Secret: admin email koinonia-firstbaptist-admin-email
Secret: admin password koinonia-firstbaptist-admin-password
Secret: database URL koinonia-firstbaptist-database-url
Secret: JWT secret key koinonia-firstbaptist-secret-key
Secret: SMTP From address koinonia-firstbaptist-smtp-from
Secret: SMTP From name koinonia-firstbaptist-smtp-from-name
Secret: Postmark token koinonia-firstbaptist-postmark-token
Secret: Twilio Account SID koinonia-firstbaptist-twilio-account-sid
Secret: Twilio Key SID koinonia-firstbaptist-twilio-key-sid
Secret: Twilio Key Secret koinonia-firstbaptist-twilio-key-secret
Secret: Twilio From Number koinonia-firstbaptist-twilio-from-number
Secret: Anthropic API key koinonia-firstbaptist-anthropic-api-key
Secret: Public URL koinonia-firstbaptist-public-url
Secret: CORS origins koinonia-firstbaptist-cors-origins
Container image (backend) us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-api:latest
Container image (frontend) us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-frontend:latest
Note: All churches share the same container images — only secrets and GCP resource names differ per church.

8b. Finance Module — Admin Reference

This section covers the accounting system architecture, database schema, and deployment-level notes for the Finance tab. For end-user instructions, refer to the Church User Manual (Part 11, Sections 53–62).

15.1 Finance Module Overview

Sub-tab Coverage
Accounts Chart of accounts — classify every financial transaction
Giving Receipts (including split-fund allocations), pledges, and year-end giving statements
Sales Inventory items, sales orders, and order line items (merchandise, event tickets)
Payables Vendors, bills, bill line items, and bill payments (accounts payable)
Settings Fiscal year, EIN, legal name, and giving funds (SuperAdmin only)

The system uses double-entry bookkeeping via an internal financial_transactions / journal_entries table pair. The giving subsystem is built on fund accounting (FASB ASC 958), the standard required for nonprofits.

15.2 Finance Database Tables

Table Purpose
financial_settings One-row config: fiscal year start month, EIN, legal name, currency code
funds Giving funds (General, Building, Missions + church-defined); seeded with 3 defaults
accounts Chart of accounts; seeded with 39 standard nonprofit accounts
income_categories Revenue classification linking to a revenue account and default fund; seeded with 6 defaults
financial_transactions Parent record for every accounting transaction
journal_entries Debit/credit lines; child of financial_transactions
receipts Individual giving transactions
receipt_allocations Split-fund allocations; child of receipts
pledges Giving commitments with amount, frequency, date range, and active flag
giving_statements Year-end tax acknowledgment records (always calendar year)
inventory_items Merchandise / ticket items with SKU, price, quantity
sales_orders Sales transactions
order_items Line items; child of sales_orders
vendors AP vendors with 1099 flag
bills Vendor invoices with status (unpaid / partial / paid / void)
bill_line_items Expense-coded line items; child of bills
bill_payments Payments recorded against a bill

15.3 Seeded Data (Auto-Applied via Alembic)

Funds (3): General Fund (unrestricted, default), Building Fund (temporarily restricted), Missions Fund (temporarily restricted)

Chart of Accounts (39 accounts): Standard nonprofit numbering — 1000s Assets, 2000s Liabilities, 3000s Equity/Net Assets, 4000s Revenue, 6000s Expenses

Income Categories (6): Tithes & General Giving, Building Fund Gift, Missions Gift, Special Offering, Merchandise Sale, Event Ticket

Note: The Finance schema is created by the Alembic chain root (0001_bootstrap_baseline) and seeded by c2d7c86cf2a4_seed_platform_reference_data. No manual SQL step is required — deploy the backend and the schema and seed data are applied automatically on first alembic upgrade head.

15.4 Finance Access Control

Role Chart of Accounts Giving Sales Payables Settings
SuperAdmin / Admin Full Full Full Full Full
Staff Read + Write Read + Write Read + Write Read + Write No access
Member (with Finance permission) Read-only giving history Own giving only — — —
Check-In No access No access No access No access No access

15.5 Year-End Giving Statements

Giving statements are generated per-giver per calendar year (January–December), regardless of the church's fiscal year setting. This is an IRS requirement.

  • Only allocations tied to income categories marked is_tax_deductible = true are included.
  • Non-deductible items are excluded automatically.
  • Statements can be regenerated for the same year — the previous set is replaced.
  • The church's EIN and legal name (from Finance Settings) are printed on each statement.

15.6 Exporting Finance Data

Finance tables can be exported via Settings → Export Data → Select Tables. Available tables include: funds, accounts, income_categories, receipts, receipt_allocations, pledges, giving_statements, inventory_items, sales_orders, order_items, vendors, bills, bill_line_items, bill_payments, financial_transactions, journal_entries, financial_settings.

Note: Finance tables are not included in the "Export All" default set. Select them individually in the Select Tables export tab.

8c. Operator Sign-In & Authenticator (TOTP)

Every church instance has exactly one account that belongs to Unbalanced Force rather than to a person: the bootstrap SuperAdmin provisioning creates from ADMIN_EMAIL (koinonia-<church>-admin-email / koinonia-<church>-admin-password). Operators use it only when a task needs the church's web app rather than the database — walking a screen the church is reporting, promoting a church SuperAdmin in User Management, taking a screenshot for a ticket. Data work goes through the database as koinonia (docs/runbook_operator_access.md §2); never sign in as a real staff member.

Since Phase D of the passwordless migration the operator account signs in with a passphrase plus a 6-digit code from an authenticator app (TOTP, RFC 6238). The passphrase alone issues no session.

8c.1 Where to sign in

https://<church web URL>/operator-signin. The page is linked from nowhere a member sees; the member sign-in page only forwards there when a passphrase sign-in answers totp_required. It always shows the passphrase box, whatever the church has set on its own sign-in screen.

  1. Email + passphrase → Continue (POST /api/auth/login). The API answers {totp_required: true, totp_token} instead of a session; the token lives 5 minutes.
  2. Code from the authenticator app → Sign In (POST /api/auth/totp/login {totp_token, code}). Use a recovery code swaps the box for an XXXX-XXXX code.
Lockout behaves exactly as for a passphrase. A wrong code counts against the same 10-failure / 15-minute lock; five wrong codes on one pending token burn that token and the page returns to step 1. Codes are accepted one time-step (30 s) either side of the clock, and a code that has already been accepted is refused if presented again.

8c.2 Enrolling the authenticator (once per church, right after provisioning)

The operator account must carry the authenticator. A church whose ADMIN_EMAIL account has totp_enabled_at IS NULL is a Phase D gap. Do this step as part of post-deployment configuration (4a, 9.4).
  1. Sign in at /operator-signin with the Secret Manager passphrase. No code is asked yet — there is none to ask for.
  2. Open https://<church web URL>/authenticator → Set up an authenticator app. Scan the QR with the operator vault's authenticator (1Password / Bitwarden TOTP, or a vault-held phone) — never a personal phone and never the church's. Can't scan? shows the base32 key for manual entry (time-based, 6 digits, 30 s).
  3. Type the current code → Confirm. The page shows the 8 recovery codes once. Put them in the same vault entry, tick I've saved these, Done.
  4. Confirming the operator account sets users.totp_required = true by itself; from the next sign-in the code is demanded.

The QR, the key and the recovery codes go in the operator vault, not to the church. Verify from the database path:

select email, totp_enabled_at is not null as enrolled, totp_required
  from users where email = '<ADMIN_EMAIL>';

8c.3 Lost authenticator, rotating it, running out of recovery codes

  • A recovery code gets you in but does not get you a new authenticator: the operator account cannot turn its own authenticator off (/authenticator hides the button; POST /api/auth/totp/disable answers 400), and enrolment refuses while one is on.
  • The sanctioned path is a reset by a different SuperAdmin: POST /api/auth/totp/users/{id}/reset (users-manage; for the ADMIN_EMAIL account the caller must be another SUPERADMIN, never the account itself). It clears the secret, totp_enabled_at, totp_required and every recovery code, logs totp_reset in the activity log, and the operator re-enrols per 8c.2.
  • No second SuperAdmin on the instance: clear it from the database path as koinonia (this is data, not DDL), then re-enrol the same day and note it in the ops log:
    update users set totp_secret_enc = null, totp_enabled_at = null, totp_required = false
     where email = '<ADMIN_EMAIL>';
    delete from totp_recovery_codes
     where user_id = (select id from users where email = '<ADMIN_EMAIL>');
  • Low on recovery codes (the /authenticator page says how many of 8 are left): reset and re-enrol — a fresh set is minted at every confirmation.

8c.4 “Confirm it's you” (elevation)

When a SuperAdmin account has elevation_required set, SuperAdmin-only routes and the sealed finance modules answer 403 {"code": "elevation_required"} until the session proves itself again. For the operator account that proof is the authenticator code: POST /api/auth/totp/elevate {code} re-mints the access token with a 15-minute elev claim (ELEVATION_WINDOW_MINUTES). The web app prompts for it in place.

8c.5 How it is stored

  • users.totp_secret_enc — the shared secret, Fernet-sealed with SECRET_KEY (app/jobs/crypto.py) together with the time-step counter of the last accepted code (the replay guard). A database reader cannot mint codes.
  • users.totp_enabled_at / users.totp_required — enrolled / enforced on /login. For church SuperAdmins who opt in, totp_required is set from User Management (auth policy), not by enrolment.
  • totp_recovery_codes — SHA-256 of each XXXX-XXXX code, used_at stamped on use.
  • Code: backend/app/api/endpoints/totp.py, backend/app/services/totp_service.py; tests in backend/tests/integration/test_totp.py.

9a. Koinonia Platform — Church Subscription & Onboarding Portal

The Koinonia Platform is a separate service from the per-church Koinonia Cloud deployments. It is the public-facing marketing site and church onboarding portal.

GCP service name: koinonia-platform-api  |  Region: us-central1

16.1 Pages and URLs

Page Path Description
Landing page / Public marketing site: features, pricing, testimonials, CTA
Get Started form /get-started.html New church subscription application form
Admin panel /admin.html Internal admin panel for reviewing church applications

16.2 Admin Panel — Reviewing Church Applications

The admin panel at /admin.html is protected by an emailed code (or link) plus a passkey (see 17.1); the email must be on the ALLOWED_ADMIN_EMAILS list of the platform API. The admin token below is the static service token (ADMIN_TOKEN on the platform API, secret koinonia-platform-admin-token) that deploy.sh --platform-token presents when it calls back to mark a church provisioned — it is not a login. Historically the panel was protected by that token (not a user account). To log in:

  1. Navigate to /admin.html
  2. Enter the admin token (stored in Secret Manager as koinonia-platform-admin-token)
  3. Click Login

Each application card shows: church name, EIN, size, denomination, contact information, selected plan, submission timestamp, and status (Pending, Approved, or Provisioned).

Approving an application

  1. Click Approve on the application card
  2. Select the billing plan from the dropdown
  3. Confirm — the system emails the church a Stripe payment link and records the approval timestamp

Rejecting an application

  1. Click Reject on the application card
  2. Enter a rejection reason (this is sent to the church in the rejection email)
  3. Confirm

16.3 Provisioning After Payment

Once the church completes Stripe payment (verify in Stripe dashboard), run the two-command provisioning sequence from the koinonia-cloud repo root:

# Step 1 -- Store secrets for the new church (skips admin credentials -- auto-derived)
./deploy/secrets.sh --church-id {church-id} --interest-id {application-id}

# Step 2 -- Provision GCP resources + seed the church instance
./deploy/deploy.sh --church-id {church-id} --interest-id {application-id} \
  --platform-url https://koinonia-platform-api-3gkbpl3h6q-uc.a.run.app \
  --platform-token {ADMIN_TOKEN}

Application status lifecycle: pending → approved (admin approves) → provisioned (deploy.sh completes)

Tip: Retrieve the admin token with: gcloud secrets versions access latest --secret=koinonia-platform-admin-token --project=koinoniacloud-490205

16.4 Stripe Payment Plans

The plan keys below map 1:1 to the PAYMENT_LINKS dict in backend/app/api/endpoints/applications.py and to PLAN_OPTIONS in frontend/admin.html. The matching STRIPE_LINK_* env vars hold the Stripe Payment Link URL for each (created in Stripe Dashboard → Payment Links). Pricing on this page should match what's displayed in the admin approval dropdown.

Plan key Label Audience
small Koinonia Cloud ~ Small ($100/mo) Up to 150 members
medium Koinonia Cloud ~ Medium ($500/mo) Up to 800 members
large Koinonia Cloud ~ Large ($1,000/mo) Over 800 members
kpa Koinonia Pastoral Assistant only ($50/mo, 21-day trial) Churches that already have a ChMS and only want KPA
kpa_small KPA + Koinonia Cloud ~ Small ($150/mo) Small church + KPA bundle
kpa_medium KPA + Koinonia Cloud ~ Medium ($550/mo) Medium church + KPA bundle
kpa_large KPA + Koinonia Cloud ~ Large ($1,050/mo) Large church + KPA bundle
beta Koinonia Cloud — Beta (free) Evaluation only. Do not approve paying churches onto this tier — Stripe skips card collection at checkout for $0 products.

16.5 Database

The platform uses its own PostgreSQL database (separate from per-church databases):

  • Cloud SQL instance: koinonia-instance
  • Database name: koinoniaplatform (no underscore or hyphen)
  • User: koinonia

16.6 Secret Manager

All platform secrets are prefixed koinonia-platform-* in Secret Manager:

Secret name Contains
koinonia-platform-db-password PostgreSQL password
koinonia-platform-admin-token Admin panel login token
koinonia-platform-admin-email Admin notification email address
koinonia-platform-postmark-token Postmark server token
koinonia-platform-smtp-from Sender email address
koinonia-platform-smtp-from-name Sender display name
koinonia-platform-stripe-link-* Stripe payment links (8 total — see §16.4)
koinonia-platform-admin-url Full public URL of the deployed service

16.7 Deploying and Updating

cd /mnt/AntiGravity/KoinoniaCloud/koinonia-platform

# Build and push the image
sg docker -c "docker build -t us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-platform:latest -f backend/Dockerfile ."
sg docker -c "docker push us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-platform:latest"

# Deploy to Cloud Run
gcloud run deploy koinonia-platform-api \
  --image us-central1-docker.pkg.dev/koinoniacloud-490205/koinonia/koinonia-platform:latest \
  --region us-central1 \
  --platform managed \
  --allow-unauthenticated \
  --add-cloudsql-instances koinoniacloud-490205:us-central1:koinonia-instance
Important: Use --update-secrets (not --set-secrets) when adding or modifying individual secret bindings. --set-secrets replaces ALL bindings, which will disconnect any secrets not listed in the command.

16.8 Architecture Notes

  • FastAPI serves frontend static files from /app/static/ using Starlette's StaticFiles(html=True).
  • The /get-started path is handled by an explicit FastAPI route that returns a RedirectResponse to /get-started.html.
  • The PORT environment variable is injected by Cloud Run (typically 8080).
  • CORS is configured via the CORS_ORIGINS environment variable. Set to * for the public platform.

9b. Command Center — Fleet Monitoring & Operations

The Command Center is the operational dashboard built into the Koinonia Platform admin portal. It gives Unbalanced Force administrators real-time visibility into all church GCP instances and the ability to take operational actions directly from the browser.

The Command Center opens as a Room. At the root URL (/) the Command Center is now the operator's office, built on the shared Unbalanced Force Studio catalog (the same furniture family as a church's Finance Office): the fleet of churches as books on shelves, spine colour = health (a church that needs attention glows and sits on the "needs attention" shelf), a desk with Costs / Records drawers, the cork board of what needs you, the onboarding in-tray, the fleet charts and KPIs, a clock. It fills with live fleet data and refreshes every 30 seconds. Every object opens as a take-down pane inside the room, not by leaving it. Clicking a church book opens the Operations screen with that church already selected and ready to manage. Clicking the Costs drawer or the fleet-cost chart opens the cost pane — this month vs last month, switchable day by day, week by week, or calendar quarters — drawn from the same cached cost data as the Costs tab (it never triggers a BigQuery query, so opening the room is free). Every other object (Fleet overview, Applications, Quality, Training videos) opens that same console screen embedded in a pane and re-dressed in the room's walnut motif — the identical screen, JS and actions as the classic console, only re-skinned, so there is nothing to drift. The classic tabbed console still lives at /admin.html as the full-window fallback and is described below. First visit each session: sign in on the classic console (/admin.html) once — it stores the operator token the room uses.

The admin portal has seven tabs (Costs is the first/default):

Tab Purpose
Costs (default landing tab) GCP FinOps reporting + adversary-detection panel: MTD/forecast tiles, per-service table with 30-day sparklines + spike deltas, per-church attribution, and a "what changed today" panel for IAM/Cloud-Run/Secret-Manager events outside CI. See 17.5.
Applications Review and approve/reject church subscription applications (Section 9a)
Fleet Monitoring Real-time health, metrics, and logs across all church instances, plus the Configuration Drift panel (see 17.2)
Operations Restart, redeploy, pause/resume, and run migrations on church services
Quality Test-run mirror from koinonia-cloud CI: status strip per gate × target, 30-day pass-rate sparkline, run-detail drill-down, and Gate C smoke trigger. See 17.4.
Training Videos Which User Guide videos each church watches: plays, minutes, how many watch to the end, and the Helpful? 👍/👎 answers. Anonymous totals. See 17.6.

17.1 Accessing the Command Center

Day to day: click “🔑 Sign in with your passkey” — one tap and your face, fingerprint or device PIN; no email. No Google sign-in script is on the page (it reported every Command Center visit to Google).

  1. Go to https://command.koinoniacloud.com/admin.html and bookmark it. Always use this one address: a passkey belongs to the address it was made on, so the passkey step fails on the service's …run.app addresses. The address is a Cloud Run domain mapping to koinonia-platform-api with a DNS-only Cloudflare CNAME to ghs.googlehosted.com (created 2026-11-26).
  2. The first time on this address (or on a device without your passkey): enter your email and click Email me a code. Only addresses on ALLOWED_ADMIN_EMAILS get an email (the page answers the same either way). Type the 6-digit code and click Confirm — or tap the link in the same email. Code and link work once, expire in 10 minutes, and five wrong codes spend the email. Then Create my passkey (or, on a device that has it, Use my passkey).
  3. Every time after: 🔑 Sign in with your passkey.

Signing in on another computer: approve on your phone

On a computer that doesn't hold your passkey, your phone approves the sign-in.

  1. Once, on the phone: sign in at https://command.koinoniacloud.com/admin.html, click 📱 Approval phones in the header, then Make this device an approval phone and allow notifications. Send a test checks it. On an iPhone, first add the page to the Home Screen (Share → Add to Home Screen) and open it from there; Safari tabs can't receive notifications. The same panel lists your approval phones and removes one.
  2. On the other computer: enter your email and click 📱 Approve on my phone. The page shows a two-digit code and waits.
  3. On the phone: tap the “Command Center sign-in” notification. It names the browser asking and shows the code. If the code matches the computer's, tap Approve with my passkey (face, fingerprint or PIN); otherwise tap Deny. The computer signs in within two seconds.

A request lasts 3 minutes and works once. An email gets at most 3 requests in 10 minutes, and only addresses on ALLOWED_ADMIN_EMAILS get a notification (the page answers the same either way). A notification you didn't ask for means someone typed your email on the sign-in page: tap Deny. Requests are kept in admin_login_approvals. The computer's session is the same 8-hour JWT as a passkey sign-in.

Only a passkey that verifies issues the session: a short-lived JSON Web Token (JWT) (8 hours) stored in sessionStorage for that browser tab. Clicking Sign out or closing the tab destroys it.

A new device: once you have a passkey, the inbox alone can't create another — approve the sign-in on your phone (above), or use a synced passkey (iCloud Keychain, Google Password Manager, 1Password…) or a security key. Lost every passkey? Delete your rows from admin_passkeys in the platform database (DELETE FROM admin_passkeys WHERE email = '<you>';), then sign in by email and create a new one.
Authorized Admin Whitelist: The list of emails permitted to access the Command Center is restricted via the ALLOWED_ADMIN_EMAILS environment variable on the platform API service. A sign-in asked for any other address sends nothing and is logged as a warning.

17.2 Fleet Monitoring Tab

The Fleet Monitoring tab provides a single-pane view of all church instances. Data is loaded from GCP Cloud Run, Cloud Logging, and Cloud Monitoring APIs.

Stats Row

Five summary tiles at the top:

Tile What it shows Notes
Churches Count of active church instances Excludes platform infrastructure
Services Total Cloud Run services across all churches Excludes platform services
Active Users (24h) Approximate unique users Based on distinct IP addresses in API request logs
5xx Errors (24h) Total server errors Investigate via church drill-down if count is high
Auth Failures (24h) Failed authentication attempts Uses AUTH_FAIL structured logging

Fleet Status Grid

Shows a card for each church with:

  • Church name (the {church-id} from the service naming convention)
  • Service status dots — green (running), yellow (reconciling/deploying), red (paused)
  • Revision suffix — the short hash of the currently deployed Cloud Run revision
  • Paused badge — if the church has been scaled to 0 instances

Click a church card to open a drill-down modal showing recent API logs (last 6 hours) with severity color-coding and a Manage button that jumps to the Operations tab.

Request Volume (24h)

A bar chart showing hourly request counts across all churches. Hover over a bar to see the exact time and count.

Resource Utilization (1h peak)

A table showing CPU and memory utilization (p99 over the last hour) for each Cloud Run service:

Color Meaning
Green Under 50% utilization
Yellow 50% – 80% utilization
Red Over 80% utilization — investigate or scale up

Cloud SQL Health

Gauge bars showing the shared Cloud SQL instance health: CPU, Memory, Disk, and Connections.

Auth Failure Log

A filterable table of failed authentication attempts. Filter by time window (1h, 6h, 24h, 3d, 7d) and by church.

Church Word engagement (how many people play the daily word game)

Church Word is the daily five-letter word game on every church’s Welcome page. This section shows how many people play it, church by church and fleet-wide, so you can gauge engagement over time. It sits under Fleet Status in the Fleet Monitoring tab and does not load by itself: it asks every running church for its numbers (a church scaled to zero wakes to answer), so press Load, choose a span (7 days, 30 days, 90 days or a year) and read the result. Nothing is stored in the Command Center — each church is the record and is asked each time.

  • Top tiles — players today, games started, the share solved (of the games finished, solved or out of tries), shares (Copy/Share taps on the result card), and how many churches have players in the span.
  • The bars — players who started the day’s word, all churches added together, one bar per day from launch (October 29, 2026) or the start of the span.
  • Per church — today, average players per day, days with any play, percent solved, average tries (over solved games), shares, and the best day: the busiest day’s players and that as a percentage of the church’s sign-in accounts, a rough measure of how much of the congregation plays. The small bars are the last 30 days. Churches that cannot be reached, or that have not been redeployed with Church Word yet, show a grey line instead of numbers.

It is anonymous. The numbers here are only a count per day (started, solved, failed, tries, shared) that each church keeps in its own database — never who played, which device, or what was guessed — and these counts are deliberately not part of a church’s backup, because they are Unbalanced Force engagement data, not church data. (Separately, each church keeps every signed-in person’s own game so it follows them between devices and a finished day stays finished; that is the church’s own data, it is part of the church’s backup, and the Command Center never reads it.) Because a person’s game is kept on the server, a person cannot replay a finished day, so the figures are a close measure of how many people play. The Command Center asks each church with its own scheduler secret, never with a person’s login.

On-Prem Activity (per-church attribution for self-hosted services)

Four services run on-premises through the Cloudflare Tunnel rather than on Cloud Run: the Pelias Geocoder (address-to-coordinate lookups), the Tile Server (Caddy serving world.pmtiles to MapLibre on every Member Map and Bible Atlas view), Valhalla Routing (driving directions and pastoral-visit optimization), and the PostGIS POI service (rich OSM attribution on Member Map POI clicks — phone, hours, website, accessibility, etc.). Because they don't run in GCP, they don't appear in the Cloud Run-derived metrics above. The On-Prem Activity card surfaces them with 100% per-church attribution.

The card shows four panels (Geocoder, Tile Server, Routing, POI). Each panel has:

  • Three count tiles — today, last 7 days, last 30 days
  • 24-hour sparkline — hourly request volume so traffic spikes are visible at a glance
  • Per-church table — rows showing each church's request count, sorted descending. A request with no recognized identity falls into unknown — investigate if you ever see it.

How attribution works (different per service, same destination table):

Service Attribution mechanism Why this approach
Geocoder (Pelias) FastAPI sidecar proxy on :4002 reads the CF-Access-Client-Id header that Cloudflare Access stamps on every authenticated request, looks up the church via CF_CLIENT_TO_CHURCH in the proxy's .env, and forwards to Pelias on :4000 unchanged. Geocoder volume is low (one request per address) so in-path counting is fine.
Tile Server (Caddy) Each church's frontend requests tiles at tiles.koinoniacloud.com/{church_id}/…. Caddy strips the prefix before serving the file and writes a JSON access log line. A Python aggregator service (koinonia-tile-aggregator.service) tails the log, groups by prefix + hour, and pushes totals to the platform every 5 min. Tile volume is 50–200 requests per map view; in-path counting would add latency.
Routing (Valhalla) FastAPI sidecar proxy (koinonia-routing-proxy.service) on :8003 reads the CF-Access-Client-Id header and forwards to Valhalla on :8002 unchanged. Same in-path pattern as the Geocoder. Counts each call to /route, /optimized_route, /sources_to_targets. Routing volume is low (one call per visit-plan optimize or one call per Get-Directions tap); in-path counting is fine.
POI (PostGIS) FastAPI service (koinonia_poi_proxy Docker container) on :8007 reads the CF-Access-Client-Id header and answers the spatial PostGIS lookup directly — it's not a passthrough proxy, it's the query implementation. Body-blind: the user's lat/lon click target never leaves the workstation in any log. One call per Member Map POI click. The query (KNN on a GIST index over ~6.4M rows) returns in <100 ms.

Privacy boundary: only (source, church_id, hour, count, bytes) leaves the on-prem workstation. The proxy never reads request/response bodies (which contain addresses and coordinates). The Caddy log is filtered to strip client_ip, remote_ip, User-Agent, Referer, Origin, and Cookie before any aggregator process can read it.

Data freshness: ~5 minutes. Both aggregators flush hourly buckets to the platform every 5 min. A bucket can be re-pushed safely — the platform side upserts on (source, church_id, hour_bucket).

Onboarding a new church: two one-time edits, both mechanical.

  1. Geocoder: create a new Cloudflare Access service token named after the church, append the new <client-id>.access:<church-id> pair to CF_CLIENT_TO_CHURCH in koinonia-geocoder/proxy/.env via scripts/setup_geocoder_proxy_env.py, then sudo systemctl restart koinonia-geocoder-proxy. Until the mapping is added, that church's geocoder requests still work but get attributed to unknown.
  2. Tile Server: nothing to do — the /<church-id>/ tile prefix is resolved at runtime, and the aggregator picks up the new prefix on its own. Because the frontend image (koinonia-frontend:latest) is shared across every church, the church id can't be baked at build time (whichever church deployed last would win the shared tag — that's what logged baylife's tiles under baylife-test). Instead deploy.sh sets a CHURCH_ID runtime env on the church's backend, the frontend reads it from /api/church/public-info, and MapLibre stamps the /<church-id>/ prefix onto every tile request. Do not hand-set NEXT_PUBLIC_TILE_BASE_URL; it is ignored. To point at a non-default tunnel, override the host only via TILE_TUNNEL_HOST (mirrors POI_URL / PELIAS_API_URL). The default host is currently the dev tunnel (tiles-dev.koinoniacloud.com) because the prod tiles.koinoniacloud.com tunnel is not stood up yet.
  3. Routing & POI: both reuse the same per-church service token as the Geocoder, and both read their CF_CLIENT_TO_CHURCH mapping from their own proxy/.env. Append the same <client-id>.access:<church-id> pair to each (koinonia-routing/proxy/.env, koinonia-poi/proxy/.env) and restart: sudo systemctl restart koinonia-routing-proxy for Routing; sg docker -c "docker compose -f /mnt/AntiGravity/KoinoniaCloud/koinonia-poi/docker-compose.yml restart proxy" for POI (it's a compose service, not a host systemd unit). Same fall-through to unknown attribution as the Geocoder until the mapping is added.

Health checks (workstation side):

systemctl status koinonia-geocoder-proxy
systemctl status koinonia-tile-aggregator

# What's queued for the next push (rows where flushed_at IS NULL)
sqlite3 /var/lib/koinonia-onprem-activity/proxy.sqlite \
  "SELECT church_id, hour_bucket, count FROM counts WHERE flushed_at IS NULL"

The aggregators tolerate platform-side outages: counts accumulate in local SQLite and flush whenever the platform is reachable again, so a Cloud Run incident doesn't lose attribution data.

Configuration Drift panel

Directly under Fleet Status. It reads the live Cloud Run spec of every koinonia-{id}-api, -web and -sse service through the Cloud Run Admin API and lays the churches side by side, one row per setting: environment variable names and their source (plain literal, or 🔒 a Secret Manager reference), min/max instances, concurrency, timeout, CPU/memory, CPU throttling, startup boost, ingress, image and sidecars (any extra containers beside the app). Secret values are never read or stored.

Test twin parity. Bay Life, the pilot church, has a development twin (baylife-test); churches provisioned from now on do not get one, and the box appears only for a church that has a -test twin. At the top of the panel the church is compared with its twin across all three services. Only two differences are allowed, each shown with its reason: the twin’s web app scales to zero, and the twin has no Billing Inbox address (it has no inbound mail stream). Anything else is listed as an unexplained difference — a rehearsal on the twin doesn’t prove the church until it is resolved or added to the allowed list (ALLOWED_TWIN_DIFFS in core/config_snapshot.py). Until 2026-11-09 the panel read only the first container, so baylife-test ran a PgBouncer + cloud-sql-proxy pair for months without it showing; sidecars are now compared too.

Why it exists. On 2026-09-09 a baylife production deploy failed because POSTMARK_WEBHOOK_USER had been set by hand on the Cloud Run service as a plain value months earlier — it existed nowhere in deploy.sh — and a change that mapped the same name as a secret reference collided with it (Cloud Run refuses to change an env var's source type in one step). The connection-pool settings (DB_POOL_SIZE, DB_MAX_OVERFLOW) reached baylife-test and never production the same way. The scripts describe how a service would be provisioned; the running spec is the truth, and until this panel it lived only in Cloud Run.

  • Show only differences (default on) hides every row that is identical across the fleet. Rows that differ are highlighted; a red — means that church does not have the setting at all. Settings that are church-specific by design (CHURCH_ID, PUBLIC_URL, CORS_ORIGINS, GCS_BUCKET_NAME, …) are tagged per-church and never count as drift. Per-church secret names are compared with the koinonia-{id}- prefix removed, so every church referencing its own copy of the same secret is consistent, not drifting.
  • Recent configuration changes is a change log. A new snapshot row is written only when a service's normalized spec changes, and each row records what moved: env vars added or removed, an env var switching between plain and secret, and settings changes with before/after values. This answers "who set that by hand, and when" in one glance — pair it with the What changed today panel on the Costs tab for the actor.
  • Poll now forces a fresh read. Opening the tab polls automatically when the last poll is older than 15 minutes. The platform service account already holds roles/run.developer, which covers the read.
Before changing how deploy.sh sets any env var, check this panel. If a church shows the variable as plain and the script is about to set it as a secret reference (or vice versa), the deploy will fail on that church. Migrate it first on the running service: gcloud run services update koinonia-{id}-api --remove-env-vars=NAME --update-secrets=NAME=koinonia-{id}-secret:latest, then deploy.

Data lives in the platform table church_config_snapshots; endpoints are GET /api/admin/config/fleet and POST /api/admin/config/refresh (UF Admin only).

Configuration Drift panel

Below the metrics, the Configuration Drift panel shows every church's live Cloud Run configuration side by side — one column per church, grouped by service kind (api / web / sse / worker): image tag, sidecars, CPU/memory, min/max instances, concurrency, timeout, and every environment variable recorded as plain (literal value), 🔒 (a Secret Manager reference) or — (not set on that church). Values themselves are never shown — only names and sources. Anything that differs between churches of the same kind is highlighted, which is how a hand-set variable on production (the kind deploy.sh never wrote) is caught before it surprises a deploy.

Snapshots are taken from the Cloud Run API on first view and whenever the last poll is older than 15 minutes; ↻ Poll now forces one. A row is written only when a service's normalized config actually changed, and Recent configuration changes lists those rows — what changed, on which church, when — so a deploy or a manual gcloud run services update leaves a trail. Backed by core/config_snapshot.py and the church_config_snapshots table; endpoints GET /api/admin/config/fleet and POST /api/admin/config/refresh.

17.3 Operations Tab

The Operations tab lets you take actions on individual church instances. All actions require confirmation before executing.

Selecting a Church

Use the Select Church dropdown at the top. After selecting a church, you'll see its current status and the action cards: Usage Heat Map, Restart Services, Redeploy Services, Scale Church, Dev Session (Stop / Start DB), Database Scaling, Database Migrations, Data Integrity (The Shield), File Recovery, Recover Deleted Records, Recover Church In-Place and The Lab (Staging & Testing).

Is anyone using the platform? (Check now)

The deploy-safety check at the top of Operations. It reads the last 15 minutes of request logs and asks each church who is signed in. BUSY = check-in, attendance or an import is running, or someone saved a change in the last 5 minutes — don’t deploy. ACTIVE = people are using it but nothing is mid-edit; the line says “N signed in and active (from the church)” when the church reports real signed-in people, or “browser activity but no one signed in has been active” when only a public page or sign-in screen is being used. CLEAR = no human traffic. A page left open on someone’s laptop does not count: its own 5-minute connectivity check is marked as background traffic and ignored. Bots, monitoring and the iOS check-in app are classified separately (the iPad counts as a person).

Restart Services

What it does: Forces Cloud Run to create a new revision from the same container image. Rolling restart with zero downtime.
When to use: Stale container state, after changing a Secret Manager value, general troubleshooting.
Buttons: Restart API | Restart Web

Redeploy Services

What it does: Creates a new revision that pulls the latest container image from Artifact Registry.
When to use: After building and pushing a new Docker image.
Buttons: Redeploy API | Redeploy Web

Scale Church (Pause / Resume)

Pause — scales both the API and Web services to 0 instances. The church site goes offline and billing stops.
Resume — restores normal scaling (0 min, 10 max instances). Cloud Run will cold-start on the next request.

When to use: Pause a demo overnight, temporary maintenance, shut down a cancelled church without deleting resources.

Note: Paused churches appear dimmed in the Fleet Status grid with a yellow "Paused" badge and red status dots.

Dev Session (Stop / Start DB)

What it does: Parks a low-traffic or test instance (e.g. baylife-test) between development sessions to trim idle cost, with an optional pre-warm so it's responsive the moment you start. The card shows a live Database: Running / Stopped state line.
When to use: You develop against a test church only occasionally and want to stop paying for its idle database in between — then bring it back up (and warm) before a session.

  • Start DB — sets the Cloud SQL instance's activation policy to ALWAYS. The instance takes ~1–2 minutes to accept connections, so start it before you begin working.
  • Stop DB — sets activation policy to NEVER. Cloud SQL compute billing halts while stopped; storage and automated backups are retained. The church's API cannot serve DB-backed requests until the instance is started again. (Confirmation required.)
  • Pre-warm API+SSE (min 1) — holds the church's API and SSE services at min_instance_count=1 so the first request skips the cold-start and the on-boot Alembic migration pass. Web is left alone (deploy.sh already sets it min 0 and it cold-starts fast).
  • Release API+SSE to 0 — returns both to scale-to-zero (min 0) so neither bills while idle.
Always Release to 0 after testing a deploy. deploy.sh deliberately deploys api and sse at --min-instances=1 (prod SSE needs a warm instance to hold streaming connections), so every deploy re-warms the church — including a test church you had parked. A warm instance bills 24/7 even while completely idle. On 2026-07-07 this bit us: baylife-test was deployed, Release dropped only the api, and the orphaned sse instance billed for a week unnoticed (Release now covers both). The church-status line at the top of the tab shows ⚠ warm listing any service held at min > 0 — if you see it on a parked church, hit Release.
Stop DB vs. Pause Church: Pause Church scales the Cloud Run services to 0 but leaves Cloud SQL running. Stop DB powers off the database itself — which Cloud SQL cannot auto-scale to zero, so it's the larger idle cost on a rarely-used instance. For a full park-it-cold, use both.
Do not stop a production church's database. Reserve Stop DB for test / demo instances. Platform infrastructure is blocked from these actions automatically.

Run Migrations

What it does: Executes the church's one-shot migrate job (koinonia-<id>-migrate, alembic upgrade head + seed) — the same job a deploy runs. It is idempotent and does not restart the API. The job is pinned to the church's currently-deployed image, so it can never apply migrations ahead of the running code.
When to use: Rarely — migrations normally run automatically at deploy time. Use this only to re-assert the schema on the currently-deployed image. (Production church APIs run with RUN_MIGRATIONS_ON_STARTUP=0, so a plain restart would not migrate.)

Data Integrity (The Shield)

Prevention and validation tools to ensure data safety before operations begin.

  • Deletion Protection Toggle: Prevents accidental deletion of database instances or backups.
  • Instant Snapshot: Manual point-of-return backup triggered before high-risk changes.

File Recovery

Puts back an earlier version of an uploaded file (a photo or document) that was overwritten or deleted, from the church’s file version history (older versions are marked [OLD VERSION]). For the database there is one tool per job: Recover Deleted Records for one record, Recover Church In-Place to rewind the whole church, and The Lab → Forensic copy (look only) to inspect past data without changing anything.

Recover Deleted Records (surgical)

What it does: Puts one deleted family or person — and everything the delete took with it (household links, volunteer roles, group memberships, support needs…) — back into the live church without rewinding anyone else. The church keeps running the whole time.

You need three things from the church. The Command Center cannot see a church’s data, so ask the church’s SuperAdmin to open Audit Log and read you the table (for example families), the record id, and when the delete happened. Pick a minute just before it. Nothing else about the church’s data is typed here or sent anywhere.

Or the church can ask you. On a person or household deleted for good (Delete immediately, or the end of the 7-day wait) — and only there, within 7 days of the removal — a SuperAdmin’s Audit Trail offers Ask support to bring this back. Everything else has a free in-app fix (Revert, Cancel deletion, Undo this delete), so the church is not offered support for it. The request sends only the table, record id and a minute shortly before the delete — never a name or any detail — and it appears at the top of this window as Requests from <church>. Use fills in the three fields for you (the minute shows in your local time); Dismiss clears a request you will not act on. A request is marked done automatically when you apply the recovery from it. Each church may have 5 open requests at a time, and the same request twice is one.

Metered by support plan. Each church’s plan includes a number of operator-run recoveries per period (platform service settings RECOVERY_INCLUDED_PER_PERIOD, default 2, and RECOVERY_PERIOD_DAYS, default 365; the wording of the fee comes from RECOVERY_FEE_NOTE, default “billed at $50.00”). The standard plan is 2 included recoveries a year, then $50.00 each. Before sending, the church is shown how many it has used. Once they are used up, the church must tick that it agrees to the fee, and the request arrives marked BILLABLE; invoice it when you complete it. A request you Dismiss (for example one the church could have undone itself) does not count against the plan. The window’s request list shows each church’s usage. Requests are not announced by email or page — open the window to see them. They reach back 7 days from the removal — the length of the database’s change log.

Two steps, on purpose.

  1. Preview — makes a temporary copy of the database at that minute (about 10–15 minutes), works out which rows would come back, and writes nothing. While it runs the window shows which step it is on and how long it has taken. When it finishes, the window shows the plan itself — each record type, how many rows existed at that minute, how many are in the church now, and how many will be put back — and fills in the total for you. (The plan is record types and counts only; it is read from the run’s own log.)
  2. Put them back — check the plan and confirm; the number is already filled in. A safety backup is taken first (the window shows its id when it finishes — restore it with Recover Church In-Place to undo), then only the missing rows are inserted. The window ends with a large green or red result. If the plan no longer adds up to the number you typed, it refuses and writes nothing. In the same transaction it writes a Restored by support entry (by Unbalanced Force support) into the church’s own Audit Trail for every row it put back, and marks the delete they answer as undone — so the church can see what came back.

The window stays open until you click Close or × — a click outside it does nothing (true of every Command Center window). If you do close it after a preview, reopen it and click Use on the same request (or enter the same table, id and minute): the finished preview comes back and you can go straight to Put them back.

It only adds; it never changes an existing row. A family or person that exists in the church today is left exactly as it is, even if it is archived. Money rows (giving, receipts) that belong to a restored person are copied back as they were at that minute — check the preview’s table list for them before applying. Try the church’s own Archive Management first: an everyday delete only archives, and un-archiving is one click for the church.

What reaches GitHub: table names, row counts and primary-key numbers — never names, addresses or notes. The temporary copy costs a little while it exists and is deleted at the end of every run, even a failed one. The same workflow (Recover Deleted Records) can be started by hand from the GitHub Actions page if the Command Center is down. Technical detail: docs/runbook_surgical_row_recovery.md in the koinonia-cloud repo.

Recover Church In-Place

What it does: Brings the same church back at its own id and URL from one of its backup runs or from a minute you choose — one click, no gcloud/psql/Alembic. It takes a safety backup of the current state first (restore that to undo), restores the chosen backup run in place onto koinonia-<id>-db, then migrates and redeploys all services automatically, cutting traffic over only after health checks pass. Because the church id is unchanged, identity secrets (SECRET_KEY, VAPID push keys) are reused, so active sessions and push subscriptions survive — unlike Recover from Complete Backup, which stands up a new instance at a new URL.

When to use: A live church needs to be returned to a recent good state (bad import, corruption, a destructive mistake). For a production church you must type the church id to confirm; the church is briefly offline during the in-place restore.

Choosing a specific minute (point-in-time): pick A specific minute instead of a backup to undo everything after a moment — for example the minute before a bad deploy. Enter the time in your local time; the page shows the UTC minute that will actually be sent, and only minutes inside the church’s recovery window (the last 7 days) can be picked. Behind the scenes the church is safety-backed-up first, the database is cloned to that minute, and the clone is restored onto the live instance (Cloud SQL cannot rewind an instance in place), then the church is migrated and redeployed as above. The temporary copy is deleted automatically, even if a step fails. It takes about 25–40 minutes (the copy is the slow part) and the church is briefly offline during the restore. Measured on baylife-test (2026-11-14): the rewind took 31½ minutes and its undo 15½, but the church’s data was unreachable for only about 2 minutes of each. While it runs the window shows the current step and the time so far, and it ends with a large green or red result and the safety backup’s id.

A rewind loses everyone’s changes after that minute, not just the mistake. Every person, every record. The safety backup taken first is the way back: restoring it returns the church to how it was just before the rewind. To undo one deleted family or person without rewinding anyone else, do not use this — use Recover Deleted Records (above).

Choosing the recovery point: the list shows only finished backups, plus Latest successful backup. Each is named for what it is. Safety backups come first, in green, named for what they undo — UNDO — the church just before it was restored to … or UNDO — the church just before support put back individuals #…. Watch for the one marked in red, Taken right after a restore: Cloud SQL takes it automatically after every restore and it holds the restored state, so restoring it undoes nothing — and right after a rewind it is the newest backup, so Latest successful backup would pick it too. Then nightly backups, newest first. Backups that are still running or that failed are left out (a line under the list says how many). To recover to a moment you choose, click Snapshot first, wait for it to finish, and it appears in the list. The same rule applies to the backup list under Restore a backup. A run that ends with a data check in its GitHub summary shows the schema version, row counts, and how many rows are newer than the recovery point.

Works even if the Command Center is down. The button simply dispatches the recover-church.yml GitHub Actions workflow. If the Command Center itself is unavailable, fire that workflow by hand from the GitHub Actions UI with the church id and (optionally) a backup run id — the recovery does not depend on the platform backend being healthy.

The Lab (Staging & Testing)

Productivity tools for evaluation.

  • Clone Sandbox Environment: Creates a copy of a church environment for testing without risk.
  • Forensic copy (look only): Makes a separate database instance as the church was at an exact second in the last 7 days, to look at past data (“what did this record say on Tuesday?”). The live church is never touched. It bills until you delete it — delete it the same day. It is not a recovery tool: to change the church use Recover Church In-Place or Recover Deleted Records, which make and delete their own copy.

Safety Features

  • Confirmation dialogs — every action shows a dialog with the church name and action description before executing
  • 3-second cooldown — after any action, the button is disabled for 3 seconds to prevent accidental double-clicks
  • Toast notifications — success/failure messages appear as floating notifications
  • Platform protection — the system prevents you from pausing, restarting, or redeploying the platform infrastructure itself

17.4 Quality Tab — Test execution mirror

Evidence Pack (top of the Quality tab)

Run evidence pack re-proves, read-only, every claim in the data-protection report (koinonia-cloud/docs/data_protection_and_recovery.pdf) — backups, point-in-time recovery, deletion protection, file versioning, public-access prevention, least privilege, data-access audit logs, TLS and headers — plus the security tooling (open Dependabot alerts, the latest security-scan, test and posture runs). It runs as GitHub workflow evidence-pack.yml under the read-only service account evidence-reader@, which can see settings and metadata only (object names in the exports bucket, never contents, data or secret values). Each run takes about 2 minutes; the list shows the latest runs. Open a run for the PASS / FAIL table; its artifact (kept 400 days) is the dated, checksummed record to hand an underwriter. It also runs every Monday on its own and pages the security ntfy topic if any claim has stopped being true. Lines marked “recorded” are facts noted without a pass/fail judgement (for example: TLS mode, single-zone database). The same check can be run on a workstation: python3 tools/security/evidence_pack.py.

The Quality tab gives Unbalanced Force admins a glanceable view of the koinonia-cloud test suite's health: are the tests passing, are they being run, and what broke when they didn't? It mirrors every CI run (Gate B push, Gate C post-deploy smoke, future Gate D fleet probes) into a local table on the platform DB and renders the result as a status strip + recent-runs table + drill-down modal. See docs/plan_test_command_center.md for the full design + step-by-step roadmap.

The status strip

One chip per (gate, target) pair active in the last 30 days. Chip layout:

  • Status dot — green = last run passed, red = last run failed, amber = stale (no recent run, see below).
  • Title row — gate label (Gate B / C / D) + target name when present (e.g. baylife-test for Gate C).
  • Time + duration — how long ago the most recent run started, and how long it took.
  • Totals row — pass / fail / flaky / skip counts from the most recent run.
  • 30-day sparkline — one square per day, green if all runs that day passed, red if any failed, grey if no runs that day. Hover any square to see the date, run count, and pass rate. Footer line summarizes "N runs · M bad days" for quick triage.

Click any chip with a recent run to open the run-detail modal: failed test names, failure signatures, flaky cases, and a link to the GitHub Actions run for the full log.

Quiet alarm — "Stale" detection

Tests that quietly stop running are a worse failure mode than tests that run and fail loudly. The strip flags this: when no run has happened in the threshold window for a given gate, the chip's dot turns amber and a Stale (Xd) tag appears next to the gate label. A passed-but-ancient run no longer reads as healthy green.

Gate Stale threshold What stale tells you
B (CI on push) 24 hours Either nobody pushed in a day, or the workflow itself is broken and not posting back.
C (post-deploy smoke) 7 days Nobody verified a deploy in a week. If you've deployed since then, you skipped the smoke.
D (per-church probe, future) 24 hours The scheduled probe didn't run. Cloud Scheduler issue or platform ingest issue.

Trigger Smoke Test (Gate C button)

Top of the Quality tab. Select a target from the dropdown, click Run Smoke Test, confirm. The platform calls GitHub's workflow_dispatch API on the billburnham/koinonia-cloud repo, propagating your admin email through as the actor input so the resulting run is attributed to you (not the bot account that owns the dispatch token).

Per-target rate limit: a single target can be re-triggered at most once per minute. The button disables for 60 seconds after a dispatch to prevent double-clicks. If GitHub returns an error (401 bad token, 422 invalid target, etc.) the rate-limit stamp rolls back so a transient failure doesn't lock you out.

Required env vars on the platform service for this button to work:

  • GITHUB_DISPATCH_TOKEN — fine-grained PAT with Actions: read & write on koinonia-cloud. Stored as Secret Manager entry koinonia-platform-github-dispatch-token. If unset, the button returns 503.
  • GATE_C_TARGETS — CSV of allowed church IDs. Defaults to baylife-test. Must match smoke.yml's target enum on koinonia-cloud; update both when onboarding.

Recent runs table

Below the status strip: the 50 most recent runs across all gates and targets, newest first. Click any row to open the run-detail modal. Useful when you need to see history beyond "the latest run per cell" — e.g. checking whether last night's Gate B run was the one that broke things, or comparing two smoke runs against the same target.

How data flows in

  1. A koinonia-cloud workflow runs (push CI, smoke, etc.).
  2. The job emits JUnit XML via --junitxml (pytest), --reporter=junit (Vitest, Playwright).
  3. An if: always() step runs scripts/ci/post_test_run.py from the koinonia-cloud repo, which parses the JUnit XML and POSTs to POST /api/admin/test-runs/ingest on the platform.
  4. The ingest endpoint authenticates the POST via the shared X-Ingest-Token header (matching PLATFORM_INGEST_TOKEN on both ends), writes a row to test_runs + per-test rows to test_cases. Idempotent on workflow_run_id — if the same run posts twice, the second wins.
  5. The Quality tab fetches /strip, /trend, and /{run_id} on demand. No background polling on the backend; data is current as of the last fetch.

If PLATFORM_INGEST_TOKEN is unset on the platform, ingest returns 503 fail-closed and the Quality tab stays empty. If the matching token is unset on the koinonia-cloud GitHub repo, post_test_run.py logs a workflow warning and exits 0 (so a Quality-tab outage cannot break CI).

Required GitHub repo secrets (on koinonia-cloud)

Secret Value
PLATFORM_INGEST_URL The deployed platform URL (look up via gcloud run services describe koinonia-platform-api --region us-central1 --project koinoniacloud-490205 --format='value(status.url)').
PLATFORM_INGEST_TOKEN The same value set in the platform's PLATFORM_INGEST_TOKEN env var. Generate with python3 -c "import secrets; print(secrets.token_hex(32))" once, set on both sides.

Rotating the GitHub dispatch token

Fine-grained PATs on GitHub expire (default 1 year, max 1 year). The "Run Smoke Test" button in the Quality tab depends on GITHUB_DISPATCH_TOKEN being a valid PAT. If the token expires, the button starts returning 502 ("Bad credentials") with no other warning. Set a calendar reminder for ~11 months after each rotation to do the next one before it expires.

Do not edit koinonia-platform/.env with nano or sudo nano on the CIFS-mounted source tree — the share is mounted with forceuid=1000, which causes editor saves to fail with "Permission denied" for any inode-touching write strategy. The rotation script uses awk → tmp → mv, the only edit pattern that survives the mount.

Step-by-step
  1. Revoke the old token first at https://github.com/settings/personal-access-tokens. Find the entry named koinonia-platform-dispatch → click Revoke. Doing this before rotating means a leaked credential is invalid even for the few minutes during the swap. (If you only generated a new token without revoking the old, both stay live until you explicitly revoke.)
  2. Generate the replacement: same page → Generate new token:
    • Token name: koinonia-platform-dispatch
    • Expiration: 1 year (or shorter if you prefer a tighter rotation cadence)
    • Repository access: Only select repositories → billburnham/koinonia-cloud
    • Repository permissions: Actions: Read and write — nothing else
    • Click Generate token, copy the value (starts with github_pat_)
  3. Run the rotation script:
    bash /mnt/AntiGravity/KoinoniaCloud/koinonia-platform/scripts/rotate_dispatch_token.sh
    The script will prompt you with Paste new GITHUB_DISPATCH_TOKEN (won't echo): — paste the value (right-click in your terminal), press Enter. Nothing appears as you paste (silent input via read -s) — that's correct. The script then updates .env, adds a new version to GCP Secret Manager, and bounces the Cloud Run revision so the new token is mounted as GITHUB_DISPATCH_TOKEN. Total time: ~30 seconds.
  4. Verify: open the Quality tab, click Run Smoke Test. A new chip should appear in the status strip 30–90 seconds later. If it's red with an error, check the workflow run on GitHub — a 401 "Bad credentials" response from GitHub means the token was wrong- scoped or already revoked.
What the script does (in order)
  1. Silent stdin prompt (no echo, no shell history capture)
  2. Verifies the local .env is writable; aborts cleanly if not
  3. Surgically rewrites the GITHUB_DISPATCH_TOKEN= line via awk → tmp → mv
  4. SHA-256 hashes both the new token and the value now in .env; aborts on mismatch (catches CIFS write failures that silently truncate)
  5. gcloud secrets versions add koinonia-platform-github-dispatch-token --data-file=-
  6. gcloud run services update koinonia-platform-api --update-secrets=GITHUB_DISPATCH_TOKEN=...:latest — triggers a new Cloud Run revision that mounts the new secret value
  7. Unsets $NEW_TOKEN from the shell so the value doesn't linger
If the script is missing

The script lives at koinonia-platform/scripts/rotate_dispatch_token.sh. If you've cloned the repo somewhere else or the file got deleted locally, pull it back via git checkout main -- scripts/rotate_dispatch_token.sh, or copy the file inline from that GitHub link.

If a token leaks (e.g. pasted in chat, email, screenshot)

Treat as compromised regardless of trust level. Same procedure as above: revoke the leaked token first, generate a replacement, run the script. Total exposure window is whatever time elapses between leak and revocation — the platform stops trusting the old token the moment gcloud run services update completes (the new revision rolls in within seconds), but the leaked token is still valid on GitHub's side until you click Revoke.

What's next: Steps 4 (Flake Bench — surface @pytest.mark.flaky-tagged tests with escalation), 5 (Slack triage integration), and 6 (Gate D fleet probe scaffolding) of the Quality tab roadmap are not yet shipped.

17.5 Costs Tab — GCP FinOps reporting

The Costs tab is the first/default tab in Command Center. It mirrors GCP billing data + audit-log change-stream into the platform DB and renders four sections so administrators can answer "did anything weird happen today?" in a glance — without ever opening the GCP billing console. See docs/plan_costs_tab.md for the full design, data model, and migration path.

Why it exists

Surprise bills are the failure mode this prevents. A forgotten min-instances=2 on a misconfigured Cloud Run service, a quiet egress spike, an attacker creating new resources — none of those signal until the invoice arrives. The Costs tab is the daily glance that catches them. Triggered 2026-05-08 when Bill's billing review showed a $206 May forecast (+50% MTM) and Secret Manager unexpectedly being the #1 line item.

The four sections

1. Spend Overview — four headline tiles:

  • Month-to-date: total spend so far this month, with last-month same-day comparison underneath.
  • Forecast (month-end): linear extrapolation of MTD over remaining days. Colored green/amber/red against the configured thresholds (default red ≥ $300, amber ≥ $225). The amber-then-red coloring is the early-warning system — if you see amber, investigate; if you see red, the budget is breached and the answer is action, not investigation.
  • Δ vs Last Month: percentage change of MTD vs same day last month.
  • Days Remaining: calendar countdown for context on how much room is left in the budget.

2. By Service table — sorted MTD descending. Each row shows MTD cost, % of total, a 30-day sparkline of daily spend, and a "today vs 7-day median" delta column. The delta is the spike-catcher: a service running at +50% above its weekly median is the kind of signal that surfaces a misconfiguration before the bill lands.

3. By Church table — per-church attribution via resource-name parsing (koinonia-{church_id}-*). Each row shows: church id, MTD cost, % of total spend, the top contributing service, and how many distinct services contributed. A "platform-shared" row at the bottom captures cost not yet attributable to a specific church (shared infrastructure, platform services, resources without consistent labels). As provisioning scripts adopt consistent church_id labels, more cost attribution shifts from platform-shared to per-church rows.

4. What Changed Today panel — the security-relevant view. Surfaces operationally-suspicious changes from the last 24h:

Detector What it catches Severity
iam_grant_added SetIamPolicy events on any resource. Privilege escalation marker. info if from expected automation; warn otherwise
service_account_created CreateServiceAccount events. Persistence marker. always warn (any new SA warrants a glance)
cloud_run_revision_outside_ci Cloud Run service deploys initiated by a non-automation actor — someone bypassing the deploy.sh / Cloud Build pipeline. warn
secret_version_outside_ci AddSecretVersion events from a non-automation actor — token theft or re-injection. warn

"Outside CI" means the actor email is human-shaped or an unrecognized service account. Expected automation actors are listed in asset_change_poller.EXPECTED_AUTOMATION_ACTORS. Each row has an Acknowledge button to silence it after review — acknowledged rows fade in the UI but stay in the table for forensics.

Refresh

The ↻ Refresh button at the top runs both pollers (cost + asset-change). Typical duration 1-3 seconds. Idempotent — can be clicked repeatedly without creating duplicate rows. The refresh timestamp displays next to the section title.

Cost data refreshes from the BigQuery billing export (which itself updates ~24h after the day it represents). Asset-change data comes from Cloud Audit Logs and is near-real-time. A future Phase 2 may add a Cloud Scheduler cron to refresh hourly without operator action.

Underlying data flow

  1. GCP billing data lands in BigQuery dataset billing_export daily.
  2. The platform service account (koinonia-platform-sa) reads it via roles/billing.viewer on the billing account + roles/cloudasset.viewer on the project.
  3. The cost poller (app/core/cost_poller.py) queries the export for the last 30 days, attributes resources to church_id via name parsing, and writes daily rollups to cost_snapshots in the platform DB.
  4. The asset poller (app/core/asset_change_poller.py) queries Cloud Audit Logs for the four detector method names and writes detected events to asset_changes.
  5. The UI fetches GET /api/admin/costs/overview + GET /api/admin/costs/changes on tab open. No synchronous GCP queries on UI fetches — everything serves from local tables.

Tuning thresholds

The red/amber forecast colors are configured in the cost_thresholds table. Defaults: red at $300/month, amber at $225/month (75% of red). To change without a redeploy:

# Mint a JWT (or use the one from a logged-in browser session via DevTools)
TOKEN=<your admin JWT>
curl -s -X PUT https://<platform-url>/api/admin/costs/thresholds \
  -H "X-Admin-Token: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"monthly_budget_red_usd": 500, "monthly_budget_amber_usd": 375}'

A future Phase 2 will surface this as a small admin form on the tab itself.

Phase 0 prerequisites (already complete as of 2026-05-08)

  • roles/billing.viewer granted on billing account 01C2AA-5EE462-4BFC38
  • roles/cloudasset.viewer granted on project koinoniacloud-490205
  • BigQuery detailed-usage export enabled, writing to dataset koinoniacloud-490205.billing_export
  • Secret Manager version cleanup: ~1,282 stale versions disabled, ~$77/mo savings. deploy.sh + secrets.sh patched to auto-prune on every store (keep last 3 versions). Bulk script lives at scripts/cleanup_secret_versions.sh.

What's deferred to Phase 2+

  • Slack/email alerts when forecast crosses thresholds
  • Per-resource egress GB anomaly detection (cost data alone misses slow exfiltration)
  • Cost-per-active-user metric (normalizes for church size)
  • Cloud Scheduler hourly refresh (currently the operator clicks ↻ Refresh)
  • Multi-project mode (Phase 1 scopes to koinoniacloud-490205 only; unbalanced-force-web is a separate GCP project covered separately)
  • Active triggers/throttling — auto-pause if cost-per-hour exceeds N, etc.

17.6 Training Videos Tab — what churches watch

Answers which User Guide training videos each church watches, for how long, where people stop watching, and whether people found them helpful. Opening the tab asks every running church for its totals (a church scaled to zero wakes up to answer, so it asks once per visit; Refresh asks again). Pick one church or All churches, and a span of 30 days, 90 days or a year. Every live video has a row, most played first; a video nobody has played in the span sits at the bottom with 0 plays, so the ones churches skip are as easy to spot as the favourites.

  • Plays — times a video was started.
  • Minutes — time actually spent playing. Skipping ahead doesn't count.
  • Still watching at 10% … 100% — ten bars, one per tenth of the video; each bar's height is the share of plays that played through that tenth (hover a bar for the count and the minute:second range it covers). The drop from one bar to the next is where people stopped. A bar turns amber when fewer than half are still watching; when one tenth loses a fifth or more of the plays, a note under the bars names it, e.g. 3 of 8 stopped between 30% and 40%, around 0:54–1:12 — that is the stretch of the video to go and watch. Skipping ahead does not count as watching, so a bar can only be as tall as the one before it.
  • Helpful — the 👍 share of the Helpful? answers under each video, with the raw 👍/👎 counts. A person can change or take back their answer.
  • Watched by — plays from staff, members, or check-in accounts (each role sees its own set of videos).

Anonymous by construction. Each church keeps per-day totals in its own help_video_daily table (day, video, viewer role and the counts) and, for the bars, help_video_reach_daily (the same key plus the tenth, and how many plays played through it). There is no person, user, session or address column, so nothing can say who watched. The guide's players report through the signed-in app (POST /api/help/video-event); the Command Center reads GET /api/help/video-stats with the church's scheduler secret, the same way it reads active-user counts. Nothing is stored on the platform side.

A church listed as not answering is unreachable or not yet deployed with video counting (the endpoint 404s until its next deploy). Paused churches are left off the list.

Who is offered which video. Every published video carries an audience, stamped by publish.py from its script: member (members only), checkin (check-in accounts and staff), staff (the default), everyone, or superadmin. A script sets audience: superadmin for videos that tour Admin-tab screens only a Super Administrator can open; the church API then signs those for the SUPERADMIN role alone, so a regular staff login’s Video Library never lists them. A SuperAdmin also gets every staff video. After changing a script’s audience, run python3 publish.py --refresh-meta to rewrite the live index (a church sees the change within about ten minutes).

17.6.1 Publishing a video collection

A collection is an unlisted page in a church's app, /watch/<name>, with a set of training videos in course order. Nothing in the app links to it and the User Guide does not mention it; you send the link. The first is finance (https://<church>.koinoniacloud.com/watch/finance): the Finance Office videos for the people cleared for the church's books. Anyone else, and anyone at all for a name that doesn't exist, sees This page isn't available to you. Plays show on the Training Videos tab like any other video, anonymously. Plan: koinonia-cloud/docs/plan_video_collections.md.

  • Who may open it — set per collection in the church API (help_media._COLLECTION_CLEARANCE). finance needs finance:read on the whole books, the same as the Finance Office. Finance is a sealed module: a SuperAdmin gets in only through a permission group holding a finance grant (e.g. Finance Committee), never by role. giving (/watch/giving, the stock, crypto and donor-advised-fund videos) needs finance:read and either the finance beta flag (BETA_FEATURE_FINANCE_USERS) or the church's books switched on (accounting_enabled) — the Finance tab's own door, set in help_media._COLLECTION_FLAG.
  • The VBS collection — /watch/vbs holds the Vacation Bible School videos in the order staff do the work: set up the event, set up registration, how families and volunteers sign up, reviewing registrations, and VBS night. It opens for anyone holding events:read, which every Staff role has by default, so one link can go to the whole staff. It needs no beta flag. Its videos are ordinary ones that are also in the Video Library.
  • Approve the videos — in tools/demo_videos/approved.yaml, a video meant only for collections goes under collection_only:, not approved: (never both). publish.py publishes those with audience finance, which the User Guide and its Video Library never show to anyone, SuperAdmin included. A collection can also hold an ordinary live video (e.g. receipts-mileage). publish.py refuses the tab-based Finance videos (finance-*, giving-*, receipts-finance) outright.
  • Publish the videos — python3 publish.py <slug> … as usual.
  • Set the order — tools/demo_videos/collections.yaml: <name>: {title, sections: [{heading, slugs: […]}]}. Check it with python3 publish.py --collections --dry-run (writes nothing), then python3 publish.py --collections, which writes /v/collections.json on the video host beside index.json, signed and cached the same way. Only videos already live go in; the rest are listed as warnings. Changing the order or a heading is just this re-publish — no deploy — and shows within about 10 minutes, like a new video.
  • Edge — the DMZ kc_help nginx serves /v/collections.json with the same signed-link rule as index.json (location ~ ^/v/(index|collections)\.json$ in koinonia-cloud/deploy/onprem/help-origin/dmz-kc_help.nginx.conf). Without it every collection page reads as not available.

17.7 GCP IAM Roles Required

The platform service account (koinonia-platform-sa) requires these IAM roles:

IAM Role Purpose
roles/run.developer List, get, and update Cloud Run services
roles/logging.viewer Read Cloud Logging entries
roles/monitoring.viewer Read Cloud Monitoring timeseries
roles/cloudsql.client Connect to Cloud SQL
roles/secretmanager.secretAccessor Read secrets
roles/cloudsql.admin Manage SQL backups, PITR, and snapshots
roles/storage.admin Manage GCS bucket versioning and file recovery

These are granted automatically by the platform's deploy/deploy.sh script (Step 4).

17.8 Deploying the Platform

The platform is deployed from the koinonia-platform repository:

cd /mnt/AntiGravity/KoinoniaCloud/koinonia-platform
./deploy/deploy.sh

The deploy script handles all 7 steps: service account, database, secrets, IAM roles, Docker build/push, Cloud Run deploy, and health check.

What the deploy does NOT do:

  • It does not touch any per-church deployments
  • It does not modify the koinonia-cloud repo or any church-specific resources
  • It generates a new database password on every run (stored automatically in Secret Manager)

After deploying:

  1. Verify the health endpoint: curl https://<service-url>/api/health
  2. Log in to /admin.html with the admin token
  3. Check all three tabs load correctly
  4. Test an operational action on a non-production church (e.g., restart the test church's API)

10a. GCP Instance Quotas & Scalability

Koinonia Cloud uses a "Shared Project, Isolated Instance" model. While this provides maximum data security, it creates a unique challenge for GCP Quotas. By default, new projects may have limits as low as 10–40 Cloud SQL instances per region.

18.1 Identifying Quota Bottlenecks

As you approach the project limit (e.g., when reaching 80% of your current quota), deployment of new churches via deploy.sh will fail at Step 4 with a QUOTA_EXCEEDED error. You must proactively request increases before running large onboarding waves.

18.2 How to Request Quota Increases

  1. Log in to the Google Cloud Console.
  2. Navigate to IAM & Admin → Quotas & System Limits.
  3. In the Filter box, type cloudsql.instances.googleapis.com or "Cloud SQL Instances".
  4. Select the checkbox for the service Cloud SQL instances in the us-central1 region (or "Global" if applicable).
  5. Click the Edit Quotas button at the top of the page.
  6. In the side panel, enter the New Limit you require (e.g., if you are at 100 and need room for 50 more churches, set it to 150).
  7. In the Request Description, provide a business justification:
    "Provisioning dedicated Cloud SQL tenancies for 50 additional church instances on the Koinonia Cloud SaaS platform."
  8. Click Submit Request. Small increases are often auto-approved within minutes; large increases may take 1-2 business days for Google Support to review.

10b. Disaster Recovery Roadmap

Koinonia Cloud implements a tiered recovery strategy. As of v2.0, many of these operations are automated directly via the Command Center (Section 17.3), but CLI fallbacks remain for break-glass scenarios.

10b.1 Automated Backups

Automated backups are your primary defense against total database failure.

  • Frequency: Daily (4-hour window).
  • Retention: 7 days (default).
  • On-Demand Snapshots: Use the "Instant Snapshot" button in the Command Center before performing any bulk imports or major configuration changes.

10b.2 Point-in-Time Recovery (PITR) — always a new instance

Cloud SQL cannot rewind an instance in place to an arbitrary second. Point-in-time recovery is a clone: a new instance is created from the live one as it was at the chosen moment (koinonia-{church}-pitr-<date>-<time>-db) and the live instance is untouched. In-place recovery is restoring a backup onto the live instance (10b.3) — either one of the instance’s own automated or on-demand backups, or, for a chosen minute, Recover Church In-Place → A specific minute, which clones to that minute and then restores the clone’s backup onto the live instance. The Command Center button for a look-only copy is The Lab → Forensic copy (look only). To make a church run on the copy, update its -database-url secret to the new instance and redeploy, or restore the copy's data across; otherwise inspect it and delete it (it bills like any instance).
After a rewind. A point-in-time rewind is itself an in-place restore, so the same rule applies to it: you cannot afterwards recover to a moment before the rewind by point-in-time. The safety backup it takes first is the way back.
Order matters in a drill. An in-place backup restore resets the instance's transaction-log chain, so point-in-time recovery to moments before that restore is no longer possible afterwards. Take the point-in-time copy first, then restore the backup in place.

PITR allows you to recover data to any specific second within the retention window by replaying Write-Ahead Logs (WAL).

Important: Restoring a backup or rolling back via PITR is a destructive operation on the target instance. The live database will be overwritten. Always use a "Sandbox Clone" first if you only need to inspect old data.

10b.3 Command Center Recovery Utilities

The Command Center Operations Tab automates the following scenarios:

Scenario Tool to Use Outcome
Church down — bring it fully back at its own URL Recover Church In-Place → pick a backup run (or latest) → type the id to confirm One click: safety backup → in-place restore → migrate + redeploy all services → auto-cutover on health check. Same id/URL; sessions and push subscriptions preserved. The recommended path for returning a live church to operation.
A bad deploy or mass mistake — undo everything after a moment Recover Church In-Place → A specific minute → type the id to confirm Safety backup → point-in-time copy → restore onto the live instance → migrate + redeploy → auto-cutover. About 25–40 minutes. Everything after that minute is lost for everyone. For one deleted family or person, use Recover Deleted Records instead.
One family or person deleted by mistake (and the church’s own Archive Management does not have it) Recover Deleted Records → table + record id from the church’s Audit Log + a minute just before the delete → Preview → type the rows to insert number → Put them back Preview writes nothing. Apply takes a safety backup, then inserts only the missing rows. Nobody else’s work is rewound; the church stays up. About 15–20 minutes.
Look at past data without changing anything (investigation) The Lab → Forensic copy (look only) → enter the moment (UTC) A NEW instance as the church was at that second (10b.2); the live church is untouched. Bills until deleted — delete it the same day.
Mass File Deletion File Recovery → file versions list Restores files from GCS bucket version history (older versions are marked [OLD VERSION]).
High-Risk Maintenance Data Integrity (The Shield) → Apply Instant Snapshot Creates a manual recovery point immediately.
Bug Investigation / dry-run migration The Lab (Staging & Testing) → cold-copy Provides a temporary copy of the church environment to view historical data or rehearse a migration.
Total Loss (Instance Deleted) deploy.sh + Restore (6b) No button for this: re-provision the church with deploy.sh, then restore the latest encrypted backup.

10b.4 Deletion Protection (Prevention)

To prevent catastrophic infrastructure loss, all church instances should have Deletion Protection enabled.

  • Command Center: Operations → Data Integrity (The Shield) shows Deletion Protection: ENABLED / disabled for the selected church, with the toggle beside it.
  • CLI: gcloud sql instances patch koinonia-{id}-db --deletion-protection
Warning: If an instance is deleted while protection is OFF, all automated backups for that instance are lost. Deletion Protection must remain ON for all production church tenants.

10b.5 Forensic Cloning & Migration Verification

Forensic cloning is a powerful utility for both bug investigation and Risk Mitigation during platform updates.

Recommended Workflow: The "Dry Run" Migration

While you should always verify updates in your staging/test environment first, unique data conditions in operational tenants can sometimes cause migrations to behave unexpectedly. For high-risk updates:

  1. Use The Lab (Staging & Testing) card in the Command Center's Operations tab for the specific church.
  2. Run your deployment or Database Migrations against this cloned sandbox instance.
  3. Verify that the data remains consistent and the application is healthy.
  4. Only after the "Dry Run" succeeds on the production replica should you apply the update to the live operational tenant.

Procedural Steps:

  1. Target church instance → Operations → The Lab → create the cold-copy.
  2. Select the PITR timestamp you want to investigate or verify.
  3. The platform provisions the sandbox instance in a separate environment.
  4. Once verified, use the Cleanup tool to delete the sandbox and stop billing.

19.6 Manual Verification & Audit

Sys Admins should periodically audit the fleet to ensure recovery headers are present:

# Verify PITR and Backup status
gcloud sql instances describe koinonia-{id}-db \
  --project=koinoniacloud-490205 \
  --format="json(settings.backupConfiguration)"

Expected flags: enabled: true, pointInTimeRecoveryEnabled: true.


11a. Geocoder (Pelias)

Koinonia Geocoder (koinonia-geocoder) is a self-hosted Pelias geocoding service that converts street addresses into latitude/longitude coordinates. It is shared infrastructure — one instance serves all church deployments. No member data is stored by the geocoder; it receives a bare address string, returns coordinates, and retains nothing.

11a.1 Architecture

The geocoder is a standalone Docker Compose stack that runs independently of any church instance:

KoinoniaCloud/
  koinonia-cloud/          ← church app (per-tenant)
  koinonia-platform/       ← fleet monitoring (shared)
  koinonia-geocoder/       ← Pelias geocoder (shared)  ← THIS
    docker-compose.yml       Pelias services
    pelias.json              US-only data config (1,606 OpenAddresses files)
    .env                     DATA_DIR + PELIAS_CONFIG paths
    setup.sh                 One-time setup script
    run_import.sh            Background import runner

Church backends call the geocoder via a single environment variable:

PELIAS_API_URL=http://localhost:4000          # dev (on-premises)
PELIAS_API_URL=http://10.128.0.x:4000         # prod (GCP internal VPC)

The geocoding flow:

  1. Church admin clicks "Geocode missing" in the Member Map tab
  2. Backend builds a canonical address string, checks for duplicates (family members at same address)
  3. Unique addresses are sent to GET /v1/search?text={address}&boundary.country=US
  4. Pelias returns GeoJSON coordinates from its Elasticsearch index
  5. Backend stores latitude, longitude, geocode_hash, and geocoded_at on the individuals table
  6. Subsequent requests skip the geocoder (cached in DB by address hash)

11a.2 Initial Setup (Dev / On-Premises)

Prerequisites: Docker, Docker Compose, ~70 GB disk, internet access for initial data download.

Step 1 — Configure paths

Edit koinonia-geocoder/.env:

COMPOSE_PROJECT_NAME=pelias
DATA_DIR=/mnt/AntiGravity/KoinoniaCloud/koinonia-geocoder/data
PELIAS_CONFIG=/mnt/AntiGravity/KoinoniaCloud/koinonia-geocoder/pelias.json

Step 2 — Set file permissions

Pelias containers run as a non-root pelias user. The data directory and config file must be world-readable. On CIFS/SMB mounts, this requires file_mode=0777,dir_mode=0777 in /etc/fstab. On native Linux filesystems:

sudo chmod -R 777 /path/to/koinonia-geocoder/data/
sudo chmod 644 /path/to/koinonia-geocoder/pelias.json

Step 3 — Run the setup script

cd /mnt/AntiGravity/KoinoniaCloud/koinonia-geocoder
./setup.sh

Or run the background import runner and monitor progress:

nohup ./run_import.sh > /dev/null 2&1 &
tail -f import.log

The import downloads ~30 GB of US address data and indexes it into Elasticsearch. Expect 1–3 hours depending on internet speed and hardware. Milestone lines in the log:

[19:34:14] Schema created.
[19:34:40] WoF download complete.
[19:53:44] OSM download complete.
[xx:xx:xx] OA download complete.
[xx:xx:xx] WoF import complete.
[xx:xx:xx] OA import complete.
[xx:xx:xx] OSM import complete.
[xx:xx:xx] === ALL DONE — Pelias running at http://localhost:4000 ===

Step 4 — Verify

curl 'http://localhost:4000/v1/search?text=123+Main+St,+Brandon+FL'

A successful response returns GeoJSON with coordinates for the address.

11a.3 Data Sources

Source What It Provides Size (US) Why It Matters
OpenAddresses Rooftop-level address points from county assessor records ~10 GB Most accurate for US residential addresses — actual government data
OpenStreetMap Streets, POIs, building footprints ~10 GB Road network context and fallback geocoding
Who’s on First Neighborhood and administrative boundary polygons ~2 GB Disambiguates city/state names during geocoding

The pelias.json config file contains 1,606 US OpenAddresses file references, curated from the official Pelias north-america project template.

11a.4 GCP Production Deployment

In production, Pelias runs on a dedicated GCE VM within the Koinonia Cloud GCP project. Church Cloud Run backends connect to it via internal VPC networking — no public internet exposure.

Resource Spec Est. Cost
GCE VM e2-standard-4 (4 vCPU, 16 GB RAM) ~$50/mo
Persistent Disk 100 GB SSD (Elasticsearch index + data) ~$17/mo
Total ~$67/mo (serves unlimited churches)

Deployment steps:

  1. Create the GCE VM in the koinoniacloud-490205 project, us-central1 region
  2. Install Docker and Docker Compose on the VM
  3. Copy koinonia-geocoder/ to the VM
  4. Run setup.sh to build the index
  5. Open internal firewall rule for port 4000 from Cloud Run VPC connector
  6. Set PELIAS_API_URL=http://<vm-internal-ip>:4000 in each church’s Cloud Run environment

11a.5 Maintenance & Updates

Quarterly data refresh

OpenAddresses and OSM data are updated regularly. To pick up new addresses (new construction, corrections):

# Re-download data sources
sg docker -c "docker compose run --rm whosonfirst ./bin/download"
sg docker -c "docker compose run --rm openaddresses ./bin/download"
sg docker -c "docker compose run --rm openstreetmap ./bin/download"

# Re-import into Elasticsearch
sg docker -c "docker compose run --rm whosonfirst ./bin/start"
sg docker -c "docker compose run --rm openaddresses ./bin/start"
sg docker -c "docker compose run --rm openstreetmap ./bin/start"

Monitoring

  • Elasticsearch health: curl http://localhost:9200/_cluster/health — should return "status":"green" or "yellow"
  • Index document count: curl http://localhost:9200/pelias/_count — US-only typically contains 100M+ documents
  • API health (Pelias direct): curl http://localhost:4000/v1 — should return version info
  • API health (through proxy): curl http://localhost:4002/v1 — same response, but the request gets counted under unknown if the call has no CF-Access-Client-Id header. cloudflared's public hostname for the geocoder points at :4002, not :4000 — the proxy is in path for all real traffic.
  • Per-church request counts: Command Center → Fleet Monitoring → On-Prem Activity. The proxy and tile-server aggregator both push hourly counts to the platform; the card shows today / 7d / 30d totals plus a per-church breakdown.

Restarting services

# Restart all runtime services
cd /path/to/koinonia-geocoder
sg docker -c "docker compose restart api placeholder pip-service interpolation"

# Full stop and start
sg docker -c "docker compose down"
sg docker -c "docker compose up -d elasticsearch api placeholder pip-service interpolation"

11a.6 Troubleshooting

Symptom Cause Fix
Geocoding returns no results for known addresses Import didn’t complete or Elasticsearch index is empty Check curl localhost:9200/pelias/_count — if count: 0, re-run the import
EACCES / Permission denied on /code/pelias.json CIFS mount with restrictive file_mode Set file_mode=0777,dir_mode=0777 in /etc/fstab and remount
Elasticsearch won’t start (exit code 78) vm.max_map_count too low sudo sysctl -w vm.max_map_count=262144
Church backend returns “Geocoding failed” Pelias not running or wrong PELIAS_API_URL Verify curl $PELIAS_API_URL/v1 from inside the church’s Docker network
Batch geocoding is slow Many unique addresses, sequential processing Normal — ~100 addresses/sec on local hardware. Address dedup reduces volume significantly.

11b. Feature Flag Management

Koinonia Cloud supports per-user beta feature flags driven by Cloud Run environment variables. This lets platform admins gate access to in-progress features (e.g. Member Map) to a small group of beta testers without redeploying code or changing the database schema. Each flag has its own email allowlist; users whose email matches see the feature, everyone else does not.

11b.1 How it works

  1. Each feature flag is identified by a short name (e.g. member_map) and is backed by a single environment variable on the church’s Cloud Run API service. The variable name follows the pattern BETA_FEATURE_<NAME>_USERS (e.g. BETA_FEATURE_MEMBER_MAP_USERS), and its value is a comma-separated list of email addresses.
  2. When a user logs in, /api/auth/me computes their feature_flags array by checking each known flag’s env var and including the flag if the user’s email is in the list.
  3. The frontend’s useAuth.hasFeatureFlag(name) reads that array. UI components hide themselves (e.g. the dashboard tab) if the user doesn’t have the flag.
  4. If the env var is absent or empty, nobody has the flag for that church.

Updating the allowlist = updating one Cloud Run env var. No redeploy, no schema migration, no frontend rebuild. The next user to log in (or any user whose token refreshes) gets the new flag list automatically.

11b.2 Adding a Beta Tester

To grant a user access to an existing beta feature on a specific church instance, add their email to the corresponding env var. Example for Member Map on baylife-test, adding newperson@example.com to the existing list:

gcloud run services update koinonia-baylife-test-api \
  --region=us-central1 --project=koinoniacloud-490205 \
  --update-env-vars=BETA_FEATURE_MEMBER_MAP_USERS="bill.burnham@unbalancedforce.com,pastor@baylifechurch.com,newperson@example.com"

Notes:

  • --update-env-vars is additive for vars not mentioned, but overwrites the value of the var named. Always include the full comma-separated list of all current beta testers, not just the new one.
  • Cloud Run rolls out a new revision automatically (~30 seconds, no downtime).
  • The new beta tester must log out and log back in for the flag to take effect — feature_flags are returned by /api/auth/me at login time and cached in the session.

11b.3 Listing Current Beta Testers

Before adding to the list, view the current value so you don’t accidentally drop anyone:

gcloud run services describe koinonia-baylife-test-api \
  --region=us-central1 --project=koinoniacloud-490205 \
  --format='value(spec.template.spec.containers[0].env)' | tr ';' '\n' | grep BETA

Copy that line, append the new email(s), and paste back into the update command from 11b.2.

11b.4 Removing a Beta Tester

Same approach — update the env var with the shorter list (omit the email being removed):

gcloud run services update koinonia-baylife-test-api \
  --region=us-central1 --project=koinoniacloud-490205 \
  --update-env-vars=BETA_FEATURE_MEMBER_MAP_USERS="bill.burnham@unbalancedforce.com,pastor@baylifechurch.com"

The removed user keeps the flag until their next token refresh (typically within an hour for active sessions). For immediate removal, force them out: in the Koinonia Cloud Users tab, set their account to inactive briefly, then re-activate — that invalidates active tokens.

11b.5 Going GA (Removing the Flag)

When a feature is ready to release to all users on a church, fully remove the env var:

gcloud run services update koinonia-baylife-test-api \
  --region=us-central1 --project=koinoniacloud-490205 \
  --remove-env-vars=BETA_FEATURE_MEMBER_MAP_USERS

This restores the default behavior: the empty allowlist means no one matches. You must also remove the flag check from the frontend code in frontend/src/app/dashboard/page.tsx — so the tab is visible to all qualifying users by role. Note the member_map flag now gates two tabs, so delete both lines: if (t === 'Member Map') return hasFeatureFlag('member_map'); and if (t === 'Pastoral Care') return hasFeatureFlag('member_map');. Submit that change as a normal PR + deploy.

11b.6 Currently Defined Flags

Flag name Env var Gates
bible_atlas BETA_FEATURE_BIBLE_ATLAS_USERS The Bible Atlas tab, for staff and members alike.
brand BETA_FEATURE_BRAND_USERS The Brand tab (church logo, check-in tag logo, email font, confidentiality notice, signature preview). Its own list — never shared with another feature.
groups BETA_FEATURE_GROUPS_USERS The Groups tab, while the group-management UI finishes; lets beta users review imported Life Groups. (The Admin tab's Manage Groups button stays disabled regardless.)
member_map BETA_FEATURE_MEMBER_MAP_USERS Declared and still returned in /api/auth/me, but no longer read by the web app: the Member Map tab is gated on the developer grant (membership of the ZZ Developer permission group) plus a map grant — see User Guide 12a. Adding an email here does nothing on its own.
pastoral_care BETA_FEATURE_PASTORAL_CARE_USERS Likewise vestigial: the Pastoral Care tab (Visit Planner, care cases, pastoral notes) is a sealed module opened only by the pastoral_care grant on a permission group designated for it — SuperAdmins included.

Beta lists are per church: the env var lives on that church's API service, so a tester must be added on every church where they should see the feature. Grant-gated features (Member Map, Pastoral Care, Giving, Finance) are configured by the church's SuperAdmin in User Management → Permission Groups, not by us.

To register a new flag, add an entry to _BETA_FEATURE_ENV_VARS in backend/app/api/endpoints/auth.py (one line: "flag_name": "BETA_FEATURE_FLAG_NAME_USERS"), then gate the relevant frontend code with hasFeatureFlag('flag_name'). Update this table when you add new flags.

11b.7 Related: Cloudflare Tunnel for On-Prem Pelias

The Member Map feature relies on the on-premises Pelias geocoder being reachable from each church’s Cloud Run backend. This is achieved via a Cloudflare Tunnel terminating at geocoder.koinoniacloud.com (production) or geocoder-dev.koinoniacloud.com (dev), protected by Cloudflare Access service tokens.

Each church Cloud Run service needs three values wired in: the PELIAS_API_URL env var (tunnel hostname) and two secrets holding the Cloudflare Access service-token Client ID / Secret. Once the secrets exist, deploy.sh picks them up automatically on every deploy — no manual gcloud commands needed for ongoing deploys.

Step A — Generate the service token (one-time, in Cloudflare)

In the Cloudflare Zero Trust dashboard: Access → Service Auth → Service Tokens → Create Service Token. Name it after the church (e.g. baylife-test-geocoder). Cloudflare will display the Client ID and Client Secret once — copy both immediately into a secure password manager.

Step B — Store the token in GCP Secret Manager (one-time per church)

Replace <CHURCH_ID>, <CLIENT_ID>, <CLIENT_SECRET>:

CHURCH_ID="<CHURCH_ID>"   # e.g. baylife-test

# Create the two secrets
echo -n "<CLIENT_ID>"     | gcloud secrets create "koinonia-${CHURCH_ID}-geocoder-client-id" \
  --data-file=- --project=koinoniacloud-490205 --replication-policy=automatic
echo -n "<CLIENT_SECRET>" | gcloud secrets create "koinonia-${CHURCH_ID}-geocoder-client-secret" \
  --data-file=- --project=koinoniacloud-490205 --replication-policy=automatic

# Grant the church's Cloud Run service account read access
SA=$(gcloud run services describe "koinonia-${CHURCH_ID}-api" \
  --region=us-central1 --project=koinoniacloud-490205 \
  --format='value(spec.template.spec.serviceAccountName)')
for SECRET in "koinonia-${CHURCH_ID}-geocoder-client-id" "koinonia-${CHURCH_ID}-geocoder-client-secret"; do
  gcloud secrets add-iam-policy-binding "$SECRET" \
    --member="serviceAccount:${SA}" --role="roles/secretmanager.secretAccessor" \
    --project=koinoniacloud-490205
done

Step C — Deploy

Once the secrets exist, deploy.sh reads them automatically and wires CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET into the Cloud Run service. The PELIAS_API_URL env var is also set on every deploy, defaulting to https://geocoder.koinoniacloud.com (production tunnel).

To deploy against the dev tunnel (testing or before the production tunnel exists), override PELIAS_API_URL at deploy time:

# Dev tunnel (testing):
PELIAS_API_URL=https://geocoder-dev.koinoniacloud.com ./deploy/deploy.sh --church-id baylife-test

# Production tunnel (default — no override needed):
./deploy/deploy.sh --church-id baylife-test

Why the override matters: early deploy.sh versions used gcloud’s --set-env-vars flag, which replaces all env vars rather than merging. That meant every deploy wiped PELIAS_API_URL, requiring a manual gcloud run services update afterward. The current script bakes PELIAS_API_URL into the deploy itself, so this one-line prefix is the only thing you need to remember when pointing at the dev tunnel.

Step D (rare) — Manual override after deploy

If you ever need to point a single church at a non-default tunnel without redeploying (e.g. emergency cutover during prod tunnel maintenance), use:

gcloud run services update "koinonia-${CHURCH_ID}-api" \
  --region=us-central1 --project=koinoniacloud-490205 \
  --update-env-vars=PELIAS_API_URL=https://geocoder-dev.koinoniacloud.com

This change persists only until the next deploy.sh run, which restores the deploy-time default.

Token rotation

Generate the replacement in Cloudflare, run gcloud secrets versions add on each of the two secrets to push the new values, then either wait for the next church deploy (which picks up the latest secret version automatically) or force a fresh revision now with gcloud run services update koinonia-<id>-api --update-secrets=...:latest. Once the new revision is serving traffic, revoke the old token in Cloudflare.

11c. Bible Atlas — Local Overlay Reference Data (Natural Earth)

The Bible Atlas 1:1 Local Overlay ("Show home overlay") drapes a true-scale tracing of each church’s real surroundings — state outlines, nearby cities, airports — onto the Holy Land map. That reference geography comes from Natural Earth, a public-domain cartographic dataset bundled into the backend. Natural Earth is one of several mapping data sources we review on a quarterly cadence alongside our PMTiles basemap, Pelias geocoder data, and Valhalla routing tiles.

11c.1 What it is & where it lives

Property Detail
Files backend/app/data/geo/admin1_states.geojson, populated_places.geojson, airports.geojson
Size ~4.2 MB total (simplified)
Source Natural Earth 1:10m (public domain), via the nvkelso/natural-earth-vector GitHub mirror
Delivery Baked into the backend Docker image — committed to the koinonia-cloud repo and shipped with every backend deploy
Served on-prem? No. Unlike the 77 GB PMTiles basemap (served on-prem behind the Cloudflare tunnel), this bundle is small enough to embed — the FastAPI backend reads it from its own local disk.
Database? No. Static read-only reference data — no table, no Alembic migration. Every church instance gets an identical copy from the image.
No per-church or per-deploy step. Because the bundle ships inside the backend image, a normal backend deploy already includes it. There is nothing to upload, install, or configure per church.

11c.2 Quarterly Data Refresh

The dependency is real but slow-moving. Natural Earth publishes new releases only every 1–2 years, and the things it tracks (state boundaries, major-city populations, airports) drift slowly. Review quarterly — in practice most quarters are a no-op: check whether Natural Earth has cut a new release; if not, there is nothing to do.

When a refresh is warranted, regenerate the bundle with the prep script. Run it on a dev machine — not in the API container and not at deploy time:

# In the koinonia-cloud repo, on a dev machine:
bash backend/scripts/prep_natural_earth.sh

The script downloads the upstream datasets, simplifies them with mapshaper (fetched on demand via npx), and overwrites the three files in backend/app/data/geo/. It requires curl and node/npx.

After regenerating:

  1. Review the diff — confirm only the three .geojson files changed and the total stays in the low-MB range.
  2. Commit the updated files to koinonia-cloud.
  3. Deploy the backend normally — the new bundle ships with the image. No migration, no per-church action.

11c.3 Dependency Notes

  • License: Natural Earth is public domain — no attribution obligation, free to redistribute inside the image.
  • mapshaper is build-time only. It is pulled transiently by npx while the prep script runs — it is not a runtime dependency and is not in requirements.txt or package.json.
  • Runtime is pure-Python. The query path (app/services/local_geography.py) uses only the standard library — no PostGIS, no geo libraries. Nothing extra to install on the server.
  • Per-church anchor: the overlay centres on each church’s own geocoded location (Main Campus geocode, falling back to the church-profile address via Pelias). No coordinates are hardcoded; the feature works for any church instance.

11d. PostGIS POI Service

koinonia-poi is a self-hosted PostGIS service holding a curated US OSM points-of-interest dataset, plus a FastAPI counting proxy that answers GET /poi/lookup?lat=&lon=&radius_m=&limit=. It powers the Member Map's rich-popup-on-click feature — tapping a restaurant, school, hospital, viewpoint, etc. returns the full OSM tag set (phone, hours, website, addresses, wheelchair access, Wikipedia links). The alternative was an external API call (Google Places, OSM Overpass) that would have leaked the user's chosen coordinate to a third party on every click; this keeps the lookup inside the operational perimeter, same posture as the Geocoder.

11d.1 Architecture

Three containers, all in koinonia-poi/docker-compose.yml:

  • postgis — PostgreSQL 16 + PostGIS 3.4 (Alpine, pinned to a digest). Holds the pois table (~6.4M rows after import, ~2–3 GB on disk including indexes). Bind-mounts POI_DATA_DIR on local NVMe; internal-only on the compose network (no host port published).
  • importer — one-shot container running osm2pgsql against the US OSM extract. Built from importer/Dockerfile on debian:bookworm-slim (Alpine 3.20 doesn't package osm2pgsql; Debian does). Compose profile: import keeps it out of default up.
  • proxy — FastAPI (python:3.11-slim-bookworm, pinned) + asyncpg connection pool. Container name koinonia_poi_proxy, host port 8007:3000. Reads CF-Access-Client-Id for per-church attribution; body-blind (never logs the lat/lon click target or the response body).

External request flow: GCP church-api → Cloudflare Tunnel (poi-dev.koinoniacloud.com → localhost:8007) → proxy → PostGIS via the compose network. The proxy talks to PostGIS by service name (postgis:5432) so no port has to be exposed to the host — tightens the attack surface vs. the routing proxy's pattern.

11d.2 Initial Setup

One-time, on the workstation. Assumes the koinonia-routing stack is already up (we reuse its US OSM extract):

# Clone (private repo)
git clone https://github.com/billburnham/koinonia-poi.git
cd koinonia-poi

# Create POI data dir on local NVMe (postgres runs as UID 1000)
mkdir -p /home/kyfakt/koinonia-poi-data

# Set env (POSTGRES_PASSWORD random, OSM_PBF_PATH = the NVMe-local Valhalla copy)
cp .env.example .env && chmod 600 .env && nano .env

# Set proxy/.env from the geocoder's (see §7e.1 for the no-echo copy command)
cp proxy/.env.example proxy/.env && chmod 600 proxy/.env
# then copy the three shared values from koinonia-geocoder/proxy/.env

# Bring up PostGIS (initdb runs migrations/001_init_pois.sql automatically)
sg docker -c "docker compose up -d postgis"

# Verify
sg docker -c "docker compose exec postgis psql -U poi -d poi -c 'SELECT postgis_version();'"

After PostGIS is up, run the first import (Phase 2 of the plan; takes ~35 min on local NVMe):

sg docker -c "docker compose --profile import build importer"
sg docker -c "docker compose --profile import run --rm importer \
  osm2pgsql --output=flex --style=/import/conf/osm2pgsql.lua \
            --slim --drop --cache=4000 \
            /import/us-latest.osm.pbf"

Then add the post-import indexes (composite + GIN, ~45s):

sg docker -c "docker compose exec postgis \
  psql -U poi -d poi -f /post-import/01_indexes.sql"

Bring the proxy up and add the Cloudflare tunnel hostname (poi-dev.koinoniacloud.com → localhost:8007) — same pattern as the geocoder/routing tunnels, dashboard-managed (no local config.yml).

11d.3 Refresh Workflow (weekly)

OSM POI churn at the per-location level is slow (restaurants open/close, hours change), so a weekly refresh keeps the data materially current. The workflow is the same as Initial Setup steps 2 + 3 (importer + post-import indexes). Reasons for the two-step pattern:

  • osm2pgsql owns the table. Despite create='never' in our Lua, osm2pgsql's default CLI mode --create drops and recreates the target table regardless. So the post-import indexes (composite on category + GIN on tags) must be re-added after each import.
  • Both steps are idempotent. The osm2pgsql refresh truncate-and-reloads; the post-import script uses CREATE INDEX IF NOT EXISTS. Safe to re-run.

A koinonia-poi-refresh.timer systemd unit wrapping both steps is Phase 2.5; until shipped, refresh is manual.

11d.4 Troubleshooting

Symptom Cause Fix
Member Map POI clicks show only name + category (no phone/hours/etc.) Backend can't reach the proxy. Either GCP POI_URL is wrong, the Cloudflare tunnel is down, or the proxy container isn't running. Cloud Run logs for koinonia-baylife-test-api, filter poi; check the proxy container is up with sg docker -c "docker ps | grep poi"; confirm the tunnel from the Cloudflare Zero Trust dashboard's Connector status.
POI tile in Command Center stuck at 0 despite real Member Map activity Almost certainly the empty-.env trap. See §7e.1. Copy the three shared values from the geocoder's .env (§7e.1 has the no-echo script), restart the proxy.
Proxy logs show "no route shape" or asyncpg connection errors after a restart PostGIS container restarted but proxy didn't reconnect cleanly, or the data dir was wiped. Restart proxy: sg docker -c "docker compose -f /mnt/AntiGravity/KoinoniaCloud/koinonia-poi/docker-compose.yml restart proxy". If pois table is empty, re-run the Phase 2 import.
osm2pgsql build fails on apk add osm2pgsql You tried to base the importer on the postgis-alpine image. Alpine 3.20 doesn't package osm2pgsql. Confirm importer/Dockerfile uses FROM debian@sha256:... (bookworm-slim), not the postgis-alpine base. The two services live on different bases intentionally.
Koinonia Cloud — Administrator Deployment Manual — v2.0 — April 2026