Skip to main content

Database

The system of record is Postgres 16, the postgres service in docker-compose.yml (data in the pg-data volume, 127.0.0.1:5432 only). VAAZHVU_DB names it:

WhoVAAZHVU_DB
api containerpostgresql://vaazhvu:…@postgres:5432/vaazhvu (set by compose)
native api (make voice), make run, host scriptspostgresql://vaazhvu:…@127.0.0.1:5432/vaazhvu (in .env, written by make env-secrets)
tests, CI, offline runsa SQLite path (:memory: in tests); unset = var/vaazhvu.db

The container and the native api reach the same database over TCP, so switching between them (make voice / make voice-stop) copies and locks no file. Before, both opened one SQLite file through Docker Desktop's file share, which corrupted it on 2026-10-04 and needed a lease file whose leftovers crash-looped the next api.

One live api per database. The api claims the database at startup, before it restores or writes anything, with a Postgres advisory lock on a connection of its own (ops/db.py OwnerLock). Postgres drops the lock the moment that connection closes, so a killed api (SIGKILL, exit 137) leaves nothing behind. A second api that finds the lock held logs who holds it and exits 0 before binding its port; compose's restart: on-failure then leaves the container stopped instead of crash-looping beside the native api. Scripts (make mcp-key, make team, imports) open the database next to the running api without claiming it.

One dialect. Modules write SQLite's SQL through the sqlite3 interface; ops/db.py runs it on Postgres (placeholders, DDL types, SQLite-like typing of parameters, rollback on error, reconnect after a Postgres restart). New SQL must run on both: INSERT … ON CONFLICT … DO NOTHING / DO UPDATE (qualify the table's own columns on the right of SET), RETURNING instead of lastrowid, ops.db.columns() instead of PRAGMA table_info, Store.json_text() instead of json_extract. make test runs the suite on SQLite, make test-pg on a throwaway Postgres (each test database a schema of its own); CI runs both.

CommandDoes
make env-secretsGenerates VAAZHVU_PG_PASSWORD and writes the host VAAZHVU_DB into .env (once; make up and make voice run it)
make db-migrateCopies var/vaazhvu.db into Postgres (scripts/migrate_sqlite_to_pg.py): one read snapshot, values coerced to the column types, rows that cannot fit reported and skipped, sequences moved past the copied ids, row counts checked. Holds the owner lock, so stop the api first. FORCE=1 replaces data already there
make db-shellpsql on the compose database
make db-backuppg_dump into var/backups/

Commits do not wait for the WAL flush (synchronous_commit=off, the writer connection only): a crash can lose the last few hundred milliseconds of commits, never corrupt the database, the trade SQLite's synchronous=NORMAL made.

Tables, by the modules that own them (every table is created when the database is opened, by numbered migrations in backend/app/ops/migrations.py):

ModuleTables
backend/app/ops/persistence.pyevents, incidents, units, runtime, vitals, audit, idempotency
backend/app/platform/store.pycomments, attachments, shares, webhooks, deliveries, api_keys, drafts, telemetry

Not in the database: GIS, the mapped hospitals and their LLM profiles, the fleet plan and app copy. Those are in-memory JSON/config (see Data). What hospitals enter about themselves is in the database (hospital_records) and overrides the map for that hospital.

Accounts, hospitals, callers and tiers (migrations 3-5)​

TableModuleHolds
operatorsplatform/auth.pyEvery account: username, display_name, role, scrypt pw_hash, disabled, kind (staff / citizen), hospital_id (a hospital account's one hospital), phone (a citizen's number, also their username), created_by, last_login.
sessionsplatform/auth.pySHA-256 of the session token → account, expiry, revocation, unit_id (a crew shift).
login_failuresplatform/auth.pyFailed sign-ins per username (lockout window).
citizen_profilesplatform/auth.pyWhat a citizen shares with the crew: blood group, conditions, allergies, medications, emergency contact, language.
hospital_recordsops/hospital_records.pyOne row per hospital entered or edited: identity, level, taei_level, capability flags, er_beds / icu_beds / ventilators, diversions, load_score, note, source (osm corrected by its staff / portal added by hand), verified, who and when.
callersplatform/callers.pyCaller reputation keyed by an HMAC of the number (never the number): masked label, counts of calls, genuine, unclear, hoax, abusive, status (ok / watch / flagged), who set it.
caller_reportsplatform/callers.pyThe outcome recorded for each incident (disposition, what it counts as, actor, note, pruned).
ambulance_tiersops/tiers.pyTier 1-3: name, description, the capabilities a unit must carry.
severity_tiersops/tiers.pySeverity → the least tier that may answer it, with a note.

