Skip to content

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.

DoDo 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).

VersionFileSummary
V025V025__tenant_account_numbers.sqlPublic tenant + member account numbers
V026V026__care_tasks_date_scoped.sqlDate-scoped care_tasks; module action idempotency
V027V027__care_task_module_responses.sqlStructured module task answers on care_tasks
V028V028__users_login_count.sqlusers.login_count — completed sign-ins for first-run mobile nav hint
V029V029__care_profiles_alacarte.sqlPaid Care Profiles à la carte — clear tier_included grants; revoke tier ledger rows
V030V030__users_care_module_dev_preview.sqlOwner preview toggle — users.care_module_dev_preview
V031V031__i18n_locale_columns.sqlI18N-P1 — tenants.locale, users.locale_override
V032V032__pending_signups_locale.sqlMarketing 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.

MigrationWhen
V089Deploy (adds tenants.name_enc, non-breaking)
V090After 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)”
Terminal window
# Workstation (also in deploy.ps1 preflight):
.\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded
# VPS manual equivalent:
cd /opt/lyncareos
docker 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_fields

Pre-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.

ScriptRole
backend/tools/verify_phi_crypto_health.pyCounts-only decrypt + email_idx check (exit 0/1)
scripts/verify-phi-crypto-health.ps1 -Target DockerUat|VpsWrapper used by release pipeline

Automated hard fail (do not ship on failure):

  1. Docker UAT — push-to-production.ps1 after migrations green
  2. VPS pre-redeploy — deploy.ps1 after backup, before image swap
  3. VPS post-redeploy — deploy.ps1 after smoke, before announce
Terminal window
.\scripts\verify-phi-crypto-health.ps1 -Target DockerUat
.\scripts\verify-phi-crypto-health.ps1 -Target Vps

Output 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.

RiskGate posture
PHI encrypt/decrypt + email_idxHard fail in push/deploy (this section)
MFA key vs mfa_secretFollow-on (pin + secrets audit today)
Stripe live vs test key / webhookPartial (production-secrets-audit.ps1)
Restore dump into env with wrong PHI keysDocumented 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.

WhenAction
DeployApplies automatically on app start with other pending migrations.
Provisionensure_tenant_dek() runs on new tenants (Stripe checkout, auth tenant create, schedule backfill) — not in routers/tenants.py.
Legacy tenantsBackfill 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).

RuleDetail
Do not edit V077–V079 SQL on hosts where they already ranAdd forward migrations V010+ instead (see §3 step 2).
Do not edit V006–V009 SQL on hosts where they already ranAdd V010+ for follow-on Care Start changes.
Authoritative specPalliative 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).
VPSV006–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)”
ItemDetail
Filebackend/migrations/V105__script_alert_dismissals.sql
Tablescript_alert_dismissals — per-user snooze for computed script banners
MirrorAlso 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)
ProductIgnore 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)”
ItemDetail
Filebackend/migrations/V112__patient_scripts_physical_count_baseline.sql
Columnspatient_scripts.last_physical_count, patient_scripts.last_physical_count_at
Indexidx_dispensings_script_tenant_created on dispensings (script_id, tenant_id, created_at)
Mirrorbackend/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)
ProductPATCH 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)”
ItemDetail
Filebackend/migrations/V113__dispensings_clock_timestamp_defaults.sql
Changedispensings.created_at / updated_at default clock_timestamp() (not transaction-frozen NOW())
WhySince-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).
Coderepositories/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.

ItemDetail
Runbook24-V1-DATABASE-BASELINE-AND-CUTOVER.md
Rehearsalscripts/v1-baseline/Invoke-V1Rehearsal.ps1 on isolated DB lyncareos_v1_rehearsal
Undo rehearsalscripts/v1-baseline/Undo-V1Rehearsal.ps1
Dev cutoverscripts/v1-baseline/Invoke-V1Cutover-Dev.ps1 / Undo-V1Cutover-Dev.ps1
VPS cutoverscripts/v1-baseline/Invoke-V1Cutover-Vps.ps1 / Undo-V1Cutover-Vps.ps1
VPS rollback safetylyncareos_legacy on server until operator drops it
Regenerate baselinescripts/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)”
FilePurposeDevVPS
V002__care_alert_auto_resolved.sqlAlert auto-resolve columnAppliedApplied at cutover
V003__patient_log_dose_quick_scripts.sqlLog Dose quick-script favouritesAppliedApplied (prod 2026-06-04)
V004__first_dose_reaction_checks.sqlFirst-dose checks + notification channelAppliedApplied (prod 2026-06-04)
V005__key_contacts_palliative_specialist.sqlpalliative_specialist role on key_contacts.role_tagAppliedApplied (prod 2026-06-04)
V006__reconcile_archetype_copy.sqlREQ-CARE-START-03 — seven archetype rows to Palliative §2Applied (2026-06-04)Applied (prod 2026-06-04)
V007__reconcile_condition_packs.sqlREQ-CARE-START-02 — twelve canonical packs + legacy purchase remapApplied (2026-06-04)Applied (prod 2026-06-04)
V008__seed_care_start_pack_content.sqlREQ-CARE-START-02 — reason types, observations, self-care, shift tasksApplied (2026-06-04)Applied (prod 2026-06-04)
V009__care_start_patient_columns.sqlREQ-TMPL-02 — patient Care Start columns + shift task templatesApplied (2026-06-04)Applied (prod 2026-06-04)
V010__seed_universal_observation_types.sqlUniversal observation types + backfill pack links for V008Applied (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).

