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:
| Who | VAAZHVU_DB |
|---|---|
| api container | postgresql://vaazhvu:…@postgres:5432/vaazhvu (set by compose) |
native api (make voice), make run, host scripts | postgresql://vaazhvu:…@127.0.0.1:5432/vaazhvu (in .env, written by make env-secrets) |
| tests, CI, offline runs | a 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.
| Command | Does |
|---|---|
make env-secrets | Generates VAAZHVU_PG_PASSWORD and writes the host VAAZHVU_DB into .env (once; make up and make voice run it) |
make db-migrate | Copies 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-shell | psql on the compose database |
make db-backup | pg_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):
| Module | Tables |
|---|---|
backend/app/ops/persistence.py | events, incidents, units, runtime, vitals, audit, idempotency |
backend/app/platform/store.py | comments, 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)
| Table | Module | Holds |
|---|---|---|
operators | platform/auth.py | Every 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. |
sessions | platform/auth.py | SHA-256 of the session token → account, expiry, revocation, unit_id (a crew shift). |
login_failures | platform/auth.py | Failed sign-ins per username (lockout window). |
citizen_profiles | platform/auth.py | What a citizen shares with the crew: blood group, conditions, allergies, medications, emergency contact, language. |
hospital_records | ops/hospital_records.py | One 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. |
callers | platform/callers.py | Caller 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_reports | platform/callers.py | The outcome recorded for each incident (disposition, what it counts as, actor, note, pruned). |
ambulance_tiers | ops/tiers.py | Tier 1-3: name, description, the capabilities a unit must carry. |
severity_tiers | ops/tiers.py | Severity → the least tier that may answer it, with a note. |
Caller SMS and crew contact (migration 6)
| Table | Module | Holds |
|---|---|---|
sms_outbox | ops/sms_out.py | Every 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_contacts | ops/locating.py | The 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)
| Table | Module | Holds |
|---|---|---|
hospital_records (new columns) | ops/onboarding.py add_record_columns | stroke_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_applications | ops/onboarding.py | Every /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_operators | ops/onboarding.py | Approved private fleets: name, contact, application. |
fleet_units | ops/onboarding.py, ops/fleet_sources.py | Ambulance 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_checks | ops/hospital_checks.py | Live-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)
| Table | Module | Holds |
|---|---|---|
er_cases | ops/er_handoff.py | One 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_status | ops/er_handoff.py | The 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_13 | ed_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_updates | ops/hospital_records.py | Every 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_attempts | ops/outreach.py | Asking 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)
| Table | Module | Holds |
|---|---|---|
trip_logs | ops/trips.py | One 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(). |
referrals | ops/referrals.py | Inter-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(). |
consults | ops/consult.py | Crew ↔ 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)
| Table | Module | Holds |
|---|---|---|
traffic_corridors | ops/traffic_police.py | One 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_attempts | ops/call_attempts.py | Every 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_history | ops/hotspots.py, scripts/import_irad.py | Imported 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. |
hotspots | ops/hotspots.py | The 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)
| Table | Module | Holds |
|---|---|---|
idempotency | ops/persistence.py (replay_get / replay_put / prune_replays), used by observability/middleware.py ReplayCache | The 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)
| Table | Columns | Purpose |
|---|---|---|
events | seq (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). |
incidents | id (PK), updated, status, data (JSON text) | Latest JSON snapshot per incident. Rebuilt from the event log on restart. |
audit | id (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)
| Table | Holds | Notes |
|---|---|---|
comments | Per-incident threaded notes, mentions, resolved/deleted flags | Soft delete (deleted=1, body cleared). |
attachments | Uploaded file metadata (filename, content type, size, sha256, note) | Content-addressed by sha256; soft delete. |
shares | Expiring external share links | Stores only SHA-256(token); plaintext returned once at creation. Tracks views / last-viewed. |
webhooks | Registered receivers: URL, events, active flag, failure count | Must store the signing secret to sign deliveries (never returned after creation, only rotated). |
deliveries | Webhook delivery queue with attempts, next attempt, response code, error, duration | UNIQUE(webhook_id, event_id) dedupes; indexed for pending work. |
api_keys | Scoped API keys | Stores SHA-256(raw); prefix is public, plaintext returned once. Capped by the creator's role. |
drafts | Autosaved form bodies per (actor, key) | Optimistic concurrency via a version column. |
telemetry | Anonymous 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):
| Table | Rows | Note |
|---|---|---|
events | 4,252 | Top types: vitals.updated 2,316, incident.status 254, route.started 188, message.sent 184, hospital.alerted 133 |
incidents | 58 | Mixed statuses: resolved, at_hospital, triaging, awaiting_location, on_scene |
audit | 249 | Actors: auto, policy, optimizer, crew, caller |
| platform tables | 0 / absent | Not 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)
| Store | What | Why |
|---|---|---|
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 Observations | Separate clinical-interop store; nothing reads it back into Vaazhvu. |
Prometheus / Grafana (monitoring profile) | Metrics TSDB | Observability only. |
var/live.log | Structured app + access log | Debugging; git-ignored. |
Retention, reset and inspection
-
Retention: there is no event/incident/audit pruning.
Platform.prune(retentioninconfig/platform.yaml) prunestelemetry, finisheddeliveries, olddrafts, andidempotencyrows 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 droppingpg-dataresets everything. -
Inspect:
make db-shell, then for example\dtSELECT 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 theschema_versiontable (CREATE TABLE IF NOT EXISTSalone cannot add a column to an existing DB).
Related
- Events and the lifecycle: Architecture
- The live API that reads/writes it: API reference
- Generated data (not in the DB): Data
- Web platform tables and their endpoints: Web platform