Caller SMS and crew contact (migration 6)​

TableModuleHolds
sms_outboxops/sms_out.pyEvery text message sent (or simulated) to a caller: ts, incident_id, to_number, kind (dispatched, location_request, silent_call), body, status (simulated / sending / sent / failed), simulated (1 when no gateway is configured: never reported as delivered), gateway_ref, error. One non-failed row per kind per incident. Live state: cleared by Store.reset().
unit_contactsops/locating.pyThe crew phone number per unit (unit_id PK, phone, updated, actor), shown to the caller once that unit is dispatched. Empty unless a crew or dispatcher sets it (PUT /units/{id}/contact).

Onboarding, ambulance registry, hospital upkeep (migration 8)​

TableModuleHolds
hospital_records (new columns)ops/onboarding.py add_record_columnsstroke_unit, toxicology, anti_snake_venom, scorpion_care (0/1); ownership (government / private / trust / unknown); nk48_empanelled, cmchis_empanelled (1 / 0 / NULL = not known); helpline_phone; confirmed_at / confirmed_by (staff said "still correct"); capacity_reported_at / capacity_reported_by (last save touching beds, diversion or load). source gains onboarding and registry.
onboarding_applicationsops/onboarding.pyEvery /onboard submission: kind (hospital / fleet), status (pending / approved / rejected), the form as JSON (never the password), contact, operator_id (the hospital's reserved account, disabled until approval), hospital_id / fleet_operator_id (what approval created), reason, token_hash (the applicant's status token), client, who decided and when.
fleet_operatorsops/onboarding.pyApproved private fleets: name, contact, application.
fleet_unitsops/onboarding.py, ops/fleet_sources.pyAmbulance registry: unit id (PV001…), source (onboarded, or plan / avl for a unit an admin disabled), status (pending / active / rejected), enabled, registration_no, type, capabilities (JSON), base, crew_phone, location_mechanism (crew_app / avl / manual).
hospital_checksops/hospital_checks.pyLive-capacity call tasks: hospital, phone, due, status (due / calling / done / failed / no_phone), source (agent_call / manual_call), result (JSON of what the hospital said), attempts, error.

migrate() applies every migration whose number is not recorded in schema_version (not only those above the highest), because numbers are reserved per change and can land out of order.

Facility registries: scripts/import_facilities.py imports a CSV / JSON export (facility id, name, lat, lon, ownership, district, facility type, emergency, phone) into hospital_records as source: registry, unverified; it fills only empty fields of an existing record. A live ABDM Health Facility Registry connector needs ABDM credentials.

Why hospitals type their own data: a connection to the state's 108 / 112 systems would be the authoritative source, but it needs government authorisation that a pilot does not have. Until then each emergency department keeps its record on the ER board, and an administrator verifies it.

ER command interface (migrations 12-14)​

TableModuleHolds
er_casesops/er_handoff.pyOne row per (hospital, incident): state (inbound / arrived / accepted / ift_requested / released / declined / closed), first_alerted, last_alert_ts / _reason, ack_ts / ack_by, arrived_ts, accepted_ts / accepted_by, department, notes, released_ts / _to / _reason, declined_ts / _by / _reason, referral_ids (JSON), ift (JSON: reason, needs, transport, who, when). Kept in step by the bus.
er_prep_statusops/er_handoff.pyThe ER's status per preparation item (config/er_prep.yaml id): not_started / in_progress / ready / not_available / not_required, note, who, when.
hospital_records (new columns, 13)ops/hospital_records.py migrate_13ed_status (accepting / limited / diversion / unavailable), ed_status_reason, resus_bays, monitored_beds, operating_theatres, cath_lab_available (1 / 0 / NULL), specialists (JSON [{specialty, state, updated, updated_by}]).
hospital_resource_updatesops/hospital_records.pyEvery change of a tracked record field: hospital_id, field (or specialist:<id>), old, new (JSON), source (er_board / record_form / admin / onboarding / integration / capacity_call:agent_call|manual_call), actor, ts, note. Gives each figure its freshness and history.
outreach_attemptsops/outreach.pyAsking an ER: kind (prealert / referral), hospital, incident, referral, channel (board / phone), state (pending / calling / answered / accepted / declined / no_answer / unreachable / closed), attempts, result (JSON).

