# Clinical data integration contracts: design

Written and committed before any result was computed. Every number below is a declared input or a declared rule, not a
finding.

## Question

When clinical records arrive from several feeds (clinical messages, lab results, device readings, enrollment and claims
files), which integration contract checks keep patient identity, clinical meaning, time, provenance and consent intact,
and what does each failure do to a downstream metric if no contract catches it?

## Overlap with published studies

The data quality scorecard asks whether a short list of checks on one daily load of one public table catches a bad
load. This study asks a different question: what happens to published metrics when records from six feeds in three
formats are joined across identities, units, clocks and consent. Nothing in the scorecard joins feeds, resolves
identity, converts units or enforces consent. The family is the same (checks against faults); the question and the data
are not, so this is a new study and not a round of the scorecard.

## Data: synthetic, on fixed seeds

No real patient data of any kind. Every person, name, record and value is generated by `cdc/world.py` from a seed. The
generator holds the truth for every record: the true person, the true event time, the true unit and value, the true
coverage and the consent state.

The exchange fixtures are shaped after public standards, using only their public descriptions: HL7 version 2 messages
(ADT admit, discharge and outpatient visit; ORU lab results), FHIR R4 Observation and Consent resources as JSON, and
X12 834 (enrollment) and 837P (professional claims) segment layouts. They are not validated against the licensed X12
implementation guides and make no conformance claim. Lab and device observations carry LOINC codes (five codes, listed
in `NOTICE.txt` with their LOINC display names). Diagnosis codes on claims are ICD-10-CM codes, published by the US
government. No synthetic patient generator is used; the population is built here so every truth field is known.

### The world (per seed)

- 12,000 people, one plan, three sites (North 40%, Central 35%, South 25%), local time zone America/Toronto, a synthetic
  year of 12 months plus two months after it so late records and 30-day windows can close. Months 1 and 2 are warm-up
  (no check has history yet); metrics are reported for months 3 to 12.
- Identity: every person has one MRN (eight digits, zero padded), one plan member id (`M` and nine digits), a name, a
  date of birth, a sex and a postal code. The enrollment file's demographics differ from the clinical system's for 7% of
  people (nickname, typo, hyphenated or changed surname, day and month swapped in the date of birth). 0.5% of people
  have a twin: same surname, date of birth and postal code, different first name.
- Coverage: 85% are members at the start; each month 1.2% of members terminate and 1.0% of non-members enroll. 30% of
  terminations are reversed later by a back-dated reinstatement. Enrollment changes arrive in weekly 834 change files;
  20% of terminations arrive 20 to 60 days after the termination date (retroactive).
- Lipid monitoring: 35% of people; each month 30% of them have a lipid panel (LDL cholesterol and total cholesterol) at
  their home site. True LDL is a person level baseline (log-normal, median 110 mg/dL) plus test noise.
- Admissions: 1% of people a month; length of stay 1 to about 8 days. After discharge, 62% have an outpatient visit
  within 30 days and 12% between day 31 and day 45. 55% of those visits are at the in-system clinic (an HL7 visit
  message); the rest are with outside providers, seen only as 837P claims, and only while the person is a member.
- Routine outpatient visits: 0.25 a person a month, split the same way.
- Remote blood pressure monitoring: 4% of people, each with their own daily chance of taking a reading (mean about
  0.67).
- Consent: 3% of people withdraw consent for analytics use at a random time in months 2 to 11. In the no-fault world the
  sources stop sending a person's records after withdrawal.
- Arrival: clinical messages arrive within minutes; lab results 2 to 36 hours after the draw; device readings within
  an hour; claims with a log-normal lag (median 12 days); enrollment weekly.

### Publication (what a team reads, and when)

Each month's metric is computed once, from the records that had arrived by its publication time:

