11 — Database safety & migrations
Purpose: Non-negotiable rules for knowing which PostgreSQL instance you are connected to, and how to apply schema and PHI migrations safely.
Audience: Engineers and operators.
Version: 3.15
Last Updated: 2026-08-04 09:20:39
Environment terminology: 00-INDEX.md — Terminology
Day-2 ops (logs, backups, REINDEX after OS upgrade): 07-PLATFORM-RUNBOOK.md §10–§18
Deploy: 20-PRODUCTION-DEPLOYMENT-GUIDE.md
1. Hard rules: which database you are touching {#hard-rules-which-database-you-are-touching}
Section titled “1. Hard rules: which database you are touching {#hard-rules-which-database-you-are-touching}”FastAPI, python -m migrations.runner, and psql use exactly the database in the active DATABASE_URL. If that URL points at production, every command runs against live data.
| Do | Do not |
|---|---|
Keep production credentials only on the VPS (or secret store), not in backend/.env on a dev PC. | Paste a production DATABASE_URL into backend/.env for day-to-day work. |
Before migrations or DDL: confirm target (SELECT current_database();, correct docker compose exec context). | Run migrations from a laptop against a DSN you have not explicitly verified. |
Use scratch DBs (lyncareos_migration_test, etc.) for rehearsal. | Assume localhost is always safe — check port and database name. |
Frontend: VITE_API_URL chooses which backend the Vite dev server proxies to; that backend’s DATABASE_URL chooses the DB. Routine dev: VITE_API_URL=http://localhost:8021 → lyncareos_dev.
Production host: DigitalOcean Sydney lyncareos-prod-syd1 (134.199.173.206). Migrations apply on app container start via init_db() → migrations.runner before schema.sql (see §3a). Operator work is normally backup + verify logs; manual python -m migrations.runner is only needed when recovery from a failed deploy (§4).
Confirm latest migration: Active files: Get-ChildItem backend/migrations/V*.sql (post-v1 forward chain V001 marker through V028+). Host state: .\migration-audit.ps1 -Target Dev|Vps -NonInteractive — brownfield DBs show ARCHIVED pre-v1 rows; PENDING means an active file not yet in schema_migrations. Always use .\migrate.ps1 -Target Dev for local dev — bare python -m migrations.runner without setting DATABASE_URL defaults to lyncareos, not lyncareos_dev.
1a. Forward migration register (post-v1 active chain) {#forward-migration-register}
Section titled “1a. Forward migration register (post-v1 active chain) {#forward-migration-register}”Every new file under backend/migrations/V*.sql (not archive/pre-v1/) must be recorded here in the same PR: append one row to the summary table and add a §2x detail subsection when the change is non-trivial (new tables, RLS, backfill, or product-facing behaviour).
| Version | File | Summary |
|---|---|---|
| V025 | V025__tenant_account_numbers.sql | Public tenant + member account numbers |
| V026 | V026__care_tasks_date_scoped.sql | Date-scoped care_tasks; module action idempotency |
| V027 | V027__care_task_module_responses.sql | Structured module task answers on care_tasks |
| V028 | V028__users_login_count.sql | users.login_count — completed sign-ins for first-run mobile nav hint |
| V029 | V029__care_profiles_alacarte.sql | Paid Care Profiles à la carte — clear tier_included grants; revoke tier ledger rows |
| V030 | V030__users_care_module_dev_preview.sql | Owner preview toggle — users.care_module_dev_preview |
| V031 | V031__i18n_locale_columns.sql | I18N-P1 — tenants.locale, users.locale_override |
| V032 | V032__pending_signups_locale.sql | Marketing signup locale → pending_signups.locale → tenant/user on provision |
Detail subsections below expand selected migrations; the table above is the canonical index of the active forward chain.
Agents and engineers: If you add V029__…, update this table, mirror the column/table in backend/schema.sql when applicable (§3a), and cite the version in any feature doc that depends on the schema.
2. B4 PHI field-level encryption (V089–V091)
Section titled “2. B4 PHI field-level encryption (V089–V091)”On every app container start, init_db() runs the migration runner — V090 will fail if encrypt_phi_fields has not run and all enc_version < 1 counts are 0. Treat backfill as a mandatory gate before deploy when V089 is applied and V090 is not.
Production status (2026-05-27): VPS backfill complete; all four PHI tables at enc_version = 1. PHI_* pinned via production-phi-pin.ps1. Dev lyncareos_dev: legacy rows lost PHI when V091 ran before backfill — see §2a; production unaffected.
| Migration | When |
|---|---|
| V089 | Deploy (adds tenants.name_enc, non-breaking) |
| V090 | After backfill verifies enc_version = 1 on all rows in all four tables |
| V091 | ≥1 week after V090 stable; drops plaintext columns. In-DB guard aborts if any row still unmigrated. |
Backfill (once per environment, before V090)
Section titled “Backfill (once per environment, before V090)”# Workstation (also in deploy.ps1 preflight):.\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded
# VPS manual equivalent:cd /opt/lyncareosdocker compose -f docker-compose.yml -f docker-compose.vps.yml ` --env-file .env.production --profile production ` run --rm --no-deps app python -m migrations.scripts.encrypt_phi_fieldsPre-V090: all four SELECT COUNT(*) … WHERE enc_version < 1 queries must return 0.
Pin keys after backfill: .\scripts\production-phi-pin.ps1 (production) or .\scripts\dev-phi-pin.ps1 (dev). deploy.ps1 runs production pin automatically when keys are missing. Pin writes HKDF-from-SECRET_KEY values only when keys are absent — it must not invent a new random key over existing ciphertext.
Required in .env.production after pin:
PHI_ENCRYPTION_KEY=…PHI_BLIND_INDEX_KEY=…See 01-ARCHITECTURE.md (field-level PHI encryption) and 02-REQUIREMENTS.md §4.5.
2a-gate. PHI crypto health — hard release gate (2026-07-20)
Section titled “2a-gate. PHI crypto health — hard release gate (2026-07-20)”Presence of PHI_* is not enough. Keys must decrypt durable ciphertext. A mismatch causes production login/patient failures and can undermine operator-blindness / Terms claims.
| Script | Role |
|---|---|
backend/tools/verify_phi_crypto_health.py | Counts-only decrypt + email_idx check (exit 0/1) |
scripts/verify-phi-crypto-health.ps1 -Target DockerUat|Vps | Wrapper used by release pipeline |
Automated hard fail (do not ship on failure):
- Docker UAT —
push-to-production.ps1after migrations green - VPS pre-redeploy —
deploy.ps1after backup, before image swap - VPS post-redeploy —
deploy.ps1after smoke, before announce
.\scripts\verify-phi-crypto-health.ps1 -Target DockerUat.\scripts\verify-phi-crypto-health.ps1 -Target VpsOutput is counts only (undecryptable=N, idx_mismatch=N) — never PHI or key material. Repair is a deliberate operator action (seed_admin.py / repair_phi_email_indexes / MultiFernet re-encrypt) — never invent new keys during deploy.
Plan: 2026-07-20-phi-crypto-release-gate.md.
Config ↔ durable state register
Section titled “Config ↔ durable state register”| Risk | Gate posture |
|---|---|
PHI encrypt/decrypt + email_idx | Hard fail in push/deploy (this section) |
MFA key vs mfa_secret | Follow-on (pin + secrets audit today) |
| Stripe live vs test key / webhook | Partial (production-secrets-audit.ps1) |
| Restore dump into env with wrong PHI keys | Documented warning (restore-vps-production-to-dev.ps1) |
2b. V104 — per-tenant DEK envelope (B4, REQ-ENC-04)
Section titled “2b. V104 — per-tenant DEK envelope (B4, REQ-ENC-04)”Migration V104__tenant_dek_columns.sql adds tenants.dek_ciphertext and tenants.dek_nonce. The platform KEK (PHI_ENCRYPTION_KEY) wraps each tenant data-encryption key; plaintext DEKs are never stored.
| When | Action |
|---|---|
| Deploy | Applies automatically on app start with other pending migrations. |
| Provision | ensure_tenant_dek() runs on new tenants (Stripe checkout, auth tenant create, schedule backfill) — not in routers/tenants.py. |
| Legacy tenants | Backfill on first provision path or operator script; optional read-time ensure_tenant_dek on tenant load is a nice-to-have. |
Not in V104: Encrypting additional clinical columns with the tenant DEK (REQ-ENC-05) — identity columns still use platform phi:v1: encryption (V076–V091). Counsel review of operator-blindness copy (REQ-ENC-06) remains before marketing gate lift (A6).
2c. V077–V079 — Care Profiles schema (draft seeds; reconciliation via V006–V009)
Section titled “2c. V077–V079 — Care Profiles schema (draft seeds; reconciliation via V006–V009)”Migrations V077, V078, and V079 created the condition-template tables (condition_archetypes, condition_packs, pack_*, observation_types, patient_observations). They are applied on all environments that ran the C1 migrations. Reconciliation shipped 2026-06-04 as active post-v1 files V006–V010 (content equivalent to Palliative §7.0.5 planned V106–V111 — see §2j).
| Rule | Detail |
|---|---|
| Do not edit V077–V079 SQL on hosts where they already ran | Add forward migrations V010+ instead (see §3 step 2). |
| Do not edit V006–V009 SQL on hosts where they already ran | Add V010+ for follow-on Care Start changes. |
| Authoritative spec | Palliative Care Archetypes.md §7.0 — legacy→canonical mapping, copy fixes, seed content. |
| Apply on dev | .\migrate.ps1 -Target Dev — verified 2026-06-04 on lyncareos_dev (V001–V010, audit PENDING/ORPHAN: none). |
| VPS | V006–V010 applied production 2026-06-04 (image deploy-20260604-1810; app healthy). Do not re-edit V007 SQL on prod — see §2k. |
Header comments in V077__*.sql, V078__*.sql, V079__*.sql point here and to Palliative §7.0 — comment-only edits do not change applied schema.
2d. V105 — prescription script alert dismissals (2026-06-03)
Section titled “2d. V105 — prescription script alert dismissals (2026-06-03)”| Item | Detail |
|---|---|
| File | backend/migrations/V105__script_alert_dismissals.sql |
| Table | script_alert_dismissals — per-user snooze for computed script banners |
| Mirror | Also in backend/schema.sql (fresh installs + test DB via conftest) |
| Apply | .\migrate.ps1 -Target Dev (and normal VPS deploy via init_db() / runner on app start) |
| Product | Ignore hides alert 3 days; rows removed when alert condition no longer applies |
No production data backfill required — table starts empty.
2e. V112 — prescription manual count baseline (2026-06-03)
Section titled “2e. V112 — prescription manual count baseline (2026-06-03)”| Item | Detail |
|---|---|
| File | backend/migrations/V112__patient_scripts_physical_count_baseline.sql |
| Columns | patient_scripts.last_physical_count, patient_scripts.last_physical_count_at |
| Index | idx_dispensings_script_tenant_created on dispensings (script_id, tenant_id, created_at) |
| Mirror | backend/schema.sql + test conftest.py ALTER TABLE … ADD COLUMN IF NOT EXISTS |
| Apply | .\migrate.ps1 -Target Dev and normal VPS deploy (init_db() runner on app start) |
| Product | PATCH pills_available persists authoritative physical count; on-hand uses since-audit fills/dispensings only when baseline exists |
No backfill — existing scripts keep legacy stock formula until a carer saves a physical count.
2f. V113 — dispensings clock_timestamp() defaults (2026-06-03)
Section titled “2f. V113 — dispensings clock_timestamp() defaults (2026-06-03)”| Item | Detail |
|---|---|
| File | backend/migrations/V113__dispensings_clock_timestamp_defaults.sql |
| Change | dispensings.created_at / updated_at default clock_timestamp() (not transaction-frozen NOW()) |
| Why | Since-audit stock compares d.created_at > last_physical_count_at; clock_timestamp() on baseline PATCH and on insert must advance within the same DB transaction (tests and rare multi-write transactions). |
| Code | repositories/dispensings.insert_dispensing sets created_at / updated_at explicitly; schedule dispense paths rely on column default after V113. |
No data migration — existing rows unchanged.
2h. V1 baseline consolidation — complete 2026-06-04
Section titled “2h. V1 baseline consolidation — complete 2026-06-04”Squash pre-v1 migrations into backend/schema/lyncareos_v1_baseline.sql. Pre-v1 SQL archived under backend/migrations/archive/pre-v1/; active forward migrations start at V001__lyncareos_v1_baseline.sql (no-op marker), then V002__… onward. Greenfield init_db() applies the baseline file once. Live cutover done on dev and VPS.
| Item | Detail |
|---|---|
| Runbook | 24-V1-DATABASE-BASELINE-AND-CUTOVER.md |
| Rehearsal | scripts/v1-baseline/Invoke-V1Rehearsal.ps1 on isolated DB lyncareos_v1_rehearsal |
| Undo rehearsal | scripts/v1-baseline/Undo-V1Rehearsal.ps1 |
| Dev cutover | scripts/v1-baseline/Invoke-V1Cutover-Dev.ps1 / Undo-V1Cutover-Dev.ps1 |
| VPS cutover | scripts/v1-baseline/Invoke-V1Cutover-Vps.ps1 / Undo-V1Cutover-Vps.ps1 |
| VPS rollback safety | lyncareos_legacy on server until operator drops it |
| Regenerate baseline | scripts/v1-baseline/Export-V1BaselineFromDump.ps1 from VPS pg_dump -Fc |
| Audit | .\migration-audit.ps1 — PENDING/ORPHAN: none on dev and VPS post-cutover; ARCHIVED rows expected only on brownfield dumps / lyncareos_legacy |
2i. Active forward migrations (post-v1, 2026-06)
Section titled “2i. Active forward migrations (post-v1, 2026-06)”| File | Purpose | Dev | VPS |
|---|---|---|---|
V002__care_alert_auto_resolved.sql | Alert auto-resolve column | Applied | Applied at cutover |
V003__patient_log_dose_quick_scripts.sql | Log Dose quick-script favourites | Applied | Applied (prod 2026-06-04) |
V004__first_dose_reaction_checks.sql | First-dose checks + notification channel | Applied | Applied (prod 2026-06-04) |
V005__key_contacts_palliative_specialist.sql | palliative_specialist role on key_contacts.role_tag | Applied | Applied (prod 2026-06-04) |
V006__reconcile_archetype_copy.sql | REQ-CARE-START-03 — seven archetype rows to Palliative §2 | Applied (2026-06-04) | Applied (prod 2026-06-04) |
V007__reconcile_condition_packs.sql | REQ-CARE-START-02 — twelve canonical packs + legacy purchase remap | Applied (2026-06-04) | Applied (prod 2026-06-04) |
V008__seed_care_start_pack_content.sql | REQ-CARE-START-02 — reason types, observations, self-care, shift tasks | Applied (2026-06-04) | Applied (prod 2026-06-04) |
V009__care_start_patient_columns.sql | REQ-TMPL-02 — patient Care Start columns + shift task templates | Applied (2026-06-04) | Applied (prod 2026-06-04) |
V010__seed_universal_observation_types.sql | Universal observation types + backfill pack links for V008 | Applied (2026-06-04) | Applied (prod 2026-06-04) |
Apply on dev: .\migrate.ps1 -Target Dev (sets DATABASE_URL → lyncareos_dev — do not rely on bare python -m migrations.runner without -Target). VPS: included automatically on next deploy via init_db() → runner. Audit: .\migration-audit.ps1 -Target Dev|Vps -NonInteractive.
2j. V006–V010 — Care Start reconciliation (2026-06-04)
Section titled “2j. V006–V010 — Care Start reconciliation (2026-06-04)”Care Start Phase 1 schema + seed reconciliation. Product steps C1a–C1e, C5c, C7 in 04-ROADMAP §Master Phase 1. Generator for V008: backend/scripts/generate_care_start_seed_sql.py (catalog: backend/care_start/seed_catalog.py).
| File | REQ | Description |
|---|---|---|
V006__reconcile_archetype_copy.sql | REQ-CARE-START-03 | UPDATE all seven condition_archetypes rows to Palliative §2 copy |
V007__reconcile_condition_packs.sql | REQ-CARE-START-02 | Insert twelve canonical §3.2 packs; remap legacy tenant_pack_purchases (see §2k) |
V008__seed_care_start_pack_content.sql | REQ-CARE-START-02 | pack_reason_types, observation types, self-care links, pack_shift_tasks |
V009__care_start_patient_columns.sql | REQ-TMPL-02 | patients.archetype_id, care_profile_slug, care_start_applied_at; patient_shift_task_templates; patient_applied_care_profiles |
V010__seed_universal_observation_types.sql | REQ-CARE-START-02 | Universal observation_types + backfill pack_observation_type_links for V008 |
Service (no migration): backend/services/care_start_service.py — apply_care_start_pack(); POST /api/patients/{id}/care-start; PATCH /api/patients/{id}/care-pattern (C5c). Tests: backend/tests/test_care_start.py. C7: python -m scripts.audit_register_r2_care_start — PASS (CARE-START-REGISTER-R2-AUDIT.md). Prod deploy: V006–V010 on VPS 2026-06-04; paid pack checkout still gated by 21-STRIPE-LIVE §4.1b until C1d + live seed.
Signup bundle (C4a): no extra migration — uses tenants.pending_care_start_pack_slug from V009; logic in services/care_start_checkout.py + stripe_provisioning.py.
2k. V007 — legacy pack purchase remap (production note)
Section titled “2k. V007 — legacy pack purchase remap (production note)”Brownfield tenants may hold multiple legacy tenant_pack_purchases rows that map to the same canonical Care Profile (e.g. breath_starter and carer_wellbeing_pack → general_palliative). A naive UPDATE of all legacy rows in one statement violates tenant_pack_purchases_tenant_id_pack_id_key.
Current V007 behaviour (repo):
DELETElegacy rows when the tenant already owns the canonical pack.UPDATEat most one legacy row per(tenant_id, canonical.pack_id)(DISTINCT ON).DELETEany remaining legacy-slug purchases.INSERTfree starter grants withON CONFLICT (tenant_id, pack_id) DO NOTHING.
If V007 fails on startup with UniqueViolation on tenant_pack_purchases, confirm the deployed image includes §2k logic before re-running. Do not edit applied V007 SQL on production — add V011+ for follow-on catalogue changes.
Pre-flight: .\migration-audit.ps1 -Target Dev — expect PENDING: none after apply. Dry-run: from backend/, $env:DATABASE_URL='postgresql://lyncare:lyncare@localhost:5432/lyncareos_dev'; python -m migrations.runner --dry.
2l. V011–V012 — Care Module events + Cancer pack marketing (2026-06-04)
Section titled “2l. V011–V012 — Care Module events + Cancer pack marketing (2026-06-04)”| File | REQ / area | Description |
|---|---|---|
V011__care_module_events.sql | Care Module Phase A | care_module_events — structured capture events for board + CaptureSession wizard (29) |
V012__cancer_at_home_marketing_copy.sql | Commerce / UX | Data only — UPDATE condition_packs for cancer_at_home: description + feature_bullets (JSONB) for Subscriptions card and preview modal; no new tables |
Dev (lyncareos_dev): through V014 (2026-06-04). VPS production: through V010 until next deploy ships V011–V014; audit with .\migration-audit.ps1 -Target Vps -NonInteractive.
UI (no migration): ConditionPackCard.tsx shows feature_bullets on the card; ConditionPackPreviewDialog.tsx uses marketing layout for cancer_at_home (seed lists behind “See full starter label list”). Catalogue source of truth for copy: backend/care_start/seed_catalog.py + V012 on brownfield.
2n. V014 — reason types per patient (2026-06-04)
Section titled “2n. V014 — reason types per patient (2026-06-04)”| File | Area | Description |
|---|---|---|
V014__reason_types_patient_scope.sql | Care Start / Log dose | reason_types.patient_id NOT NULL; legacy tenant-wide rows removed; backfill from dispensings + care_profile_slug pack seeds |
API: GET /api/reason-types?patient_id= (required). Care Start apply inserts reasons for that patient only. Tier limit max_reason_types counts per person in care.
2p. V026–V027 — care calendar module tasks (2026-07-31)
Section titled “2p. V026–V027 — care calendar module tasks (2026-07-31)”| File | Area | Description |
|---|---|---|
V026__care_tasks_date_scoped.sql | Care calendar | care_tasks.patient_id, date, module source columns; nullable shift_id; RLS via patients; unique index for idempotent calendar_actions apply |
V027__care_task_module_responses.sql | Care calendar | source_task_id, task_prompt, response_kind, response_code, response_recorded_at, response_recorded_by — structured answers for module tasks on the focus-day panel |
API (no extra migration): PATCH /api/care-tasks/{id} accepts response_code when the row has response_kind (validated in calendar_task_responses.py). Apply/undo of actions still audit per task in calendar_actions_service.
Product note: Tasks inserted before V027 (or before manifest task objects) may have NULL response_kind — UI shows prompt/title only until the family re-applies that action on the date (or a future backfill migration runs).
Tests: backend/tests/test_calendar_actions.py, test_calendar_task_responses.py. Doc map: 15-CARE-CALENDAR-COMPOSITION.md §6.
Apply: .\migrate.ps1 -Target Dev; VPS on next deploy via init_db().
2q. V028 — users login count (2026-07-31)
Section titled “2q. V028 — users login count (2026-07-31)”| File | Area | Description |
|---|---|---|
V028__users_login_count.sql | Auth / UX | users.login_count INTEGER NOT NULL DEFAULT 0 — incremented on each completed password, Google, MFA, or register-with-session sign-in; not on refresh-cookie bootstrap |
API: login_count on login/register user payloads and GET/PATCH /auth/me (UserProfile). App: first five logins arm a one-time mobile bottom-nav horizontal scroll hint (frontend/src/lib/mobileBottomNavLoginHint.ts). Tests: backend/tests/test_auth_routes.py (test_login_increments_login_count), frontend/src/test/lib/mobileBottomNavLoginHint.test.ts. Greenfield: column also in backend/schema.sql.
Apply: .\migrate.ps1 -Target Dev; VPS on next deploy via init_db().
2m. V013 — PRN reason medical descriptions (cancer + breathing) (2026-06-04)
Section titled “2m. V013 — PRN reason medical descriptions (cancer + breathing) (2026-06-04)”| File | Area | Description |
|---|---|---|
V013__pack_reason_medical_descriptions.sql | Care Start / UX | ALTER pack_reason_types ADD description; UPDATE rows for cancer_at_home and breathing_difficulties; backfill matching reason_types.description on tenants |
Source of truth: REASON_MEDICAL_DESCRIPTION_BY_PACK in backend/care_start/seed_catalog.py. Regenerate SQL: python -m scripts.generate_v013_reason_descriptions. New applies copy description via insert_reason_type().
UI: More → Reason codes (/admin/reasons); Log a dose shows description under selected reason; pack Preview modal lists description under each label.
2g. V114 — script alert stock_count_needed (2026-06-03)
Section titled “2g. V114 — script alert stock_count_needed (2026-06-03)”| Item | Detail |
|---|---|
| File | backend/migrations/V114__script_alert_stock_count_needed.sql |
| Change | Extends script_alert_dismissals CHECK to allow alert type stock_count_needed |
| Mirror | backend/schema.sql |
| Apply | .\migrate.ps1 -Target Dev and normal VPS deploy |
| Product | Admin-only computed banner when on-hand is 0 but dose log has volume; members see inline guidance only (no migration of user data) |
2a. Repairing a dev DB that lost PHI to a premature V091
Section titled “2a. Repairing a dev DB that lost PHI to a premature V091”If rows have enc_version = 0 and NULL *_enc columns, plaintext was already dropped. Options:
- Restore from a recent dev backup.
- Re-seed from a fresh dev fixture.
- Run
.\scripts\dev-phi-reseed.ps1for synthetic placeholder values (idempotent;enc_version = 0rows only).
2o. Refresh dev from a production snapshot (2026-06-26)
Section titled “2o. Refresh dev from a production snapshot (2026-06-26)”Use when you want lyncareos_dev to mirror live data for comparative testing (subscriptions, entitlements, real tenant shapes). This is not day-to-day migration work — it replaces all dev data.
| Step | Action |
|---|---|
| Pre-flight | .\migration-audit.ps1 -Target Dev -NonInteractive and -Target Vps -NonInteractive — both must show PENDING: none so schema matches after restore. |
| Stop dev | .\scripts\dev-stop.ps1 — release connections to lyncareos_dev. |
| Optional backup | .\db-backup.ps1 -Target Dev or pass -BackupDevFirst to the restore script. |
| Restore | .\scripts\restore-vps-production-to-dev.ps1 (pulls fresh VPS dump by default) or -UseLatestLocal / -DumpPath backups\lyncareos_vps_*.dump. |
| Confirm | Type RESTORE-PROD-TO-DEV when prompted. |
| Start dev | .\scripts\dev-start.ps1 — DATABASE_URL must still target lyncareos_dev, never production. |
Script: scripts/restore-vps-production-to-dev.ps1 · Related: 23-BACKUP-RESTORE-DRILL.md (backup tiers), scripts/sync-docker-postgres-to-dev.ps1 (Docker UAT → dev, not VPS).
After restore:
| Topic | Detail |
|---|---|
| PHI | Dump and restored DB contain real patient data — secured dev PC only. |
| PHI keys | PHI_ENCRYPTION_KEY / PHI_BLIND_INDEX_KEY in backend/.env must match production (or pinned prod copies) to decrypt names and other encrypted fields. |
| Uploads | pg_dump does not include /app/uploads — images may 404 locally. |
| Stripe | Keep test Stripe keys in dev; prod subscription/customer IDs remain in the DB. |
| Never reverse | Do not restore dev into production except controlled disaster recovery with full VPS backup first. |
Verified 2026-06-26: Dev and VPS both at V001–V017, audit PENDING: none on both tiers.
3. Authoring migrations
Section titled “3. Authoring migrations”| Step | Rule |
|---|---|
| 1 | Name VNNN__short_description.sql (three-digit version, double underscore) in backend/migrations/ only — not in archive/pre-v1/. After v1 baseline, next forward file is V002__…. |
| 2 | Never edit a migration already applied on any shared environment — add VNNN+1. |
| 3 | Validate column names against backend/schema.sql, lyncareos_v1_baseline.sql, and prior migrations before merge. |
| 4 | Apply on dev: .\migrate.ps1 -Target Dev (preferred) or dry-run: python -m migrations.runner --dry with DATABASE_URL → lyncareos_dev. |
| 5 | Audit: .\migration-audit.ps1 -Target Dev — ARCHIVED rows on brownfield are expected, not ORPHAN. |
| 6 | Register: Add a row to §1a forward migration register and a §2x note when the change needs more than one line; mirror DDL in schema.sql for greenfield (§3a). |
| 7 | After merge: update 32-KNOWN-DEBTS-REGISTER.md and 04-ROADMAP only if the change affects launch posture. |
Pre-v1 archive: Incremental migrations V001–V114 (except the active v1 marker) live in backend/migrations/archive/pre-v1/ for audit history only. Do not run them on new databases — use lyncareos_v1_baseline.sql + data load (24-V1-DATABASE-BASELINE-AND-CUTOVER.md).
Duplicate version numbers: Historical filenames reuse V017 and V025. V083 was also used twice — V083__clinical_wave1_care_observations and (on some hosts) V083__phi_tenants_enc_columns before tenant PHI columns were re-filed as V089__phi_tenants_enc_columns. Both V083 PHI and V089 archive files exist so audit ORPHAN stays zero. Trust schema_migrations.version on the host, not raw file count.
Orphan rows (zero tolerance): If migration-audit.ps1 reports ORPHAN, add the missing historical file under archive/pre-v1/ (idempotent SQL) or reconcile the DB after operator review — do not dismiss as “pre-existing”.
Data-backfill migrations on large tables (e.g. V099__audit_log_patient_id): V099 adds audit_log.patient_id, runs a series of UPDATE … FROM <owning table> backfills, and creates idx_audit_log_tenant_patient. On dev/UAT audit_log is small and this runs in well under a second. On a production VPS where audit_log has grown large, the backfill UPDATEs take a row lock per touched row and the CREATE INDEX (non-CONCURRENTLY, inside the runner’s transaction) briefly locks writes to audit_log. Audit writes happen inside clinical mutations, so a long lock can stall those requests. Mitigation: apply during the normal low-traffic deploy window (the runner runs at container start, before traffic is served by the new container), and if audit_log is very large, consider pre-running the backfill out-of-band. New rows are populated forward by the routers (no ongoing backfill needed).
4. Production deploy checklist (VPS)
Section titled “4. Production deploy checklist (VPS)”Use when recovering from a failed startup or deploy.ps1 needs context.
| Step | Action |
|---|---|
| 1 | .\migration-audit.ps1 -Target Vps -NonInteractive |
| 2 | cd frontend && npm run build |
| 3 | If V089 applied and V090 pending: .\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded |
| 4 | .\scripts\deploy.ps1 |
| 5 | .\scripts\production-phi-pin.ps1 if PHI_* missing on VPS |
| 6 | Verify schema_migrations and https://app.lyncareos.com/api/billing/tiers → HTTP 200 |
Lesson (2026-05-22): Production was at V073 while repo was at V092 — always audit the host before assuming doc version numbers match reality.
V099__audit_log_patient_id rollout note (2026-05-29): see §3 — backfill + index build can briefly lock audit_log on a large production table; apply in the deploy window.
Production status (2026-05-29): VPS at V099 after deploy magna123456/lyncareos:deploy-20260529-2251. First container start failed (schema.sql index on audit_log.patient_id before V099 ran — fixed in repo by reordering init_db()). Recovery: docker compose … run --rm --no-deps app python -m migrations.runner, then docker compose … restart app. Re-deploy with a post-fix image when convenient so future migrations inherit migrations-first startup.
3a. init_db() order
Section titled “3a. init_db() order”database.init_db() applies schema in this order:
| Order | Step | When |
|---|---|---|
| 1 | lyncareos_v1_baseline.sql | Greenfield only — no public.tenants |
| 2 | migrations.runner (active dir only) | All hosts — no-op when caught up |
| 3 | schema.sql | All hosts — idempotent IF NOT EXISTS |
Brownfield (dev, VPS): step 1 skipped; step 2 applies pending active files only (e.g. V001__lyncareos_v1_baseline no-op marker after Phase 2 deploy). Rationale for migrations-before-schema.sql: schema.sql includes indexes on columns that older databases only receive via numbered migrations. Running schema.sql before migrations caused UndefinedColumn: patient_id on production when V099 was pending.
Authoring rule: when adding a column in VNNN, add the same column to schema.sql for greenfield installs; never rely on schema.sql alone to alter existing production tables.
Dev troubleshooting: PoolTimeout / pages never load
Section titled “Dev troubleshooting: PoolTimeout / pages never load”If the SPA sits on spinners for ~30 s per API call (or ~80 s on Dashboard), check backend-err.log for couldn't get a connection after 30.00 sec. That is pool exhaustion, not slow SQL or GPU work.
| Check | Action |
|---|---|
| Log | backend-err.log — search PoolTimeout |
| Code smell | Same handler uses both Depends(require_tenant_member) and Depends(get_ro_db_with_rls) — use require_tenant_member_read for ctx on read routes (01-ARCHITECTURE.md § Connection pool) |
| Parallel load | Dashboard + StrictMode (dev) fires many /api/* at once — stay within one connection per read request |
| Recovery | .\dev-stop.ps1 then .\dev-start.ps1 after fixing code |
Fixed in repo 2026-05-30 (backend/auth.py, analytics/audit/onboarding read paths). Do not raise DB_POOL_MAX as the first fix — fix dependency stacking first.
2q. PostgreSQL collation and REINDEX after OS upgrade {#2q-postgresql-collation-and-reindex-after-os-upgrade}
Section titled “2q. PostgreSQL collation and REINDEX after OS upgrade {#2q-postgresql-collation-and-reindex-after-os-upgrade}”Why this exists: Application databases use UTF-8 with a glibc collation (typically en_US.utf8). PostgreSQL text indexes record a collation version tied to the host’s glibc. When the operating system (not merely the Postgres Docker image tag) moves to a newer glibc, indexes may become invalid or sort order may change for non-ASCII text until indexes are rebuilt.
Operator rule: After any VPS OS upgrade on the production host, run REINDEX DATABASE lyncareos; as documented in 07-PLATFORM-RUNBOOK.md §18. This is a standard control, independent of schema migrations.
What REINDEX does not fix: Changing the database’s default collation still requires dump/restore into a new cluster — we do not do that for i18n; we keep en_US.utf8 and rely on REINDEX after OS moves.
Dev / Docker UAT: Same command against the relevant Postgres instance when the host OS behind Docker was upgraded and you depend on correct Unicode sort in tests.
Cross-reference
Section titled “Cross-reference”| I need to… | Read |
|---|---|
CI / -Target Production script meaning | 12-CI-REFERENCE.md |
| Open engineering debts | 32-KNOWN-DEBTS-REGISTER.md |
| Product/code inventory | 31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md |