All are live state, cleared by Store.reset().

Trip logs, referrals, consults (migration 9)​

TableModuleHolds
trip_logsops/trips.pyOne row per ambulance per incident (UNIQUE(incident_id, unit_id)): status (open / closed), dispatched_ts, data JSON: stages (dispatched, accepted, departed {from: base|elsewhere}, on_scene, departed_scene, at_hospital, cleared, back_at_base {at}; each {ts, sim}), legs (purpose, planned metres, ETA, driven metres estimated by the clock), odometer (start / end km, who, when), destinations (from / to hospital, reason, actor, ts), agency_remarks (police / fire acks and messages), crew_remarks, hospital_id, outcome, call time. Filled only by listening to bus events. Live state: cleared by Store.reset().
referralsops/referrals.pyInter-facility transfer requests: status (requested / accepted / queued / dispatched / completed / declined / cancelled), urgency, from_hospital, to_hospital (NULL = any hospital with the services), accepted_by, incident_id (the IFT incident once dispatched), data JSON (patient summary / diagnosis / age / sex, needs, transport, incident_type, notes, declined_by, history). Live state: cleared by Store.reset().
consultsops/consult.pyCrew ↔ ERC physician consults: incident_id, unit_id, status (open / closed), question, created_by, closed_ts / closed_by, data JSON (messages [{actor, role, text, advice, ts}], close_note). Live state: cleared by Store.reset().

Vitals rows (vitals table, migration 1) now carry an id per reading and, when the crew voids one, voided: {ts, by, reason} in their JSON (updated in place; the reading is never deleted).

Green corridors, call attempts, hotspots (migration 10)​