| Metric | Definition | Published |
|---|---|---|
| LDL control rate | Of people with an LDL result drawn in the month, the share whose last LDL in the month is under 100 mg/dL | 7 days after month end |
| 30-day follow-up rate | Of inpatient discharges of active members in the month, the share followed by an outpatient visit within 30 days | 45 days after month end |
| Active enrolled members | Distinct members with an active coverage span on the 15th | 7 days after month end |
| Monitoring adherence | Of people enrolled in blood pressure monitoring for the whole month, the share with readings on 16 or more days | 3 days after month end |

Truth is computed from the generator: true events, true values, true coverage, excluding people who had withdrawn consent
by the publication time. Error is the published value minus truth, per month, never pooled across metrics.

## Faults: a declared schedule (base case)

Each fault is an integration defect: it changes what the feeds deliver, never the care that happened.

| Id | Fault | Base case |
|---|---|---|
| F1 | Shared identifier reformatted: one site's lab interface strips leading zeros from the MRN | South lab, every message from month 5 |
| F2 | Shared identifier lost: clinical messages stop carrying the plan member id | all sites, from month 6 |
| F3 | Duplicate registration: an outpatient visit creates a second MRN for an existing patient | 4% of in-system visits from month 4 |
| F4 | Lab unit change, labelled: LDL sent in mmol/L with the unit field saying so, under the mass code | Central lab from month 7 |
| F5 | Lab unit change, unlabelled: LDL sent in mmol/L with the unit field still saying mg/dL | 30% of North LDL results from month 9 |
| F6 | Code mapped to the wrong concept: total cholesterol sent under the LDL code | South lab from month 8 |
| F7 | Time zone: UTC clock times sent without an offset, read as local time | North clinical and lab messages from month 8 |
| F8 | Late records: a claims backlog | 50% of claims due to arrive in month 10 delayed 45 to 75 more days |
| F9 | Device feed gap: readings lost in an outage and never resent | days 10 to 18 of month 6 |
| F10 | Enrollment spans that do not match claims: reinstatements never sent | 60% of reinstatements from month 3 |
| F11 | Records arriving after consent was withdrawn | device and claims feeds, every record after withdrawal |
| F12 | Malformed values: lab values like `<40` or `112 H`, units left blank | 3% of lab messages from month 4 |

Scenarios: no fault; each fault alone; all twelve together. Fault shares are assumptions. A sweep runs each fault at half
and double its base share (capped at every message), so the page can say how the metric error scales with the share.

## Arms: the contracts

The same parser front end and the same metric queries run in every arm; the arms differ only in the checks applied
between landing and the metric.

1. **No contract.** Load what arrives. Lenient parsing (digits pulled out of a value, a missing unit read as mg/dL,
   an unparseable date left empty), joins on the raw identifier, exact match on first name, surname and date of birth
   where no identifier is shared, every value read in the unit the metric expects.
2. **Schema only.** Required segments and fields present, types and formats valid (HL7 timestamps, FHIR dateTime with an
   offset whenever a time is given, X12 dates), numeric values numeric, units present, enumerated fields in their lists.
   A failing record is quarantined. Joins and units as in arm 1.
3. **Semantic.** Schema, plus:
   - **S1 identifier format**: MRN and member id patterns; an unambiguous variant (missing zero padding) is normalised,
     anything else quarantined.
   - **S2 identity matching**: a scored match on names (Jaro-Winkler, a small nickname table), date of birth, sex and
     postal code links clinical records to members where no identifier is shared, and finds duplicate MRNs. Weights in
     `cdc/contracts.py`; link at a score of 8.0 or more out of 11.5; 5.5 to 8.0 goes to a review list (flagged, not
     linked).
   - **S3 units and ranges**: each code has an expected unit property (mass or moles per volume); a declared unit that
     disagrees with the code is converted (LDL: 1 mmol/L = 38.67 mg/dL) and flagged; a value outside the plausible range
     for its unit (LDL 15 to 400 mg/dL) is quarantined.
   - **S4 code sets**: lab and device codes must be in the value set; local codes must map through the versioned map.
   - **S5 distribution drift**: per source and code, the month's median against the trailing three months; a shift over
     12% with at least 30 results holds that source's results for the month.
   - **S6 event time against arrival time**: an event stamped more than 10 minutes after it arrived is quarantined.
   - **S7 completeness**: per source and day, arrived volume against the trailing 28-day median; a day under 30% marks a
     gap and holds the metric month that reads it. For claims, the share of the month's claims that had arrived by
     publication against the same share in the three months before; under 85% holds the month.
   - **S8 enrollment against claims**: claims with a service date outside every coverage span of the member; if such
     members exceed 0.3% of active members, the month's member count is held.
   - **S9 consent gate at read time**: rows of people whose consent was withdrawn by the read time are excluded.
   - **S10 provenance**: every row carries its source interface, site, message id, arrival time and contract version.
     It catches nothing alone; S5 and S7 group by it.