FileREQDescription
V006__reconcile_archetype_copy.sqlREQ-CARE-START-03UPDATE all seven condition_archetypes rows to Palliative §2 copy
V007__reconcile_condition_packs.sqlREQ-CARE-START-02Insert twelve canonical §3.2 packs; remap legacy tenant_pack_purchases (see §2k)
V008__seed_care_start_pack_content.sqlREQ-CARE-START-02pack_reason_types, observation types, self-care links, pack_shift_tasks
V009__care_start_patient_columns.sqlREQ-TMPL-02patients.archetype_id, care_profile_slug, care_start_applied_at; patient_shift_task_templates; patient_applied_care_profiles
V010__seed_universal_observation_types.sqlREQ-CARE-START-02Universal 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):

  1. DELETE legacy rows when the tenant already owns the canonical pack.
  2. UPDATE at most one legacy row per (tenant_id, canonical.pack_id) (DISTINCT ON).
  3. DELETE any remaining legacy-slug purchases.
  4. INSERT free starter grants with ON 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)”
FileREQ / areaDescription
V011__care_module_events.sqlCare Module Phase Acare_module_events — structured capture events for board + CaptureSession wizard (29)
V012__cancer_at_home_marketing_copy.sqlCommerce / UXData 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)”
FileAreaDescription
V014__reason_types_patient_scope.sqlCare Start / Log dosereason_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)”
FileAreaDescription
V026__care_tasks_date_scoped.sqlCare calendarcare_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.sqlCare calendarsource_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)”
FileAreaDescription
V028__users_login_count.sqlAuth / UXusers.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)”
FileAreaDescription
V013__pack_reason_medical_descriptions.sqlCare Start / UXALTER 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)”
ItemDetail
Filebackend/migrations/V114__script_alert_stock_count_needed.sql
ChangeExtends script_alert_dismissals CHECK to allow alert type stock_count_needed
Mirrorbackend/schema.sql
Apply.\migrate.ps1 -Target Dev and normal VPS deploy
ProductAdmin-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:

  1. Restore from a recent dev backup.
  2. Re-seed from a fresh dev fixture.
  3. Run .\scripts\dev-phi-reseed.ps1 for synthetic placeholder values (idempotent; enc_version = 0 rows 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.

StepAction
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.
ConfirmType 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:

TopicDetail
PHIDump and restored DB contain real patient data — secured dev PC only.
PHI keysPHI_ENCRYPTION_KEY / PHI_BLIND_INDEX_KEY in backend/.env must match production (or pinned prod copies) to decrypt names and other encrypted fields.
Uploadspg_dump does not include /app/uploads — images may 404 locally.
StripeKeep test Stripe keys in dev; prod subscription/customer IDs remain in the DB.
Never reverseDo 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.


StepRule
1Name 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__….
2Never edit a migration already applied on any shared environment — add VNNN+1.
3Validate column names against backend/schema.sql, lyncareos_v1_baseline.sql, and prior migrations before merge.
4Apply on dev: .\migrate.ps1 -Target Dev (preferred) or dry-run: python -m migrations.runner --dry with DATABASE_URL → lyncareos_dev.
5Audit: .\migration-audit.ps1 -Target Dev — ARCHIVED rows on brownfield are expected, not ORPHAN.
6Register: 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).
7After 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).


Use when recovering from a failed startup or deploy.ps1 needs context.

StepAction
1.\migration-audit.ps1 -Target Vps -NonInteractive
2cd frontend && npm run build
3If 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
6Verify 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.


database.init_db() applies schema in this order:

OrderStepWhen
1lyncareos_v1_baseline.sqlGreenfield only — no public.tenants
2migrations.runner (active dir only)All hosts — no-op when caught up
3schema.sqlAll 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.

CheckAction
Logbackend-err.log — search PoolTimeout
Code smellSame 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 loadDashboard + 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.


I need to…Read
CI / -Target Production script meaning12-CI-REFERENCE.md
Open engineering debts32-KNOWN-DEBTS-REGISTER.md
Product/code inventory31-REQUIREMENTS-CODE-MARKETING-RECONCILIATION.md