TableModuleHolds
traffic_corridorsops/traffic_police.pyOne row per green-corridor request: incident_id, unit_id, status (requested / accepted / declined / closed), and data JSON (route geometry, ETA, distance, junctions with alerted, the traffic police answer, close reason). Open ones are reloaded at start. Live state: cleared by Store.reset().
call_attemptsops/call_attempts.pyEvery voice-line connection and every failed app attempt: channel, caller_key (msisdn:… / account_id:… / device_id:…), caller JSON, device lat / lon if sent, started_ts, connected_ts (first words), ended_ts, status (ringing / connected / abandoned / failed), waited_sec, incident_id, previous_attempts (same caller within call_attempts.repeat_window_min), reason, callbacks JSON (dispatcher, outcome, note). Live state: cleared by Store.reset().
crash_historyops/hotspots.py, scripts/import_irad.pyImported road-crash records (iRAD / blackspot CSV): source + source_ref (unique; the file's id column, else a hash of place + time), ts (region time), lat, lon, severity, fatalities, injuries, raw row. CSV columns, case-insensitive: lat|latitude, lon|lng|long|longitude, datetime or date (+ time) (ISO, dd-mm-yyyy, dd/mm/yyyy), severity, fatalities|killed|deaths, injuries|injured, id|accident_id|fir_no. Empty until someone imports a file; nothing ships with the repository. Historical: not reset.
hotspotsops/hotspots.pyThe last computed top cells: cell_id, rank, centroid lat / lon, score, incidents, crashes, fatalities, data JSON (counts by hour, weekday, month, season, type, severity; peak hours), refreshed_ts. Rebuilt by refresh() (on demand, or by GET /hotspots when older than hotspots.refresh_every_sec); the refresh time is in runtime key hotspots_refreshed.

Idempotent writes (migration 11)​

TableModuleHolds
idempotencyops/persistence.py (replay_get / replay_put / prune_replays), used by observability/middleware.py ReplayCacheThe first 2xx response (status, headers JSON: content-type and location only, body up to 256 KiB) of each write sent with an Idempotency-Key, keyed by (client, method, path, key), with created. A retry, also after a restart, gets this response back instead of running again. Rows older than 24 hours never replay; they are deleted, with all but the newest 20,000, at most hourly on write and by Platform.prune. Not cleared by Store.reset().

Core tables (ops/persistence.py)​

TableColumnsPurpose
eventsseq (PK, autoincrement), event_id (unique), event_type, ts, incident_id, source, schema_version, payload (JSON text)Append-only domain event log. seq is global and monotonic. Idempotent on event_id (a duplicate returns no new row). Indexed on (incident_id, seq) and (ts).
incidentsid (PK), updated, status, data (JSON text)Latest JSON snapshot per incident. Rebuilt from the event log on restart.
auditid (PK), ts, actor, action, incident_id, input, output (JSON text)Who did what: AI recommendations, policy outcomes, human approvals/overrides.

Platform tables (platform/store.py)​

TableHoldsNotes
commentsPer-incident threaded notes, mentions, resolved/deleted flagsSoft delete (deleted=1, body cleared).
attachmentsUploaded file metadata (filename, content type, size, sha256, note)Content-addressed by sha256; soft delete.
sharesExpiring external share linksStores only SHA-256(token); plaintext returned once at creation. Tracks views / last-viewed.
webhooksRegistered receivers: URL, events, active flag, failure countMust store the signing secret to sign deliveries (never returned after creation, only rotated).
deliveriesWebhook delivery queue with attempts, next attempt, response code, error, durationUNIQUE(webhook_id, event_id) dedupes; indexed for pending work.
api_keysScoped API keysStores SHA-256(raw); prefix is public, plaintext returned once. Capped by the creator's role.
draftsAutosaved form bodies per (actor, key)Optimistic concurrency via a version column.
telemetryAnonymous feature events (name, path, props, session)Only table with pruning (prune_telemetry(before)). No content, ever.

What is actually stored right now​

From the local dev DB (numbers move as the demo runs):

TableRowsNote
events4,252Top types: vitals.updated 2,316, incident.status 254, route.started 188, message.sent 184, hospital.alerted 133
incidents58Mixed statuses: resolved, at_hospital, triaging, awaiting_location, on_scene
audit249Actors: auto, policy, optimizer, crew, caller
platform tables0 / absentNot yet instantiated in this DB (see the lazy-creation note above)

An incident snapshot is a large JSON object (text, triage, policy, decision, vitals[], messages[], units[], status_history[], fhir, news2, outcome, …). Vital signs come from the simulated monitor (source: monitor-sim/neurokit2) with a NEWS2 score and risk band per reading.

Secondary stores (not the source of truth)​

StoreWhatWhy
NATS JetStream (nats-data volume)Mirror of every bus event on ems.<event_type>Durable fan-out for other consumers; survives restarts. Not the system of record.
HAPI FHIR (VAAZHVU_FHIR_URL, optional)Patient / Encounter / vital-sign ObservationsSeparate clinical-interop store; nothing reads it back into Vaazhvu.
Prometheus / Grafana (monitoring profile)Metrics TSDBObservability only.
var/live.logStructured app + access logDebugging; git-ignored.

Retention, reset and inspection​

  • Retention: there is no event/incident/audit pruning. Platform.prune (retention in config/platform.yaml) prunes telemetry, finished deliveries, old drafts, and idempotency rows past their 24-hour TTL. The DB grows with every demo run.

  • Reset: Store.reset() empties the live tables (events, incidents, audit, units, runtime, vitals, hospital_records, callers, caller_reports, sms_outbox, traffic_corridors, call_attempts, …) and restarts their ids; accounts and tiers stay. docker compose down -v (deletes every volume) or dropping pg-data resets everything.

  • Inspect: make db-shell, then for example

    \dt
    SELECT event_type, COUNT(*) FROM events GROUP BY 1 ORDER BY 2 DESC;
    SELECT id, status, to_timestamp(updated) FROM incidents ORDER BY updated DESC LIMIT 10;
    SELECT application_name, client_addr FROM pg_stat_activity WHERE application_name LIKE 'vaazhvu owner%'; -- who owns it
  • Migrate: schema changes are numbered, idempotent migrations in backend/app/ops/migrations.py, recorded in the schema_version table (CREATE TABLE IF NOT EXISTS alone cannot add a column to an existing DB).