A held month is published with a flag instead of as final. The page reports both the error of the number and the error
left in months published as final ("silent error").

Ablation: on the all-faults scenario, the semantic arm is also run with each of S1 to S10 removed in turn, to show what
each check is worth on its own.

## What is measured, and what is true by construction

Every declared fault and every semantic check were written by the same hand, so the semantic arm's catch of a declared
fault is a self-test. Several catches are true by construction: the consent gate (S9) removes withdrawn people's rows
because that is its definition; identifier normalisation (S1) undoes exactly the reformatting F1 applies; the labelled
unit change (F4) is converted because the unit field says so. These are reported as such and are not evidence that the
checks work.

The measured parts are: how much error each fault leaves in each metric when a check is missing (the no-contract and
schema arms), which faults reach no metric at all, how much of the measured population each fault removes, how many
false holds the checks raise with no fault, and how the checks fare on faults written without sight of them.

## Faults written blind

An independent author who never saw the checks, the declared faults or this file writes up to ten integration faults
as Python functions over the feed envelopes. The author sees only a description of the feeds, the envelope format, the
four metrics, and a few sample envelopes from a seed not used in the study. The author's instructions are committed
before the author runs, the author runs once, and the inputs and outputs are hashed. Each blind fault is run on every
seed in every arm, with no change to the checks. A blind fault that crashes the harness is reported as a method failure,
not as a miss.

A fault counts as **caught** by an arm when the arm raises at least one quarantine, hold or review flag in the fault
scenario that it did not raise in the no-fault scenario of the same seed, on a record the fault touched or on a source
and month it touched. **Partly caught**: caught, but the metric error left in months published as final is still more
than half the no-contract error.

## Seeds and intervals

Five seeds (0 to 4), each a new world and a new fault draw. Every figure is reported as the mean of the five, with the
lowest and highest seed. There is no sampling interval in the usual sense: the error is measured against the
generator's own truth. The seed range is the spread a different synthetic world gives.

## Predictions (written before any run)

1. Schema-only contracts leave the same metric error as no contract on every fault except F12.
2. The follow-up rate, which joins clinical, claims and enrollment records, moves at least three times as far under the
   identity faults (F1 to F3) as the LDL control rate, which reads one feed.
3. The consent fault (F11) moves no metric by more than half a point, while the no-contract and schema arms use the
   withdrawn people's records.
4. The semantic arm catches every declared fault at least partly (a self-test, so this is a check of the code, not of
   the method).
5. On the blind faults the semantic arm catches a smaller share than on the declared faults.
6. Without provenance (S10 removed), the drift check misses the one-site wrong-concept fault (F6).

## What would change the conclusion

- If schema-only contracts caught most of the declared faults, the case for semantic checks rests on the blind round
  alone.
- If the blind round showed the semantic checks catching most blind faults, the checks generalise beyond the faults
  they were written for; if they caught few, the page leads with that.
- If the metric errors scale with the fault shares (the sweep), every error on the page is a base-case figure and is
  labelled so.

## Limits

Synthetic people and synthetic feeds; no clinical validity claim for any value, threshold or rate; fixtures shaped after
the public standards, not conformance tested; no claim of employment in healthcare. The study shows a method.
