Data first, model second¶
I start with the captured FHIR data, then choose the fields the screens and rules need. The generated profile records what is actually present. The profile JSON carries the complete values and lengths; the Data model page reads the same generated output. These fixtures are synthetic examples, not a representative patient population.
flowchart TB
profile[Data profile: counts, fill rates, codes, units, dates]
decisions[Decisions: preserve missing values and select useful fields]
entity[EF model: persistence]
table[SQL table: latest resource version]
domain[Domain model: eligible facts at as_of]
dto[API response: stable JSON contract]
ts[TypeScript model: browser contract]
form[Vue form and Vuetify table: UI state]
profile --> decisions --> entity --> table
table --> domain --> dto --> ts --> form
The profile explains the existing model; it did not cause a schema migration. Observed maximum lengths are evidence about these fixtures, not safe upper bounds for future FHIR data. Id, PatientId and VersionId keep their existing 64-character limits. Other clinical text remains unbounded. Tightening a length to today's maximum would change accepted data and is outside this pass.
Operational EF model¶
The ER block below is generated from the committed EF model snapshot: entity blocks, property types, HasKey, HasIndex, column names and table names. There are no declared foreign keys or navigation relationships in that model. PatientId and ResponseId are application-level references, not enforced database relationships. Adding foreign keys would change the schema and ingest behavior.
Regenerate from the repository root with dotnet run --project tools/OperationalErd. This dependency-free C# documentation tool extracts the snapshot's actual table names, keys, indexed properties and selected clinical fields, writes operational-erd.mmd, and replaces only the marked block below. It prints the source SHA-256 and rejects an unrecognized/foreign-key shape instead of guessing relationships. Nullable types are shown without ? in this compact diagram; the dictionary and entity declarations retain nullability. The full snapshot, rather than this selected-field diagram, remains the schema authority.
erDiagram
allergies {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
conditions {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
questionnaire_responses {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
intake_answers {
string ResponseId PK
int Ordinal PK
string PatientId "nonunique index; logical reference only"
string LinkId
string Question
string Answer
}
encounters {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
immunizations {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
medications {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
observations {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
outbox {
Guid Id PK
DateTimeOffset CreatedAt
string PatientId
string RawJson
string ResourceType
string Status
}
patients {
string fhir_id PK
string Code
double Diastolic
DateTimeOffset Effective
string PatientId "nonunique index; logical reference only"
string Status
double Systolic
double Value
string VersionId
}
quarantine {
Guid Id PK
string Error
string FhirId
string RawJson
string VersionId
string ResourceType
}
staging_fhir {
Guid Id PK
string FhirId
DateTimeOffset IngestedAt
string RawJson
string ResourceType
string Source
string VersionId
}
sync_state {
string ResourceType PK
DateTimeOffset Watermark
}
source_binding {
int Id PK
string SourceIdentity
}
All eight clinical tables use fhir_id as their primary key and have a nonunique PatientId index. VersionId is stored alongside the resource identity; it is not part of that primary key. SyncService.IsNewer uses numeric versions when both versions are numeric, otherwise producer timestamps. The latest accepted version updates the row. staging_fhir retains accepted versions. The source binding prevents IDs from different upstream servers sharing one operational database.
The PatientId indexes serve the patient-summary and CDS queries. intake_answers has primary key (ResponseId, Ordinal) because a questionnaire can repeat a link ID; its PatientId index serves the intake section. No additional time/code indexes were added: that would be a separate measured query-performance change.
This data → this decision → this model¶
For every resource below, look up its paths entry in the generated profile to see presentCount, fillRatePercent, maxLength, distinct values and date bounds. Nulls remain null. A missing field is not a negative finding.
| Entity / table | Data observed and fields selected | Decision, type and omissions |
|---|---|---|
PatientEntity / patients |
id, meta.versionId, meta.lastUpdated, first name, gender, birthDate, US Core race extension |
IDs are strings, not assumed GUIDs. Birth date stays a string because FHIR permits partial dates; age requires a complete yyyy-MM-dd. Only explicit supported race codes become Race; no inference. Addresses, telecom, identifiers and remaining names stay in RawJson; no screen/rule consumes them. |
ObservationEntity / observations |
LOINC coding, valueQuantity, effectiveDateTime or period start, status, BP components and coded smoking value |
Nullable double values support quantitative rules; units are required by each rule. DateTimeOffset? retains instants. Components map only supported LOINC BP codes and mmHg units. Interpretation, performer and unused components stay in raw JSON. |
AllergyEntity / allergies |
SNOMED coding, patient, recorded date, clinical and verification status | Code/display power the allergy table; invalid verification overrides clinical status. Reaction detail and criticality remain in raw JSON because this demo has no reaction rule/editor. Allergy facts do not feed a risk score. |
ImmunizationEntity / immunizations |
CVX vaccine code, occurrence, completion status | Separate code/system prevents confusing vocabularies. Nullable occurrence preserves unknown dates. Lot/manufacturer and dose route are not used by the recorded-dose/care-gap rules. |
ConditionEntity / conditions |
SNOMED concept, onset or recorded date, clinical/verification status | Active explicit diabetes concepts provide positive evidence only. Unrelated history does not establish no diabetes. Severity and body site remain raw. |
MedicationEntity / medications |
RxNorm medicationCodeableConcept, authored date, status |
A bounded supported product list establishes BP treatment. No medication reference resolution or dose inference. Dosage and prescriber remain raw. |
EncounterEntity / encounters |
First encounter type, subject, period start, status | Supports latest encounter in gold. End time, locations and participants remain raw. Not returned in the patient-summary clinical arrays. |
QuestionnaireResponseEntity / questionnaire_responses |
Subject, questionnaire URL, authored date, status and raw items | Retain original response and version. Questionnaire URL uses Display. The operational intake projection handles nested items; the lakehouse does not currently ingest the Ottehr subdirectory. |
IntakeAnswerEntity / intake_answers |
Nested item.linkId, item.text, each answer.value[x] |
One displayed answer per response ordinal. Preserve duplicate link IDs. Question falls back to link ID; strings/coding displays become Answer. Do not turn free text into clinical diagnoses. |
StagingEntry / staging_fhir |
Resource identity/version, source, raw JSON and ingest time | GUID identifies an ingest event, not a FHIR resource. Retain raw evidence for accepted updates; no patient-facing DTO. |
QuarantineEntry / quarantine |
Resource identity/version, raw JSON and mapping error | Separate rejected evidence from clinical facts. The failed version affects cursor progress; it must not silently disappear. No patient-facing DTO. |
SyncState / sync_state |
Resource type and producer update watermark | One cursor per resource type. Nullable watermark forces full replay when safe chronology is unavailable. |
SourceBinding / source_binding |
Source identity | Singleton key 1, string limit 512. Prevents mixing source-specific resource IDs and cursors. This is configuration evidence, not a clinical fact. |
OutboxEntry / outbox |
Validated local allergy request, generated FHIR JSON, created time | GUID event key; status is simulated-not-sent. Local intent is separate from confirmed source data. No automatic upstream write and no new allergy in the synced clinical table. |
Common clinical provenance columns are ResourceType, VersionId, LastUpdated, PatientId, and RawJson. The shared base shape also leaves unused nullable columns in individual tables. Removing those columns would change the database schema; this pass does not do that.
FHIR → entity → SQL → API → form¶
* below means each clinical entity. SQL column casing is deliberate: only Id is renamed to fhir_id; Code, Value, PatientId, etc. retain their EF property names. JSON uses camelCase. The summary response includes historical clinical rows; the risk and summary-bullet paths apply eligibility separately.
| FHIR resource and element | EF property | SQL column | API response field | Vue field | System / rule |
|---|---|---|---|---|---|
All supported types: id, meta.versionId, meta.lastUpdated |
*.Id, VersionId, LastUpdated |
fhir_id, VersionId, LastUpdated |
Clinical id; versions omitted |
row id |
Latest accepted resource version; raw evidence retained |
Patient name[0], gender, birthDate |
PatientEntity.Name, Sex, BirthDate |
patients.Name/Sex/BirthDate |
patient.name/sex/birthDate |
patient heading/selector | No inferred demographic fields |
Patient US Core race extension[ombCategory].valueCoding.code |
PatientEntity.Race |
patients.Race |
Omitted; used in card reasoning | card detail | 2106-3 white / 2054-5 black only; social classification caveat |
AllergyIntolerance code.coding / code.text |
AllergyEntity.Code/System/Display |
allergies.Code/System/Display |
allergies[].code/system/display |
Allergies table; new form allergy.code/display/system |
Prefer SNOMED http://snomed.info/sct |
AllergyIntolerance recordedDate, clinical/verification status |
AllergyEntity.Effective/Status |
allergies.Effective/Status |
allergies[].effective/status |
table date/status | Undated/future or invalid verification excluded from eligible summaries; raw table still shows historical rows |
Observation code.coding, valueQuantity.value, .code or .unit |
ObservationEntity.Code/System/Value/Unit |
observations.Code/System/Value/Unit |
observations[].code/system/value/unit |
Labs & vitals measurement | Prefer LOINC; A1c 4548-4 requires %; lipids 2093-3/2085-9 require mg/dL |
Observation component[8480-6/8462-4].valueQuantity.value |
ObservationEntity.Systolic/Diastolic |
observations.Systolic/Diastolic |
observations[].systolic/diastolic |
formatted BP measurement | LOINC components; panels 85354-9 or 55284-4; mm[Hg] code or mmHg unit |
Observation effectiveDateTime / effectivePeriod.start, status |
ObservationEntity.Effective/Status |
observations.Effective/Status |
observations[].effective/status |
table date/status | Risk uses final/amended/corrected, dated at or before as_of |
Observation 72166-2, valueCodeableConcept.coding |
ObservationEntity.ValueCode |
observations.ValueCode |
Omitted; feeds card | ASCVD card detail | SNOMED smoking codes only; unsupported evidence stays unknown |
Condition code, onset[x] or recordedDate, clinical/verification status |
ConditionEntity.Code/System/Display/Effective/Status |
conditions same-name columns |
conditions[] same camelCase fields |
Conditions table | Prefer SNOMED; active 44054006/46635009 establish diabetes; 15777000 does not |
Immunization vaccineCode, occurrence[x], status |
ImmunizationEntity.Code/System/Display/Effective/Status |
immunizations same-name columns |
immunizations[] same camelCase fields |
Immunizations table | CVX; care gap counts completed supported flu codes in inclusive prior 12 months |
MedicationRequest medicationCodeableConcept, authoredOn, status |
MedicationEntity.Code/System/Display/Effective/Status |
medications same-name columns |
medications[] same camelCase fields |
Medications table | RxNorm 197361/316049/897718; active or recent completed establishes treatment |
Encounter type[0], subject.reference, period.start, status |
EncounterEntity.Code/System/Display/PatientId/Effective/Status |
encounters same-name columns |
No direct summary field; gold last_encounter |
No encounter form in demo | Latest eligible encounter drives gold summary |
QuestionnaireResponse questionnaire, authored, status, subject.reference |
QuestionnaireResponseEntity.Display/Effective/Status/PatientId |
questionnaire_responses same-name columns |
Flattened answers only | Intake section | Ottehr source; entered-in-error responses produce no answer projection |
QuestionnaireResponse nested item.linkId/text, answer.value[x] |
IntakeAnswerEntity.LinkId/Question/Answer |
intake_answers.LinkId/Question/Answer |
intakeAnswers[].linkId/question/answer |
intake question/answer list | Ordinal preserves repeated answers; not a clinical terminology inference |
Lakehouse layers and grain¶
The SQL is in src/FhirDemo.Lakehouse/Helpers/LakehouseRunner.cs. The runner reads top-level clinical fixture files. Ottehr's nested QuestionnaireResponse fixture is an operational-intake example and is not a silver table here.
| Layer/table | Grain | Columns |
|---|---|---|
bronze_fhir |
One append per resource capture per run; replay duplicates are retained | resource_type VARCHAR, id VARCHAR, version_id VARCHAR, last_updated TIMESTAMPTZ, source VARCHAR, ingested_at TIMESTAMPTZ, raw_json JSON |
latest_fhir (temporary view) |
Latest (resource_type,id) |
Bronze columns; numeric version descending, last-updated descending, ingest time descending |
silver_patient |
One current patient | id VARCHAR, version_id VARCHAR, name VARCHAR, sex VARCHAR, birth_date DATE |
silver_observation, silver_encounter, silver_condition, silver_allergy, silver_immunization, silver_medication |
One current resource per table | id, version_id, patient_id, code, code_system, display, unit, status as VARCHAR; value/systolic/diastolic DOUBLE; effective TIMESTAMPTZ; invalid_verification BOOLEAN |
eligible_* (temporary views) |
Eligible silver resource at run clock | Same columns; dated at/before as_of, not invalid verification/cancelled/error/refuted; observations additionally final/amended/corrected |
run_clock (temporary) |
One run | as_of TIMESTAMPTZ |
risk_rule_results |
One patient and emitted rule flag | patient_id, flag, indicator, summary VARCHAR; score DOUBLE; inputs JSON; as_of TIMESTAMPTZ |
Silver preserves source rows. Gold answers specific questions. Risk uses the shared C# mapper and RiskEngine against persisted latest_fhir raw JSON, not a second formula hidden in SQL. This keeps the operational rules and gold flags aligned. SQL selects population slices and outreach order.
Gold data dictionary¶
| Table.column | DuckDB type | Meaning and source rule |
|---|---|---|
gold_patient_summary.id, .version_id |
VARCHAR | Patient identity and latest source version from silver_patient |
.name, .sex |
VARCHAR | First given/family name concatenation; recorded gender from silver |
.birth_date |
DATE | Parsed full birth date; missing/invalid remains null |
.age |
BIGINT | Calendar age at run clock, subtracting one if birthday has not occurred |
.active_conditions |
BIGINT | Count of eligible condition rows whose status is active |
.allergy_count |
BIGINT | Count of eligible allergy rows; not a statement about absent allergies |
.latest_a1c |
DOUBLE | Latest positive finite eligible LOINC 4548-4 in %; time descending then ID |
.latest_bmi |
DOUBLE | Latest eligible code 39156-5; existing SQL does not add a separate system/unit check |
.latest_systolic, .latest_diastolic |
DOUBLE | Same latest eligible supported BP panel with both positive finite components; do not combine different readings |
.last_encounter |
TIMESTAMPTZ | Latest eligible encounter start |
gold_immunization_status.patient_id |
VARCHAR | One row per patient |
.has_recent_flu |
BOOLEAN | Completed eligible CVX flu dose in inclusive [as_of - 12 months, as_of] |
.has_covid |
BOOLEAN | Any completed eligible supported CVX COVID dose before clock; not current immunity |
.as_of |
TIMESTAMPTZ | Clock used to establish both vaccination statements |
gold_lab_trends.patient_id, .id, .code, .display, .unit |
VARCHAR | One eligible quantitative LOINC observation; identity and labels from silver |
.value |
DOUBLE | Non-null source numeric value; this table is broader than risk-valid positive values |
.effective |
TIMESTAMPTZ | Source observation time |
gold_population.category, .label |
VARCHAR | One aggregate per category/label: age_band or active_condition; missing age becomes unknown |
.patients |
BIGINT | Patient count by age band or distinct patients with that active condition label |
gold_risk_flags.patient_id, .flag |
VARCHAR | One patient and emitted flag: a1c, a1c_trend, hypertension, ascvd, flu_gap; no trend row if no A1c |
.score |
DOUBLE nullable | A1c percent, rising-trend 0/1, elevated-BP count, ASCVD percent, or flu gap 0/1; null means insufficient inputs |
.indicator |
VARCHAR | Rule output info or warning; not a diagnosis |
.summary |
VARCHAR | Human-readable rule outcome |
.inputs |
JSON | Shared rule Detail and SourceIds; retains reasoning and citations |
.as_of |
TIMESTAMPTZ | Fixed clock of the population run |
gold_outreach.patient_id |
VARCHAR | One patient with at least one warning; this object is a view |
.warning_count |
BIGINT | Sum of warning indicators across that patient's flags |
.ascvd_percent |
DOUBLE nullable | ASCVD flag score if available; missing score stays null |
.reasons |
VARCHAR nullable | Warning summaries joined with ; |
The grain is part of the model: patient summary and immunization status are one row per patient; lab trends are one row per observation; population is one row per aggregate; flags are one row per emitted rule; outreach is one row per patient with warnings. None substitutes absent measurements with zero. Metabase reads these gold objects. /api/reports/{name} reads gold when available and clearly labels its operational fallback.
Model at every layer¶
Both examples belong to Ali Herman, synthetic patient d00b080d-706e-4cd8-ae87-6531e798b1fd. The allergy is 56ce30b4-941d-4100-8577-0610ad002b6b, SNOMED 419263009, “Allergy to tree pollen.” The A1c is 91c84bf1-1fba-4a9b-93d3-ab26a904b370, LOINC 4548-4, 6.270038819212741 %, displayed as 6.27%. Display rounding does not change the rule input.
| Tier | Model / View / Controller | Allergy value | A1c value | Owner / code |
|---|---|---|---|---|
| 1. Source | FHIR Model | code.coding[0].code=419263009, active; recorded 1952-12-21 |
valueQuantity.value=6.270038819212741, unit %, final |
data/fixtures/d00b080d-706e-4cd8-ae87-6531e798b1fd_AllergyIntolerance_001.json:20; corresponding Observation_002.json:4076 |
| 2. Persistence | SQL Model | allergies.Code/Display/Status; silver code/display/status; gold allergy count includes eligible row |
observations.Value/Unit; silver_observation.value/unit; gold_patient_summary.latest_a1c; gold_risk_flags a1c score |
src/FhirDemo.Data/Data/AppDbContext.cs:131; src/FhirDemo.Lakehouse/Helpers/LakehouseRunner.cs:62 and :117; exact column dictionary above |
| 3. API persistence | EF Model | AllergyEntity.Code="419263009", .Display="Allergy to tree pollen" |
ObservationEntity.Value=6.270038819212741, .Unit="%" |
src/FhirDemo.Data/Models/Entities/ClinicalEntity.cs:41; src/FhirDemo.Core/Helpers/ClinicalMapping.cs:23 |
| 4. Domain | Risk Model | Preserved ClinicalRecord; intentionally no allergy input on RiskPatient |
RiskPatient.Labs[] → LabFact(Code="4548-4", Value=6.270038819212741, Unit="%") |
src/FhirDemo.Core/Helpers/ClinicalMapping.cs:159; src/FhirDemo.Core/Helpers/RiskEngine.cs:32; src/FhirDemo.Core/Models/RiskPatient.cs:11 |
| 5. API contract | API View | allergies[].code/display/status |
observations[].value/unit; card “HbA1c: Prediabetes range” |
src/FhirDemo.Api/Services/ClinicalService.cs:213 (RecordDto); raw FHIR does not cross this boundary |
| 6. API behavior | API Controller | Query patient rows, project allergy fields | Query observations, map eligible facts, evaluate cards | src/FhirDemo.Api/ClinicalEndpoints.cs:36; src/FhirDemo.Api/Services/ClinicalService.cs:58 |
| 7. Browser contract | UI Model | Clinical.code/display/status |
Clinical.value/unit, Summary.cards |
web/src/models/clinical.ts:8 |
| 8. Browser behavior | UI Controller | Patient service loads summary; component owns selection and submit state | Same service; component passes measurement to formatter | web/src/services/patientService.ts:1; web/src/App.vue:110 |
| 9. Browser presentation | UI View | Vuetify allergy table shows tree pollen; form has separate draft code/display/system | Labs table/card shows 6.27%; no browser risk recomputation | web/src/App.vue:413; web/src/App.vue:447; web/src/format.ts:15 |
The table describes the persisted projections and committed snapshot values. Run verification before treating it as evidence of a fresh database execution; VERIFY.md records the actual commands. LINEAGE.md traces each rule and the separate Oystehr implementation.
Reverse path: Add allergy¶
flowchart TB
form[Vue form Model: code, display, system]
controller[UI Controller: patientService]
request[API Model: AllergyRequest]
validation[API Controller: validate ID, SNOMED code and safe display]
fhir[FHIR Model: AllergyIntolerance active and unconfirmed]
outbox[SQL outbox: RawJson and simulated-not-sent]
response[API View: id, status, createdAt, resource]
view[UI View: Stored outbox JSON]
form --> controller --> request --> validation --> fhir --> outbox --> response --> view
The draft is not the synced allergy entity. The API validates a numeric SNOMED code of 1–64 characters, safe nonblank display of 1–200 characters, exact SNOMED system and an existing patient. It generates a new FHIR ID and timestamp, sets active/unconfirmed, saves the outbox and returns 201. Snapshot mode simulates the same interaction in memory; no upstream write occurs. Existing read-only mode still blocks API writes.
C4 Component view and layered view¶
This is a Component-level view inside the API and Vue containers, not a deployment diagram. Structurizr DSL carries the same boundaries for Forge Studio.
flowchart LR
fhir[FHIR source Model]
db[(Operational SQL Model)]
subgraph api[API container]
sync[Sync Controller: source and mapping]
entity[EF Model: ClinicalEntity]
risk[Domain Model and RiskEngine]
endpoint[Endpoint and service Controller]
dto[Response View: JSON contract]
sync --> entity
entity --> risk
entity --> endpoint
risk --> endpoint --> dto
end
subgraph vue[Vue container]
service[Service Controller: HTTP and snapshot]
model[TypeScript Model: Clinical and Summary]
component[Component Controller: selection and draft]
view[View: Vuetify tables and form]
service --> model --> component --> view
view -->|draft request| component --> service
end
fhir --> sync
entity <--> db
dto --> service
service -->|validated request contract| endpoint
| Boundary | Translation owner | Why it exists |
|---|---|---|
| FHIR → clinical record → EF | ClinicalMapping then SyncService / ClinicalEntity.Apply |
Accept an external standard while storing queryable fields and original evidence. FHIR version and status rules stay outside the UI. |
| EF → domain | Clinical projection and ClinicalMapping.ToRiskPatient |
Domain inputs are eligible facts at a clock, not tracked database rows. Missing data remains visible. |
| Domain / EF → response DTO | API endpoint/service | The JSON contract can evolve independently of database schema and EF tracking. Only intended fields leave the server. |
| Response DTO → TypeScript | Patient/report/sync services | Browser types describe the contract; services own transport and snapshot routing. |
| TypeScript → form/view | Vue component | Selection, errors, pending state and drafts belong to the browser. They are not clinical facts until accepted. |
| Request → FHIR outbox | API allergy endpoint/service | Validation and explicit local intent are separate from confirmed source-chart data. |
Layered architecture is the same picture read vertically: presentation → application services → domain/mapping → persistence/source adapters. There is a Model, View and Controller at each application tier, but they do different jobs. An API response is the back end's View; that JSON becomes the front end's Model. The Vuetify template is the browser's View.