Week 3 practice
HL7 v2 + patient identity · 44 exercises
The full text of every practice problem that fits week 3, grouped by lecture section. Set up the two sets first: the commands are on the practice problems page. Each reference solution is collapsed under its exercise; run the tests before you open it.
- Anatomy of a message, the carriage-return trap: hl7-practice 01, hl7-practice 02, hl7-practice 04, hl7-practice 05, hl7-practice 06, hl7-practice 07, mellp 08
- Use a parser: mellp 06, mellp 07, mellp 11
- Message types and trigger events: hl7-practice 03, hl7-practice 13, mellp 12
- Getting messages across: MLLP: hl7-practice 10, hl7-practice 11, mellp 01, mellp 02, mellp 03, mellp 04, mellp 05, mellp 15, mellp 16, mellp 17, mellp 20, mellp 21
- Acknowledgments: hl7-practice 08, mellp 09, mellp 10
- Delivery: at least once: mellp 18, mellp 19, mellp 23, mellp 24
- Patient identity: hl7-practice 17
- Building the bridge: mellp 32, mellp 33, mellp 35
- When the FHIR server is down: mellp 36
- Integration engines: hl7-practice 09, mellp 25, mellp 26
- The broken message set: hl7-practice 12, hl7-practice 14, mellp 13, mellp 14
Anatomy of a message, the carriage-return trap
Lecture: Anatomy of a message, the carriage-return trap.
hl7-practice 01: segment_names(message) -> list[str]
Easy
Return the segment names in order. Line endings may be \r, \n, or \r\n. Skip empty lines.
ADT → ['MSH', 'EVN', 'PID', 'NK1', 'NK1', 'PV1']
"" → []
Write it in p01_segment_names.py, then run python3 test_practice.py p01.
Reference solution
def segment_names(message: str) -> list[str]:
return [line.split("|")[0] for line in message.splitlines() if line]
hl7-practice 02: count_segments(message) -> dict[str, int]
Easy
Count how many times each segment appears.
ORU → {'MSH': 1, 'PID': 1, 'OBR': 1, 'OBX': 3, 'NTE': 1}
Write it in p02_count_segments.py, then run python3 test_practice.py p02.
Reference solution
from collections import Counter
from solutions.p01_segment_names import segment_names
def count_segments(message: str) -> dict[str, int]:
return dict(Counter(segment_names(message)))
hl7-practice 04: format_hl7_date(ts) -> str
Easy
HL7 timestamp = YYYY[MM[DD[HH[MM[SS]]]]]; the longer it is, the more precise. Format it for humans, printing only the parts present:
'1990' → '1990'
'199005' → '1990-05'
'19900515' → '1990-05-15'
'2026111109' → '2026-11-11 09'
'202611110930' → '2026-11-11 09:30'
'20261111093045' → '2026-11-11 09:30:45'
'' → ''
Write it in p04_format_date.py, then run python3 test_practice.py p04.
Reference solution
It imports solutions/_hl7.py.
def format_hl7_date(ts: str) -> str:
# (start, end, separator placed before this piece)
pieces = [(0, 4, ""), (4, 6, "-"), (6, 8, "-"), (8, 10, " "), (10, 12, ":"), (12, 14, ":")]
return "".join(sep + ts[start:end] for start, end, sep in pieces if len(ts) >= end)
hl7-practice 05: get_value(message, path) -> str
Medium
Return the value in an HL7 v2 message at the given path.
Path format: SEG-F, SEG-F.C, or SEG-F.C.S
- SEG: 3-letter segment name (MSH, PID, OBX...)
- F: field number (1-based)
- C: component number (1-based), split by ^
- S: subcomponent number (1-based), split by &
Rules:
1. Segments are separated by \r, \n, or \r\n (real files often get their line endings converted).
2. If a segment appears more than once (e.g. several OBX), use the first one.
3. If a field has repeats (~), use the first repeat.
4. MSH is special: MSH-1 = | (the separator itself), MSH-2 = ^~\& (returned as-is, not split). So MSH-n (n ≥ 3) is off by one compared with other segments.
5. Not found (missing segment, field/component/subcomponent out of range, or empty) → return "".
6. Separators are fixed: | ^ ~ \ & (no need to read them from MSH-2 yet).
MSH|^~\&|LAB|HOSP|EMR|HOSP|202611110930||ORU^R01|MSG42|P|2.5.1
PID|1||12345^^^HOSP^MR||NGUYEN&VAN^AN^B||19900515|F|||12 LE LOI^^HUE^^530000^VN||(234)555-0101~(234)555-0202
| path | output |
|---|---|
PID-5.2 |
AN |
PID-5.1.1 |
NGUYEN |
PID-13 |
(234)555-0101 |
MSH-9.2 |
R01 |
PID-4 |
"" |
Follow-up (optional):
- Support a repeat index: PID-13[2] → (234)555-0202.
- Read separators from MSH-2 instead of hardcoding them.
- set_value(message, path, value): that is problem 09.
Write it in p05_get_value.py, then run python3 test_practice.py p05.
Reference solution
def get_value(message: str, path: str) -> str:
seg_name, _, rest = path.partition("-")
field_num, *sub_nums = (int(n) for n in rest.split("."))
for line in message.splitlines(): # handles \r, \n, \r\n
fields = line.split("|")
if fields[0] != seg_name:
continue
if seg_name == "MSH":
if field_num == 1:
return "|"
if field_num == 2:
return fields[1]
index = field_num - 1 # MSH-1 is the separator itself, so everything shifts by one
else:
index = field_num
if index >= len(fields):
return ""
value = fields[index].split("~")[0]
for sep, n in zip("^&", sub_nums):
parts = value.split(sep)
if n > len(parts):
return ""
value = parts[n - 1]
return value
return ""
hl7-practice 06: patient_summary(message) -> dict | None
Medium
Extract patient info from PID. No PID → None.
| key | from | note |
|---|---|---|
mrn |
PID-3.1 |
|
family |
PID-5.1.1 |
surname, without the prefix |
given |
PID-5.2 |
|
dob |
PID-7 |
formatted with problem 04 |
sex |
PID-8 |
|
phones |
PID-13 |
all repeats, as a list; none → [] |
ADT → {'mrn': '12345', 'family': 'NGUYEN', 'given': 'AN', 'dob': '1990-05-15',
'sex': 'F', 'phones': ['(234)555-0101', '(234)555-0202']}
Write it in p06_patient_summary.py, then run python3 test_practice.py p06.
Reference solution
It imports solutions/_hl7.py.
from solutions.p04_format_date import format_hl7_date
def _part(text: str, sep: str, n: int) -> str:
parts = text.split(sep)
return parts[n - 1] if n <= len(parts) else ""
def patient_summary(message: str) -> dict | None:
pid = next((line.split("|") for line in message.splitlines() if line.startswith("PID|")), None)
if pid is None:
return None
field = lambda n: pid[n] if n < len(pid) else ""
return {
"mrn": _part(field(3), "^", 1),
"family": _part(_part(field(5), "^", 1), "&", 1),
"given": _part(field(5), "^", 2),
"dob": format_hl7_date(field(7)),
"sex": field(8),
"phones": [p for p in field(13).split("~") if p],
}
hl7-practice 07: abnormal_results(message) -> list[str]
Medium
Walk every OBX, keep the ones with an abnormal flag (OBX-8 not empty and not N), formatted as:
"<OBX-3.2> <OBX-5> <OBX-6> (<OBX-8>)"
ORU → ['Hemoglobin 11.2 g/dL (L)', 'White Cells 12.8 10*9/L (H)']
ADT → []
Write it in p07_abnormal_results.py, then run python3 test_practice.py p07.
Reference solution
def abnormal_results(message: str) -> list[str]:
results = []
for line in message.splitlines():
obx = line.split("|")
if obx[0] != "OBX":
continue
obx += [""] * (9 - len(obx)) # pad so OBX-3..OBX-8 always exist
flag = obx[8]
if flag in ("", "N"):
continue
name = (obx[3].split("^") + [""])[1]
results.append(f"{name} {obx[5]} {obx[6]} ({flag})")
return results
mellp 08: Peel the Onion
Medium · parsing · delimiters · escapes · stdlib
Libraries hide the HL7 encoding rules until a message arrives that they handle differently from what you expected, and then you need to know what the rules are. This is the one problem where you write the parser by hand: use no HL7 library here, the standard library only. An HL7 message is an onion of five delimiters, and the message itself says which characters they are.
def get(raw: str, path: str) -> str
MSH|^~\&|... declares the delimiters: characters 4 to 8 of the message are the field separator |, then the component separator ^, the repetition separator ~, the escape character \ and the subcomponent separator &. A path has the form SEG[n]-F[r].C.S, numbers 1-based, the bracket and dot parts optional:
SEGis the segment name,[n]the n-th segment with that name (default 1).Fis the field. In MSH, MSH-1 is the field separator character itself and MSH-2 the four encoding characters; return both verbatim.[r]is the repetition (default 1, soPID-3means the first repetition of PID-3),.Cthe component,.Sthe subcomponent.- Read the five delimiters from the message itself. Do not hard-code them.
- Return the text at the level the path names, with deeper delimiters left in place:
PID-5givesDOE^JANE^Q. - Decode escape sequences in the result:
\F\field separator,\S\component separator,\T\subcomponent separator,\R\repetition separator,\E\escape character. Decode in one left-to-right pass, so\E\T\becomes\T\, not&. - Anything absent or empty gives
"".
Example 1:
raw = ("MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ORU^R01^ORU_R01|MSG00003|P|2.5\r"
"PID|1||12345^^^HOSP&1.2.3.4.5&ISO^MR~987654321^^^SSA^SS||JOHNSON\\T\\JOHNSON^PAT\r"
"OBX|1|NM|2345-7^Glucose^LN||182|mg/dL\r"
"OBX|2|NM|2160-0^Creatinine^LN||0.9|mg/dL\r")
get(raw, "PID-3[2].1") -> "987654321"
get(raw, "PID-3.4.1") -> "HOSP"
get(raw, "PID-3") -> "12345^^^HOSP&1.2.3.4.5&ISO^MR"
get(raw, "OBX[2]-5") -> "0.9"
get(raw, "MSH-9.2") -> "R01"
get(raw, "MSH-2") -> "^~\\&"
get(raw, "PID-5.1") -> "JOHNSON&JOHNSON"
get(raw, "OBX[3]-5") -> ""
(The strings are Python literals: "^~\\&" is the four characters ^~\&.)
Example 2:
raw = "MSH#$*!%#EPIC#HOSP#LAB#HOSP#20260105083000##ADT$A01$ADT_A01#MSG00001#P#2.5\rPID#1##12345$$$HOSP$MR##DOE$JANE\r"
get(raw, "MSH-1") -> "#"
get(raw, "MSH-9.2") -> "A01"
get(raw, "PID-5.2") -> "JANE"
Explanation: this sender uses # $ * ! % for field, component, repetition, escape and subcomponent.
Constraints:
- The message starts with
MSH, segments end with\r, and the five delimiter characters are all different. - Paths are always well-formed, segment names are three characters, and every number is at least 1.
- MSH-1 and MSH-2 are only asked for as a whole field (no repetition, component or subcomponent).
- The only escape sequences in the tests are the five listed above.
Follow-up: HL7 defines more escape sequences than these five, for example \.br\ for a line break in formatted text and \Xhh\ for hexadecimal data. Where in an interface should those be decoded, and where must they pass through unchanged?
Hint 1
Split from the outside in: segments, then fields, repetitions, components, subcomponents. Decode escapes last, on the final string. A decoded \F\ is a | and must never be split on.
Hint 2
Chained str.replace calls decode \E\T\ wrongly in either order. re.sub with a function as the replacement scans left to right and never rescans what it has replaced.
Write it in problems/08-peel-the-onion/solution.py, then run:
uv run pytest problems/08-*
Reference solution
import re
PATH = re.compile(r"([A-Z][A-Z0-9]{2})(?:\[(\d+)\])?-(\d+)(?:\[(\d+)\])?(?:\.(\d+))?(?:\.(\d+))?")
def get(raw: str, path: str) -> str:
name, occurrence, field, repetition, component, subcomponent = PATH.fullmatch(path).groups()
field_separator = raw[3]
component_separator, repetition_separator, escape, subcomponent_separator = raw[4:8]
matching = [segment for segment in raw.split("\r") if segment[:3] == name]
fields = nth(matching, occurrence).split(field_separator)
if name == "MSH":
fields.insert(1, field_separator) # MSH-1 is the separator itself
if int(field) <= 2:
return fields[int(field)]
value = nth(fields[1:], field)
value = nth(value.split(repetition_separator), repetition)
if component:
value = nth(value.split(component_separator), component)
if subcomponent:
value = nth(value.split(subcomponent_separator), subcomponent)
decoded = {
"F": field_separator,
"S": component_separator,
"T": subcomponent_separator,
"R": repetition_separator,
"E": escape,
}
sequence = re.escape(escape) + "([FSTRE])" + re.escape(escape)
return re.sub(sequence, lambda match: decoded[match.group(1)], value)
def nth(parts: list[str], number: str | None) -> str:
"""The part at a 1-based position (1 when not given), or "" past the end."""
index = int(number or 1) - 1
return parts[index] if index < len(parts) else ""
Use a parser
Lecture: Use a parser.
mellp 06: Read the Header
Easy · parsing · msh · python-hl7
Every routing decision an interface makes starts in the MSH segment: who sent the message, who it is for, what kind of message it is, which version of the standard it follows and whether it is production traffic. Read those values once into a plain dict and the rest of your code never touches the raw text. The catch is MSH-1. The | right after MSH is not a separator in front of field 1, it is field 1, so every MSH field number is one higher than its position in raw.split("|").
def header(raw: str) -> dict[str, str]
Return a dict with exactly these ten keys:
| Key | Field |
|---|---|
sending_app |
MSH-3 |
sending_facility |
MSH-4 |
receiving_app |
MSH-5 |
receiving_facility |
MSH-6 |
timestamp |
MSH-7, as written |
type |
MSH-9.1 |
trigger |
MSH-9.2 |
control_id |
MSH-10 |
processing_id |
MSH-11 |
version |
MSH-12 |
Segments may end with \r (as on the wire), \n or \r\n (a message saved to a file by an editor). All three must work.
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
Output: {"sending_app": "EPIC", "sending_facility": "HOSP", "receiving_app": "LAB",
"receiving_facility": "HOSP", "timestamp": "20260105083000", "type": "ADT",
"trigger": "A01", "control_id": "MSG00001", "processing_id": "P", "version": "2.5"}
Explanation: raw.split("|")[9] is "MSG00001". That is MSH-10, not MSH-9.
Example 2:
Input: the same message with "\n" after every segment instead of "\r"
Output: the same dict
Constraints:
- The first segment is MSH and the message uses the default delimiters
|^~\&. - MSH-3 through MSH-12 are present and non-empty. MSH-9 has at least two components.
- MSH-3 to MSH-7 and MSH-10 to MSH-12 hold a single value with no components.
- One message uses one kind of line ending throughout.
Follow-up: MSH-3 is an HD (hierarchic designator) with up to three components: namespace ID, universal ID and universal ID type. When a sender fills all three, what should sending_app contain, and what would you route on?
Hint 1
python-hl7 numbers MSH fields the HL7 way, so the off-by-one is handled for you:
msg = hl7.parse(raw)
msg["MSH.F10"] # "MSG00001"
msg["MSH.F9.R1.C2"] # "A01"
The hl7apy equivalent of the second line is parse_message(raw).msh.msh_9.msh_9_2.value.
Hint 2
python-hl7 splits segments on \r only. Given \n line endings it sees one long MSH segment, and msg["MSH.F12"] comes back as "2.5\nEVN". Normalise the line endings before parsing.
Write it in problems/06-read-the-header/solution.py, then run:
uv run pytest problems/06-*
Reference solution
import hl7
def header(raw: str) -> dict[str, str]:
# python-hl7 splits segments on \r only, so normalise editor line endings first.
message = hl7.parse(raw.replace("\r\n", "\r").replace("\n", "\r"))
return {
"sending_app": message["MSH.F3"],
"sending_facility": message["MSH.F4"],
"receiving_app": message["MSH.F5"],
"receiving_facility": message["MSH.F6"],
"timestamp": message["MSH.F7"],
"type": message["MSH.F9.R1.C1"],
"trigger": message["MSH.F9.R1.C2"],
"control_id": message["MSH.F10"],
"processing_id": message["MSH.F11"],
"version": message["MSH.F12"],
}
mellp 07: Find the Patient
Easy · parsing · pid · python-hl7
Nearly every inbound message has to be matched to a patient before anything else happens, and the PID segment is where the identity lives: the medical record number in PID-3, the name in PID-5, birth date in PID-7, administrative sex in PID-8. HL7 writes dates as 19800214, while most systems downstream (a FHIR server, a JSON API, a database column) want 1980-02-14. Pull out the five values in the shape the next system expects.
def patient(raw: str) -> dict
Return a dict with exactly these keys:
mrn: PID-3.1 of the first repetition of PID-3family: PID-5.1given: PID-5.2dob:"YYYY-MM-DD"built from the first 8 digits of PID-7, orNonewhen PID-7 is empty. PID-7 may carry a time after the date (198002141230); ignore it.sex: PID-8, orNonewhen it is empty
Raise ValueError when the message has no PID segment.
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
"PV1|1|I|ICU^101^A\r"
Output: {"mrn": "12345", "family": "DOE", "given": "JANE", "dob": "1980-02-14", "sex": "F"}
Example 2:
Input: "MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20260105083000||ORU^R01^ORU_R01|MSG00003|P|2.5\r"
"PID|1||12345^^^HOSP^MR~987654321^^^SSA^SS||DOE^JANE||198002141230|\r"
"OBR|1|ORD448^EPIC|LAB7731^LAB|24323-8^Comprehensive metabolic panel^LN\r"
Output: {"mrn": "12345", "family": "DOE", "given": "JANE", "dob": "1980-02-14", "sex": None}
Explanation: PID-3 has two repetitions and the first is the MRN. PID-7 carries a time.
PID-8 is empty. PID is the second segment here, not the third.
Example 3:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
Output: raises ValueError
Constraints:
- Segments end with
\rand the message uses the default delimiters|^~\&. - There is at most one PID segment, and it can be anywhere after MSH.
- PID-5, when the PID is there, has at least two components (family and given).
- PID-7 is either empty or starts with 8 digits
YYYYMMDD.
Follow-up: the MRN is not always the first repetition of PID-3. Other identifiers, such as a social security number, can come first, and PID-3.5 (identifier type code, MR for medical record number, SS for social security number) says which is which. How would you pick the right one? Problem 08 builds the tool.
Hint
msg = hl7.parse(raw)
msg["PID.F3.R1.C1"] # "12345": field 3, repetition 1, component 1
msg["PID.F8"] # "" when PID-8 is empty
When there is no PID at all, the same lookup raises KeyError, not ValueError.
Write it in problems/07-find-the-patient/solution.py, then run:
uv run pytest problems/07-*
Reference solution
import hl7
def patient(raw: str) -> dict:
message = hl7.parse(raw)
try:
birth = message["PID.F7"]
except KeyError: # python-hl7 raises KeyError for a segment that is not there
raise ValueError("message has no PID segment") from None
sex = message["PID.F8"]
return {
"mrn": message["PID.F3.R1.C1"],
"family": message["PID.F5.R1.C1"],
"given": message["PID.F5.R1.C2"],
"dob": f"{birth[:4]}-{birth[4:6]}-{birth[6:8]}" if birth else None,
"sex": sex or None,
}
mellp 11: Lab Results
Easy · parsing · oru · obx · python-hl7
A lab result arrives as an ORU^R01: an OBR for the ordered test, then one OBX per observation. OBX-2 names the value type, and it matters: NM (numeric) values get charted, trended and compared against ranges, so they have to become numbers, while ST (string) values stay text. Turn the OBX segments into a list of plain dicts.
def observations(raw: str) -> list[dict]
Return one dict per OBX segment, in message order:
code: OBX-3.1 (the observation identifier, here a LOINC code)name: OBX-3.2value:float(OBX-5)when OBX-2 isNM, otherwise OBX-5 as a stringunits: OBX-6.1, orNonewhen emptyflag: OBX-8 (abnormal flag), orNonewhen emptystatus: OBX-11 (result status)
A message with no OBX gives [].
Example 1:
Input: "MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20260105083000||ORU^R01^ORU_R01|MSG00003|P|2.5\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
"OBR|1|ORD448^EPIC|LAB7731^LAB|24323-8^Comprehensive metabolic panel^LN\r"
"OBX|1|NM|2345-7^Glucose^LN||182|mg/dL|70-99|H|||F\r"
"OBX|2|ST|5778-6^Color of Urine^LN||YELLOW||||||F\r"
Output: [{"code": "2345-7", "name": "Glucose", "value": 182.0, "units": "mg/dL",
"flag": "H", "status": "F"},
{"code": "5778-6", "name": "Color of Urine", "value": "YELLOW", "units": None,
"flag": None, "status": "F"}]
Example 2:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
Output: []
Constraints:
- Segments end with
\rand the message uses the default delimiters|^~\&. - Every OBX has fields through OBX-11, and OBX-3 has at least two components.
- When OBX-2 is
NM, OBX-5 is a plain decimal number such as182,0.9or-1.5. - OBX-5, OBX-8 and OBX-11 hold a single value with no components or repetitions.
Follow-up: labs report values such as <0.5 or >1000, which no float can hold. HL7 has the SN (structured numeric) data type for them, with a comparator component. How would you represent those values in your dict without losing the comparator?
Hint
python-hl7 accessor keys take a segment number: msg["OBX2.F5"] is OBX-5 of the second OBX, and msg["OBX2.F6.R1.C1"] returns "" when OBX-6 is empty. msg.segments("OBX") raises KeyError when there are none.
Write it in problems/11-lab-results/solution.py, then run:
uv run pytest problems/11-*
Reference solution
import hl7
def observations(raw: str) -> list[dict]:
message = hl7.parse(raw)
# message.segments("OBX") raises KeyError when there are none, so count them instead.
count = sum(1 for segment in message if str(segment[0]) == "OBX")
return [observation(message, f"OBX{number}") for number in range(1, count + 1)]
def observation(message: hl7.Message, obx: str) -> dict:
"""One OBX, addressed as "OBX1", "OBX2", ... in python-hl7 accessor keys."""
value = message[f"{obx}.F5"]
return {
"code": message[f"{obx}.F3.R1.C1"],
"name": message[f"{obx}.F3.R1.C2"],
"value": float(value) if message[f"{obx}.F2"] == "NM" else value,
"units": message[f"{obx}.F6.R1.C1"] or None,
"flag": message[f"{obx}.F8"] or None,
"status": message[f"{obx}.F11"],
}
Message types and trigger events
Lecture: Message types and trigger events.
hl7-practice 03: message_type(message) -> tuple[str, str]
Easy
Return (MSH-9.1, MSH-9.2). No event → event = "". Ignore MSH-9.3.
ADT (MSH-9 = ADT^A04^ADT_A01) → ('ADT', 'A04')
ORU (MSH-9 = ORU^R01) → ('ORU', 'R01')
MSH-9 = ACK → ('ACK', '')
Write it in p03_message_type.py, then run python3 test_practice.py p03.
Reference solution
def message_type(message: str) -> tuple[str, str]:
msh = message.splitlines()[0].split("|")
msh_9 = msh[8] # MSH-1 is the '|' itself, so MSH-n sits at index n-1
code, event = (msh_9.split("^") + [""])[:2]
return code, event
hl7-practice 13: ADT router
Easy
INT-102: Transport/billing only need to know what to do, not how to read HL7. Map ADT event → action.
adt_action(message: str) -> str
MSH-9 |
return |
|---|---|
ADT^A01 |
OPEN_ENCOUNTER |
ADT^A02 |
MOVE_PATIENT |
ADT^A03 |
CLOSE_ENCOUNTER |
ADT^A04 |
OPEN_OUTPATIENT |
ADT^A08 |
UPDATE_PATIENT |
ADT^A11 |
CANCEL_ADMIT |
ADT^A31 |
UPDATE_PERSON |
| other ADT event | IGNORE |
| not ADT | NOT_ADT |
Trap: ADT^A04^ADT_A01 is A04, not A01.
Write it in p13_adt_router.py, then run python3 test_practice.py p13.
Reference solution
It imports solutions/_hl7.py.
from solutions._hl7 import field, first, part
ACTIONS = {
"A01": "OPEN_ENCOUNTER", "A02": "MOVE_PATIENT", "A03": "CLOSE_ENCOUNTER", "A04": "OPEN_OUTPATIENT",
"A08": "UPDATE_PATIENT", "A11": "CANCEL_ADMIT", "A31": "UPDATE_PERSON",
}
def adt_action(message: str) -> str:
msh_9 = field(first(message, "MSH"), 9)
if part(msh_9, "^", 1) != "ADT":
return "NOT_ADT"
return ACTIONS.get(part(msh_9, "^", 2), "IGNORE")
mellp 12: Four Message Types
Medium · adt · oru · orm · python-hl7
A typical first interface handles a handful of message types and has to tell them apart before doing anything else. MSH-9 says what a message is; the segments that matter differ by type. These four cover a lot of hospital traffic:
| MSH-9 | What it means | Key segments |
|---|---|---|
ADT^A01 |
admit a patient | PID, PV1 (patient visit) |
ADT^A08 |
update patient information | PID |
ORU^R01 |
observation results, such as lab values | PID, OBR (the test), OBX (one per result) |
ORM^O01 |
an order | PID, ORC (order control), OBR (the test ordered) |
class UnsupportedMessage(ValueError): ...
def summarize(raw: str) -> dict
Dispatch on MSH-9.1 and MSH-9.2. Every summary has "event", "mrn" (PID-3.1) and "name" ("DOE, JANE", from PID-5.1 and PID-5.2), plus:
ADT^A01: event"admit","class"PV1-2 (patient class),"location"PV1-3.1, PV1-3.2 and PV1-3.3 (point of care, room, bed) joined with-, empty parts skipped:"ICU-101-A"ADT^A08: event"update", nothing extraORU^R01: event"result","order"OBR-3.1 (filler order number),"test"OBR-4.2,"results"the number of OBX segments,"abnormal"the list of OBX-3.1 of every OBX whose OBX-8 (abnormal flag) is neither empty norN, in message orderORM^O01: event"order","control"ORC-1 (order control, such asNWnew orCAcancel),"order"ORC-2.1 (placer order number),"test"OBR-4.2- anything else: raise
UnsupportedMessagewith the message type ("ADT^A04") in its message
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
"PV1|1|I|ICU^101^A||||1234^WELBY^MARCUS\r"
Output: {"event": "admit", "mrn": "12345", "name": "DOE, JANE", "class": "I", "location": "ICU-101-A"}
Example 2:
Input: "MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20260105083000||ORU^R01^ORU_R01|MSG00003|P|2.5\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
"OBR|1|ORD448^EPIC|LAB7731^LAB|24323-8^Comprehensive metabolic panel^LN\r"
"OBX|1|NM|2345-7^Glucose^LN||182|mg/dL|70-99|H|||F\r"
"OBX|2|NM|2160-0^Creatinine^LN||0.9|mg/dL|0.6-1.2|N|||F\r"
"OBX|3|ST|5778-6^Color of Urine^LN||YELLOW||||||F\r"
Output: {"event": "result", "mrn": "12345", "name": "DOE, JANE", "order": "LAB7731",
"test": "Comprehensive metabolic panel", "results": 3, "abnormal": ["2345-7"]}
Example 3:
Input: a message whose MSH-9 is ADT^A04^ADT_A01
Output: raises UnsupportedMessage("unsupported message type: ADT^A04")
Constraints:
- Segments end with
\rand the message uses the default delimiters|^~\&. - Every supported message has a PID whose PID-5 has a family and a given name.
- PV1, OBR and ORC appear once in the messages that use them, and every
ORU^R01has at least one OBX. - Fields named above are present; any of them may be empty.
Follow-up: ADT^A08 uses the same segment structure as ADT^A01 (MSH-9.3 is ADT_A01 for both). What goes wrong if you dispatch on MSH-9.3 instead of MSH-9.1 and MSH-9.2?
Hint
msg["OBX2.F8"] reads OBX-8 of the second OBX. For the count, len(msg.segments("OBX")) works when there is at least one.
Write it in problems/12-four-message-types/solution.py, then run:
uv run pytest problems/12-*
Reference solution
import hl7
class UnsupportedMessage(ValueError):
pass
def summarize(raw: str) -> dict:
message = hl7.parse(raw)
message_type = f"{message['MSH.F9.R1.C1']}^{message['MSH.F9.R1.C2']}"
summary = {
"mrn": message["PID.F3.R1.C1"],
"name": f"{message['PID.F5.R1.C1']}, {message['PID.F5.R1.C2']}",
}
if message_type == "ADT^A01":
parts = [message[f"PV1.F3.R1.C{number}"] for number in (1, 2, 3)]
summary["event"] = "admit"
summary["class"] = message["PV1.F2"]
summary["location"] = "-".join(part for part in parts if part)
elif message_type == "ADT^A08":
summary["event"] = "update"
elif message_type == "ORU^R01":
summary["event"] = "result"
summary["order"] = message["OBR.F3.R1.C1"]
summary["test"] = message["OBR.F4.R1.C2"]
summary["results"] = len(message.segments("OBX"))
summary["abnormal"] = abnormal_codes(message, summary["results"])
elif message_type == "ORM^O01":
summary["event"] = "order"
summary["control"] = message["ORC.F1"]
summary["order"] = message["ORC.F2.R1.C1"]
summary["test"] = message["OBR.F4.R1.C2"]
else:
raise UnsupportedMessage(f"unsupported message type: {message_type}")
return summary
def abnormal_codes(message: hl7.Message, count: int) -> list[str]:
"""OBX-3.1 of every OBX whose OBX-8 flag is set to anything but N (normal)."""
codes = []
for number in range(1, count + 1):
if message[f"OBX{number}.F8"] not in ("", "N"):
codes.append(message[f"OBX{number}.F3.R1.C1"])
return codes
Getting messages across: MLLP
Lecture: Getting messages across: MLLP.
hl7-practice 10: MLLP wrap / unwrap
Easy
INT-101: A new lab sends over MLLP. Write 2 helpers to wrap/unwrap a frame.
wrap(message: str) -> bytes:0x0B+ message (ASCII) +0x1C 0x0D.unwrap(frame: bytes) -> str: the reverse. Frame doesn't start with0x0Bor doesn't end with0x1C 0x0D→raise ValueError.
wrap("MSH|...\rPID|...") → b"\x0bMSH|...\rPID|...\x1c\r"
Note: the \r between segments is not the end of the frame.
Write it in p10_mllp.py, then run python3 test_practice.py p10.
Reference solution
START, END = b"\x0b", b"\x1c\x0d"
def wrap(message: str) -> bytes:
return START + message.encode("ascii") + END
def unwrap(frame: bytes) -> str:
if not (frame.startswith(START) and frame.endswith(END)):
raise ValueError("not an MLLP frame")
return frame[len(START):-len(END)].decode("ascii")
hl7-practice 11: MLLP stream reader
Hard
INT-301: TCP doesn't guarantee 1 recv() = 1 message. Write a reader that survives any kind of split.
class MllpReader:
def feed(self, chunk: bytes) -> list[str]: ...
- Each
feedreturns the complete messages just finished (could be 0, 1, or many). - Partial data is kept for the next chunk — even when
0x1Cand0x0Dland in 2 different chunks. - Garbage bytes before
0x0B→ dropped.
Write it in p11_mllp_reader.py, then run python3 test_practice.py p11.
Reference solution
START, END = b"\x0b", b"\x1c\x0d"
class MllpReader:
def __init__(self):
self.buffer = bytearray()
def feed(self, chunk: bytes) -> list[str]:
self.buffer += chunk
messages = []
while True:
start = self.buffer.find(START)
if start == -1:
self.buffer.clear() # no frame started: everything is noise
break
del self.buffer[:start]
end = self.buffer.find(END)
if end == -1:
break # incomplete frame, wait for more bytes
messages.append(self.buffer[1:end].decode("ascii"))
del self.buffer[:end + len(END)]
return messages
mellp 01: Wrap It
Easy · framing · stdlib
TCP delivers a stream of bytes with no message boundaries. MLLP (Minimal Lower Layer Protocol) adds them by putting every HL7 message inside a block:
<SB> payload <EB><CR>
0x0B ... 0x1C 0x0D
SB is the start-of-block byte (ASCII vertical tab), EB the end-of-block byte (ASCII file separator), and a carriage return closes the block. The payload is the HL7 message itself, segments and their \r terminators included.
Implement both directions:
def frame(payload: bytes) -> bytes
def unframe(block: bytes) -> bytes
framewrapspayloadin one block.unframetakes exactly one block and returns its payload.- A payload may not contain
0x0Bor0x1C. Both functions raiseValueErrorfor one that does. unframeraisesValueErrorfor anything that is not exactly one block: missingSB, missingEBorCR, or bytes before or after the block.
Example 1:
Input: frame(b"MSH|^~\\&|EPIC\r")
Output: b"\x0bMSH|^~\\&|EPIC\r\x1c\r"
Example 2:
Input: unframe(b"\x0bMSH|^~\\&|EPIC\r\x1c\r")
Output: b"MSH|^~\\&|EPIC\r"
Explanation: the \r before \x1c is the last segment's terminator and belongs to the payload.
Example 3:
Input: unframe(b"\x0bMSH|^~\\&|EPIC\r\x1c\r\n")
Output: ValueError
Explanation: a trailing newline is not part of the block.
Constraints:
0 <= len(payload) <= 10**6- An empty payload is legal:
frame(b"") == b"\x0b\x1c\r". - Work with
bytes. Do not decode.
Follow-up: some senders really do append \n after the block, and some payloads arrive without the final segment terminator. Which of the two would you tolerate in a receiver, and where?
Hint
bytes.startswith, bytes.endswith and slicing are enough. Remember the end marker is two bytes.
Write it in problems/01-wrap-it/solution.py, then run:
uv run pytest problems/01-*
Reference solution
SB = b"\x0b"
EB = b"\x1c\x0d"
def _checked(payload: bytes) -> bytes:
if SB in payload or b"\x1c" in payload:
raise ValueError("payload contains an MLLP marker byte")
return payload
def frame(payload: bytes) -> bytes:
return SB + _checked(payload) + EB
def unframe(block: bytes) -> bytes:
if not (block.startswith(SB) and block.endswith(EB)):
raise ValueError("not a single MLLP block")
return _checked(block[1:-2])
mellp 02: Several in One Send
Easy · framing · stdlib
One recv() does not return one message. A busy sender, or the kernel on its own, will hand you several blocks glued together, and the last one is often cut off because the rest has not arrived yet.
Given everything read so far, split it into the payloads of the complete blocks and the bytes that are still waiting for their ending:
def split_blocks(buffer: bytes) -> tuple[list[bytes], bytes]
- The list holds the payload of every complete block, in order.
- The second value is the unconsumed remainder: empty, or the beginning of an incomplete block (its
SBincluded).
Example 1:
Input: b"\x0bADT-1\x1c\r\x0bADT-2\x1c\r"
Output: ([b"ADT-1", b"ADT-2"], b"")
Example 2:
Input: b"\x0bADT-1\x1c\r\x0bADT"
Output: ([b"ADT-1"], b"\x0bADT")
Explanation: the second block has started but its end marker has not arrived.
Example 3:
Input: b"\x0bADT-1\x1c"
Output: ([], b"\x0bADT-1\x1c")
Explanation: 0x1C alone does not end a block. The carriage return may be in the next packet.
Constraints:
0 <= len(buffer) <= 10**6bufferstarts at a block boundary and there are no stray bytes between blocks.- Payloads never contain
0x0Bor0x1C. They do contain\r. - Remainder plus the next bytes from the network must be a valid input to the same function.
Follow-up: your solution is probably O(n²) in the number of blocks if it re-slices the buffer after each one. Does that matter for a 64 KB read? For a 1 GB replay file?
Hint
Search for the two-byte end marker, not for 0x1C. bytes.find returns -1 when there is no more.
Write it in problems/02-several-in-one-send/solution.py, then run:
uv run pytest problems/02-*
Reference solution
SB = b"\x0b"
EB = b"\x1c\x0d"
def split_blocks(buffer: bytes) -> tuple[list[bytes], bytes]:
payloads = []
while (end := buffer.find(EB)) != -1:
payloads.append(buffer[1:end])
buffer = buffer[end + len(EB) :]
return payloads, buffer
mellp 03: Split Across Sends
Easy · framing · stdlib
The opposite of the previous problem: one message spread over several reads. A 4 KB message can arrive as 1,460 bytes, then 1,460, then the rest. A slow link can deliver it one byte at a time. The cut can land anywhere, including between 0x1C and the carriage return.
A receiver therefore needs memory between reads. Build it:
class Deframer:
def feed(self, chunk: bytes) -> list[bytes]
feed takes whatever the network just delivered and returns the payloads of the blocks that this chunk completed, in order. Usually that is an empty list or a single payload. Bytes of a block that is still incomplete are kept for the next call.
Example 1:
d = Deframer()
d.feed(b"\x0bMSH|^~\\&|EP") -> []
d.feed(b"IC\r\x1c") -> []
d.feed(b"\r") -> [b"MSH|^~\\&|EPIC\r"]
Example 2:
d = Deframer()
d.feed(b"\x0bA\x1c\r\x0bB\x1c\r\x0bC") -> [b"A", b"B"]
d.feed(b"\x1c\r") -> [b"C"]
Constraints:
- The concatenation of all chunks is a sequence of well-formed blocks with nothing between them.
- A chunk may be empty and may be a single byte.
- Payloads never contain
0x0Bor0x1C. - Each
Deframerinstance serves one connection. Two instances must not share state.
Follow-up: what should happen to the kept bytes when the connection closes? Problem 05 answers it.
Hint
Keep one buffer on the instance, append the chunk to it, then run the logic from problem 02 and keep its remainder.
Write it in problems/03-split-across-sends/solution.py, then run:
uv run pytest problems/03-*
Reference solution
SB = b"\x0b"
EB = b"\x1c\x0d"
class Deframer:
def __init__(self) -> None:
self._buffer = b""
def feed(self, chunk: bytes) -> list[bytes]:
self._buffer += chunk
payloads = []
while (end := self._buffer.find(EB)) != -1:
payloads.append(self._buffer[1:end])
self._buffer = self._buffer[end + len(EB) :]
return payloads
mellp 04: Noisy Line
Medium · framing · resync · stdlib
Real peers are not as tidy as problem 03 assumed. Some append \n after every block. Some die halfway through a message and start a new one. A misconfigured one sends an endless block that would eat all your memory. A receiver that survives a production feed needs rules for all three.
class Deframer:
discarded: int
def __init__(self, max_size: int = 1_048_576) -> None
def feed(self, chunk: bytes) -> list[bytes]
feed returns the payloads of the blocks completed by this chunk, as in problem 03, with these additions:
- Noise outside a block is dropped. Bytes before the first
SB, and bytes between an end marker and the nextSB, are thrown away. - A new
SBrestarts the block. IfSBarrives while a block is open, the open block was abandoned by its sender: throw it away and begin a new block at thisSB. - Oversized blocks are dropped. A block whose payload is longer than
max_sizebytes is never returned. As soon as an open block is known to exceed the limit, stop buffering it and treat what follows as noise until the nextSB. discardedcounts every dropped byte, marker bytes of dropped blocks included.
Example 1:
d = Deframer()
d.feed(b"\x0bA\x1c\r\r\n\x0bB\x1c\r") -> [b"A", b"B"]
d.discarded -> 2
Explanation: the sender puts CR LF after each block.
Example 2:
d = Deframer()
d.feed(b"\x0bMSH|half a mess") -> []
d.feed(b"\x0bMSH|whole\r\x1c\r") -> [b"MSH|whole\r"]
d.discarded -> 16
Explanation: the first block (SB plus 15 payload bytes) was abandoned when the second SB arrived.
Example 3:
d = Deframer(max_size=4)
d.feed(b"\x0bABCDE\x1c\r\x0bOK\x1c\r") -> [b"OK"]
d.discarded -> 8
Explanation: a 5-byte payload exceeds max_size=4. All 8 bytes of that block are dropped.
Constraints:
- Chunks are cut anywhere, as in problem 03.
- Payloads of well-formed blocks never contain
0x0Bor0x1C. - A payload of exactly
max_sizebytes is accepted. - Memory stays bounded: never hold more than about
max_sizebytes plus one chunk, no matter how long an unterminated block runs. - Accounting is exact. At any moment: bytes fed = bytes of returned blocks (payload + 3 each) +
discarded+ bytes still buffered.
Follow-up: rule 2 silently loses a message. What would you log, and would you rather close the connection? What does your interface engine do?
Hint 1
Two states are enough: outside a block and inside one. Outside, look for SB. Inside, look for whichever comes first: the end marker or another SB.
Hint 2
For the size limit, mind the block whose payload is exactly max_size and whose 0x1C has arrived but whose \r has not.
Write it in problems/04-noisy-line/solution.py, then run:
uv run pytest problems/04-*
Reference solution
SB = b"\x0b"
EB = b"\x1c\x0d"
class Deframer:
def __init__(self, max_size: int = 1_048_576) -> None:
self.max_size = max_size
self.discarded = 0
self._buffer = bytearray() # empty, or starts with the SB of the open block
def feed(self, chunk: bytes) -> list[bytes]:
self._buffer += chunk
payloads = []
while self._buffer:
if self._buffer[0] != SB[0]: # outside a block: drop noise up to the next SB
self._drop(self._buffer.find(SB))
continue
end = self._buffer.find(EB, 1)
restart = self._buffer.find(SB, 1)
if restart != -1 and (end == -1 or restart < end): # abandoned by its sender
self._drop(restart)
elif end == -1:
# Still open. One extra byte of slack: a trailing 0x1C may be half an end marker.
if len(self._buffer) - 1 > self.max_size + 1:
self._drop(-1)
break
elif end - 1 > self.max_size:
self._drop(end + len(EB))
else:
payloads.append(bytes(self._buffer[1:end]))
del self._buffer[: end + len(EB)]
return payloads
def _drop(self, count: int) -> None:
"""Discards the first `count` buffered bytes; -1 discards them all."""
if count == -1:
count = len(self._buffer)
self.discarded += count
del self._buffer[:count]
mellp 05: Hung Up Mid-Message
Easy · framing · sockets · stdlib
Time for a real socket. A peer connects, sends some messages, and closes. Sometimes it closes cleanly after its last block. Sometimes the process is killed, the VPN drops, or a firewall times out, and the connection ends with half a message in flight. The half must never be mistaken for a message.
def receive(conn: socket.socket) -> tuple[list[bytes], bytes]
Read from the connected socket conn until the peer closes it. Return:
- the payloads of all complete blocks, in order, and
- the bytes of the incomplete block that was cut off (its
SBincluded), orb""after a clean close.
recv() returning b"" means the peer closed its side. Do not close conn yourself: the caller owns it.
Example 1:
Peer sends: b"\x0bADT-1\x1c\r\x0bADT-2\x1c\r" then closes
Output: ([b"ADT-1", b"ADT-2"], b"")
Example 2:
Peer sends: b"\x0bADT-1\x1c\r\x0bADT-" then closes
Output: ([b"ADT-1"], b"\x0bADT-")
Explanation: the second message never finished. Report it, do not process it.
Constraints:
- The peer may deliver the bytes in pieces of any size, with pauses in between.
- A single message can be larger than one
recv()buffer (tests go up to 1 MB). - There are no stray bytes between blocks.
connis in blocking mode with no timeout.
Follow-up: this function only returns when the peer hangs up, which is useless for a connection that stays open all day. Turn it into a generator that yields each payload the moment it is complete. Problem 15 onward needs exactly that.
Hint
Loop on conn.recv(65536) until it returns b"". Everything you learned in problems 02 and 03 applies to what you collected.
Write it in problems/05-hung-up-mid-message/solution.py, then run:
uv run pytest problems/05-*
Reference solution
import socket
SB = b"\x0b"
EB = b"\x1c\x0d"
def receive(conn: socket.socket) -> tuple[list[bytes], bytes]:
buffer = b""
while chunk := conn.recv(65536):
buffer += chunk
payloads = []
while (end := buffer.find(EB)) != -1:
payloads.append(buffer[1:end])
buffer = buffer[end + len(EB) :]
return payloads, buffer
mellp 15: Answer One Call
Easy · sockets · server · stdlib
So far the bytes were handed to you. Now you are the receiving system: a sender connects to your port, sends a message, and waits for the acknowledgment before it does anything else. The smallest useful receiver answers exactly one such call. Everything a long-running listener does later is this, in a loop.
def serve_once(listener: socket.socket, handler: Callable[[bytes], bytes]) -> None
listener is already bound and listening.
- Accept one connection.
- Read exactly one block from it. It may arrive in pieces.
- Call
handler(payload)once with the block's payload and send the returned payload back as one block. - Close the connection and return. Leave
listeneropen: the caller will use it again.
Example 1:
Input: a client sends b"\x0bMSH|...|MSG00001|P|2.5\r...\x1c\r"
handler = lambda payload: b"MSH|...\rMSA|AA|MSG00001\r"
Output: the client receives b"\x0bMSH|...\rMSA|AA|MSG00001\r\x1c\r", then the connection closes
Example 2:
Input: the same block, delivered as 300 one-byte writes
Output: the same reply. The handler is called once, with the whole payload.
Constraints:
- The client sends one complete, well-formed block and nothing else, then waits for the reply.
- Payloads never contain
0x0Bor0x1C. handlerreturns the reply payload, unframed, and never raises.
Follow-up: while handler runs, a second sender can still connect (the operating system completes the connection and queues it in the listen backlog), but nobody reads its message. How long can a slow handler make it wait, and what does that do to a sender with a 5-second timeout?
Hint
conn, address = listener.accept(). Use the connection in a with block so it is closed on every path, and keep calling conn.recv(65536) until the end marker 0x1C 0x0D is in what you collected.
Write it in problems/15-answer-one-call/solution.py, then run:
uv run pytest problems/15-*
Reference solution
import socket
from collections.abc import Callable
SB = b"\x0b"
EB = b"\x1c\x0d"
def serve_once(listener: socket.socket, handler: Callable[[bytes], bytes]) -> None:
conn, _ = listener.accept()
with conn:
buffer = b""
while EB not in buffer:
chunk = conn.recv(65536)
if not chunk:
return # the caller hung up before finishing its message
buffer += chunk
payload = buffer[buffer.find(SB) + 1 : buffer.find(EB)]
conn.sendall(SB + handler(payload) + EB)
mellp 16: Send and Wait
Easy · sockets · client · timeout · stdlib
Now the other side of the call. Your system has a message for the lab and must know whether the lab accepted it. Sending is the easy part. The work is in everything that can happen while you wait: the lab answers, the lab says nothing, the lab hangs up, or the lab hangs up halfway through its answer.
def send(host: str, port: int, payload: bytes, timeout: float = 5.0) -> bytes
Connect, send payload as one block, wait for one reply block, and return its payload.
- If the server sends nothing for
timeoutseconds while you wait, raiseTimeoutError. - If the server closes the connection before a complete reply block arrived (no reply at all, or only part of one), raise
ConnectionError. - A refused connection raises
ConnectionRefusedError, which is already a subclass ofConnectionError. Let it propagate. - The socket is closed on every path, success and failure alike.
An AE or AR acknowledgment is still a reply: return it. Deciding what to do with it is problem 18.
python-hl7 ships a client, hl7.client.MLLPClient. In version 0.4.5 its constructor takes only host, port and encoding, so there is no way to give it a timeout, and its send returns whatever a single recv() delivers. That is why this one is written by hand.
Example 1:
Input: send("127.0.0.1", 2575, adt) the server replies with an AA
Output: b"MSH|^~\\&|LAB|HOSP|EPIC|HOSP|...\rMSA|AA|MSG00001\r"
Example 2:
Input: send("127.0.0.1", 2575, adt, timeout=0.2) the server reads the message and says nothing
Output: TimeoutError, about 0.2 s later
Example 3:
Input: send("127.0.0.1", 2575, adt) the server sends half an ACK, then closes
Output: ConnectionError
Explanation: half an acknowledgment is not an acknowledgment.
Constraints:
- The reply may arrive in pieces, down to one byte per read.
- The server sends at most one block per request and nothing outside it.
- Payloads never contain
0x0Bor0x1C. timeoutis between 0.1 and 5 seconds.
Follow-up: after a TimeoutError you do not know whether the lab processed the message. If you send it again, what stops the lab from admitting the patient twice? Problems 18 and 19 are about exactly this.
Hint
socket.create_connection((host, port), timeout=timeout) sets the timeout for the connect and for every later recv() on that socket. When it expires, recv() raises TimeoutError (socket.timeout is an alias of it since Python 3.10). A with block closes the socket however you leave it.
Write it in problems/16-send-and-wait/solution.py, then run:
uv run pytest problems/16-*
Reference solution
import socket
SB = b"\x0b"
EB = b"\x1c\x0d"
def send(host: str, port: int, payload: bytes, timeout: float = 5.0) -> bytes:
with socket.create_connection((host, port), timeout=timeout) as sock:
sock.sendall(SB + payload + EB)
buffer = b""
while EB not in buffer:
chunk = sock.recv(65536) # raises TimeoutError after `timeout` seconds of silence
if not chunk:
raise ConnectionError("server closed the connection before a complete reply")
buffer += chunk
return buffer[buffer.find(SB) + 1 : buffer.find(EB)]
mellp 17: Keep the Line Open
Medium · sockets · client · long-lived · stdlib
Problem 16 opened a connection per message. Real feeds do not: an ADT feed opens one connection and keeps it for hours or days, sending message after message and waiting for each ACK before the next. That saves a handshake per message, but it adds state. Bytes that belong to the next reply can arrive with this one, and once a reply goes missing, the conversation can quietly slip out of step.
class Session:
def __init__(self, host: str, port: int, timeout: float = 5.0) -> None # connects
def send(self, payload: bytes) -> bytes
def close(self) -> None
def __enter__(self) -> "Session"
def __exit__(self, *exc) -> None
send sends one block and returns the payload of the reply block, like problem 16, but over the session's single connection.
- One connection. The constructor connects. Every
senduses that connection; nothing ever reconnects. - Replies arrive in pieces. If bytes beyond the end of a reply arrive, they are the start of the next reply: keep them for the next
send. - The reply must match. If the reply's
MSA-2differs from theMSH-10of the message just sent, raiseConnectionError. - A failure breaks the session.
TimeoutErrorwhen the server sends nothing fortimeoutseconds,ConnectionErrorwhen it closes before a complete reply (or any other socket error): close the socket and re-raise. Every latersendraisesConnectionErrorwithout sending anything. - Closing.
close()may be called any number of times.sendaftercloseraisesConnectionError. Leaving awithblock closes the session.
Why rule 4 is so strict: suppose the ACK for message 2 is late. You time out and send message 3. The late ACK for message 2 now arrives and is read as the answer to message 3. From then on every ACK is off by one, and a rejection of message 7 is reported against message 8. Rule 3 catches one such mismatch, and closing the connection is the only safe recovery: a new connection starts with no old replies in flight.
Example 1:
s = Session("127.0.0.1", 2575)
s.send(adt_1) -> b"MSH|...\rMSA|AA|MSG00001\r"
s.send(adt_2) -> b"MSH|...\rMSA|AA|MSG00002\r"
Explanation: both messages travel over the same connection.
Example 2:
s = Session("127.0.0.1", 2575, timeout=0.1) the server will answer message 1 after 0.4 s
s.send(adt_1) -> TimeoutError
s.send(adt_2) -> ConnectionError adt_2 is never sent
Example 3:
s = Session("127.0.0.1", 2575) the server answers message 1 with "MSA|AA|WRONG"
s.send(adt_1) -> ConnectionError
s.send(adt_2) -> ConnectionError
Constraints:
- Over the whole connection the server sends at most one reply block per message, in order, and no bytes outside blocks. Where one read ends is up to the network.
- Every message has a non-empty
MSH-10. Every reply has anMSAsegment. - Payloads never contain
0x0Bor0x1C. Segments end with\r. - A refused connection makes the constructor raise
ConnectionRefusedError(aConnectionError).
Follow-up: a broken session loses the connection, but the caller still has a message that may or may not have been processed. Should the caller reconnect and resend? Problem 18 says how often, problem 19 makes resending safe for the receiver.
Hint 1
Keep a buffer on the instance and a socket that becomes None once the session is closed or broken. A try / except OSError around the send-and-read catches both TimeoutError and ConnectionError, since both are subclasses of OSError.
Hint 2
Fields are separated by | and segments by \r. In MSH, the first | is itself field 1, so MSH-10 is item 9 of msh_segment.split(b"|") while MSA-2 is item 2 of msa_segment.split(b"|").
Write it in problems/17-keep-the-line-open/solution.py, then run:
uv run pytest problems/17-*
Reference solution
import socket
SB = b"\x0b"
EB = b"\x1c\x0d"
def fields(message: bytes, name: bytes) -> list[bytes]:
"""The `|`-separated parts of the first segment called `name`. For MSH, MSH-n is part n - 1."""
for segment in message.split(b"\r"):
if segment.startswith(name + b"|"):
return segment.split(b"|")
return []
class Session:
def __init__(self, host: str, port: int, timeout: float = 5.0) -> None:
self._sock: socket.socket | None = socket.create_connection((host, port), timeout=timeout)
self._buffer = b""
def send(self, payload: bytes) -> bytes:
if self._sock is None:
raise ConnectionError("the session is closed")
try:
self._sock.sendall(SB + payload + EB)
reply = self._read_block()
if fields(reply, b"MSA")[2] != fields(payload, b"MSH")[9]:
raise ConnectionError("the reply acknowledges a different message")
except OSError: # TimeoutError and ConnectionError included: the stream is out of step
self.close()
raise
return reply
def _read_block(self) -> bytes:
while (end := self._buffer.find(EB)) == -1:
chunk = self._sock.recv(65536)
if not chunk:
raise ConnectionError("the server closed the connection")
self._buffer += chunk
block = self._buffer[self._buffer.find(SB) + 1 : end]
self._buffer = self._buffer[end + len(EB) :]
return block
def close(self) -> None:
if self._sock is not None:
self._sock.close()
self._sock = None
def __enter__(self) -> "Session":
return self
def __exit__(self, *exc) -> None:
self.close()
mellp 20: Many Callers
Medium · sockets · server · threads · stdlib
A real receiver does not answer one call and hang up. The registration system, the lab system and the pharmacy system each open a connection in the morning and keep it open all day, sending a message whenever something happens. One of them may go quiet for an hour, and one may die halfway through a message. None of that may hold up the others.
def serve(
listener: socket.socket,
handler: Callable[[bytes], bytes],
stop: threading.Event,
) -> None
listener is already bound and listening. serve blocks until stop is set.
- Every connection is long-lived: the client sends any number of messages, and gets one reply block per message,
handler(payload), in the order it sent them, until it closes the connection. - Connections are served concurrently. A client that is idle, slow, or stuck halfway through a message delays nobody else.
- A client that disconnects, even in the middle of a message or with a TCP reset, does not disturb the server or the other clients. A half-received message is never passed to
handler. - Within 1 s of
stop.set(),servereturns, and the connections it accepted are closed.
Example 1:
client A connects, sends MSG00001, MSG00002, MSG00003 in one write
client A receives the replies for MSG00001, MSG00002, MSG00003, in that order
client A stays connected and sends MSG00004 ten minutes later: it gets its reply
Example 2:
client A connects and sends nothing
client B connects, sends half of MSG00001 and stalls
client C connects, sends MSG00002 -> gets its reply at once
client B sends the rest of MSG00001 -> gets its reply
Example 3:
handler sleeps 0.02 s per message
20 clients each send 20 messages, one at a time, waiting for each reply
a server that serves one client at a time needs 20 * 20 * 0.02 = 8 s
yours finishes in well under 4 s
Constraints:
handlernever raises and returns the reply payload, unframed.- Clients send well-formed blocks with nothing between them, though a block may arrive in pieces and several blocks may arrive in one read.
- Payloads never contain
0x0Bor0x1C. - Tests run up to 20 clients at once.
servedoes not closelistener; the caller does.
Follow-up: one thread per connection is fine for twenty interfaces. What breaks at ten thousand idle connections, and what would you change? Problem 21 is one answer.
Hint 1
One thread runs the accept loop; each accepted connection gets its own thread (threading.Thread(target=..., daemon=True)) running a receive loop like the one in problem 15, which keeps going instead of returning after one reply. recv() returns b"" on a clean close and raises ConnectionResetError (an OSError) on a reset.
Hint 2
accept() blocks forever and never looks at stop. listener.settimeout(0.1) makes it raise TimeoutError every 0.1 s so the loop can check. Accepted sockets do not inherit that timeout. To close connections whose threads are blocked in recv(), keep them in a set guarded by a threading.Lock and call conn.shutdown(socket.SHUT_RDWR) on each: the blocked recv() returns b"" and the thread finishes on its own.
Write it in problems/20-many-callers/solution.py, then run:
uv run pytest problems/20-*
Reference solution
import socket
import threading
from collections.abc import Callable
SB = b"\x0b"
EB = b"\x1c\x0d"
def serve(
listener: socket.socket,
handler: Callable[[bytes], bytes],
stop: threading.Event,
) -> None:
connections: set[socket.socket] = set()
lock = threading.Lock() # guards `connections`
def converse(conn: socket.socket) -> None:
"""Answers one client's messages in order until it hangs up."""
buffer = b""
try:
while chunk := conn.recv(65536):
buffer += chunk
while (end := buffer.find(EB)) != -1:
payload = buffer[buffer.find(SB) + 1 : end]
buffer = buffer[end + len(EB) :]
conn.sendall(SB + handler(payload) + EB)
except OSError:
pass # reset by the peer, or shut down by serve()
finally:
with lock:
connections.discard(conn)
conn.close()
listener.settimeout(0.1) # accept() wakes up regularly to look at `stop`
while not stop.is_set():
try:
conn, _ = listener.accept()
except TimeoutError:
continue
with lock:
connections.add(conn)
threading.Thread(target=converse, args=(conn,), daemon=True).start()
with lock:
for conn in connections:
try:
conn.shutdown(socket.SHUT_RDWR) # wakes the worker blocked in recv()
except OSError:
pass # the peer is already gone
mellp 21: Async Listener
Medium · asyncio · server · python-hl7
Problem 20 spends one thread per connection, most of them asleep waiting for the next message. asyncio serves every connection from one thread, and python-hl7 ships an asyncio MLLP server that does the framing and the parsing for you. The work left is the part the library cannot decide: what to do when a client goes away.
async def start(
handler: Callable[[hl7.Message], Awaitable[hl7.Message]],
host: str = "127.0.0.1",
port: int = 0,
) -> asyncio.Server
Build the server of problem 20 on hl7.mllp.start_hl7_server. The handler receives each message as a parsed hl7.Message and returns the hl7.Message to send back.
- Connections are long-lived: any number of messages per connection, one reply per message, in order.
- Clients are served concurrently. With a handler that awaits
asyncio.sleep(0.2), 50 clients sending one message each all have their replies in under 2 s. - A client that disconnects, cleanly, mid-message, or with a TCP reset, ends only its own connection. So does a client that sends bytes outside a block (before the start byte
0x0B): close that connection. No exception is left unhandled: the tests install a loop exception handler and assert it never fires. startreturns once the server is listening, and returns theasyncio.Server. The caller reads the port fromserver.sockets[0].getsockname()[1]and stops it withserver.close().
Example 1:
handler = async def (msg): return msg.create_ack()
server = await start(handler)
client sends MSG00001, MSG00002 on one connection
client receives ACKs with MSA-2 MSG00001, then MSG00002
Example 2:
client A sends half of a block, then closes
client B, connected all along, sends MSG00003 -> gets its ACK
nothing is reported to the loop's exception handler
Example 3:
client sends b"\r\n" + a framed message
the server closes that connection; other clients are unaffected
Constraints:
- Every complete block is a parseable HL7 message in ASCII.
handlernever raises.- Tests run every case under
asyncio.runwith plainasyncio.open_connectionclients writing framed bytes.
Follow-up: rule 3 closes the connection on the stray \r\n and loses the message after it, while the Deframer of problem 04 would have skipped the noise and kept the message. Which behaviour do you want on a production feed, and how would you get the other one with this library?
Hint 1
import hl7.mllp explicitly: import hl7 alone does not load it. start_hl7_server(client_connected_cb, host, port) calls client_connected_cb(reader, writer) for each connection, and if that call returns a coroutine (an async def callback), the server runs it as a task. Loop on await reader.readmessage(), then writer.writemessage(reply) and await writer.drain(). Close the writer when the loop ends.
Hint 2
Found by running python-hl7 0.4.5 on Python 3.12. reader.readmessage() raises:
asyncio.IncompleteReadError(a subclass ofEOFError) on a clean close between messages. Its.partialisb"".asyncio.IncompleteReadErroron a close mid-block..partialholds the bytes of the unfinished block.ConnectionResetErrorwhen the client resets the connection.hl7.mllp.InvalidBlockErrorwhen the bytes up to the next0x1C 0x0Ddo not begin with0x0B. Those bytes are consumed, message included.
An exception that escapes the per-connection task is not lost silently: when the dead task is garbage collected, asyncio reports "Task exception was never retrieved" to the loop's exception handler.
Write it in problems/21-async-listener/solution.py, then run:
uv run pytest problems/21-*
Reference solution
import asyncio
from collections.abc import Awaitable, Callable
import hl7
import hl7.mllp
async def start(
handler: Callable[[hl7.Message], Awaitable[hl7.Message]],
host: str = "127.0.0.1",
port: int = 0,
) -> asyncio.Server:
async def converse(reader: hl7.mllp.HL7StreamReader, writer: hl7.mllp.HL7StreamWriter) -> None:
try:
while True:
message = await reader.readmessage()
writer.writemessage(await handler(message))
await writer.drain()
except (asyncio.IncompleteReadError, ConnectionError):
pass # the client hung up, cleanly or not, possibly mid-message
except hl7.mllp.InvalidBlockError:
pass # bytes outside a block: this stream cannot be trusted any more
finally:
writer.close()
return await hl7.mllp.start_hl7_server(converse, host, port)
Acknowledgments
Lecture: Acknowledgments.
hl7-practice 08: build_ack(message, ack_code, now) -> str
Medium
Build the ACK replying to the original message. Output is 2 segments joined by \r:
MSH|^~\&|<MSH-5>|<MSH-6>|<MSH-3>|<MSH-4>|<now>||ACK^<MSH-9.2>|ACK<MSH-10>|<MSH-11>|<MSH-12>
MSA|<ack_code>|<original MSH-10>
- Sender/receiver swap: the receiving app/facility (
MSH-5/6) now becomes the sender. MSA-2must equal the originalMSH-10so the other side knows which message is being acknowledged.
build_ack(ORU, 'AA', '202611111016') →
MSH|^~\&|EMR|HOSP|LAB|HOSP|202611111016||ACK^R01|ACKMSG42|P|2.5.1\rMSA|AA|MSG42
Write it in p08_build_ack.py, then run python3 test_practice.py p08.
Reference solution
from solutions.p03_message_type import message_type
def build_ack(message: str, ack_code: str, now: str) -> str:
msh = message.splitlines()[0].split("|")
m = lambda n: msh[n - 1] # MSH-n sits at index n-1
_, event = message_type(message)
ack_type = f"ACK^{event}" if event else "ACK"
header = ["MSH", m(2), m(5), m(6), m(3), m(4), now, "", ack_type, "ACK" + m(10), m(11), m(12)]
return "|".join(header) + "\r" + f"MSA|{ack_code}|{m(10)}"
mellp 09: Echo the Control ID
Easy · ack · msa · python-hl7
In original-mode acknowledgment, every message you receive gets an ACK back on the same connection, and the sender matches that ACK to the message it sent through one value: MSA-2, which echoes the original MSH-10. An ACK with the wrong MSA-2 is useless to the sender, because it cannot tell which message you accepted. Build the general acknowledgment.
def build_ack(raw: str, code: str = "AA", text: str = "") -> str
Return exactly two segments, MSH then MSA, each ending with \r:
- MSH-1 and MSH-2 as in the original.
- The reply goes back the way it came: MSH-3/MSH-4 are the original MSH-5/MSH-6, and MSH-5/MSH-6 are the original MSH-3/MSH-4.
- MSH-7 is the current date and time as 14 digits,
YYYYMMDDHHMMSS. The tests accept local time or UTC. - MSH-9.1 is
ACKand MSH-9.2 is the original trigger event (MSH-9.2). WritingACKas the message structure in MSH-9.3 is fine. - MSH-10 is a new control ID: non-empty and different on every call.
- MSH-11 (processing ID) and MSH-12 (version) are copied from the original.
- MSA-1 is
code, MSA-2 is the original MSH-10, and MSA-3 istextwhentextis not empty.
Example 1:
Input: raw = "MSH|^~\\&|EPIC|HOSP|LAB|CORE|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
build_ack(raw)
Output: "MSH|^~\\&|LAB|CORE|EPIC|HOSP|20261112093015||ACK^A01^ACK|6316093015123456ABCD|P|2.5\r"
"MSA|AA|MSG00001\r"
Explanation: MSH-7 and MSH-10 will differ on every call.
Example 2:
Input: build_ack(raw, "AE", "PID-3 is required")
Output: "MSH|^~\\&|LAB|CORE|EPIC|HOSP|20261112093016||ACK^A01^ACK|6316093016004521WXYZ|P|2.5\r"
"MSA|AE|MSG00001|PID-3 is required\r"
Constraints:
- The message uses the default delimiters
|^~\&, segments end with\r, and MSH-3 through MSH-12 are present. codeis one ofAA,AE,AR.textcontains no delimiter characters.
Follow-up: enhanced-mode acknowledgment (MSH-15 and MSH-16) splits the reply in two: a commit ACK (CA, CE, CR) saying the message was safely stored, and an application ACK saying it was processed. When would a sender want both?
Hint 1
hl7.parse(raw).create_ack(code) builds MSH and MSA with the parties swapped, MSA-2 echoed and a generated control ID, but it has no parameter for MSA-3. A python-hl7 segment has assign_field(value, field_number). str() of a python-hl7 message ends every segment with \r.
In python-hl7 0.4.5 create_ack stamps MSH-7 in UTC through datetime.utcnow(), which is deprecated since Python 3.12. The tests silence that DeprecationWarning.
Hint 2
Building it by hand is about as short. raw.split("\r")[0].split("|") gives a list in which index k holds MSH-(k + 1), because MSH-1 is the separator you just split on.
Write it in problems/09-echo-the-control-id/solution.py, then run:
uv run pytest problems/09-*
Reference solution
import hl7
def build_ack(raw: str, code: str = "AA", text: str = "") -> str:
# create_ack swaps the parties, echoes MSH-10 into MSA-2 and stamps a new control ID.
ack = hl7.parse(raw).create_ack(code)
if text:
ack.segment("MSA").assign_field(text, 3)
return str(ack) # str() of a python-hl7 Message ends every segment with \r
mellp 10: AA, AE or AR
Medium · ack · validation · python-hl7
In original-mode acknowledgment, MSA-1 carries one of three codes from HL7 Table 0008: AA application accept, AE application error, AR application reject. This problem uses the following convention to choose between the last two. AR means this interface will never accept the message as addressed: a message type it does not handle, a version it does not speak, or a processing ID other than P (production; Table 0103 also has T training and D debugging). Resending it unchanged is pointless. AE means the message is the right kind but its content is wrong, so someone has to fix the data.
SUPPORTED_TYPES = {"ADT^A01", "ADT^A08", "ORU^R01", "ORM^O01"}
SUPPORTED_VERSIONS = {"2.3", "2.3.1", "2.4", "2.5", "2.5.1"}
def respond(raw: bytes) -> bytes
Return the ACK payload for an inbound payload. Run these checks in order; the first failure decides the answer:
- MSH-12 not in
SUPPORTED_VERSIONS:AR, textunsupported version: <MSH-12> - MSH-11 is not
P:AR, textunsupported processing id: <MSH-11> <MSH-9.1>^<MSH-9.2>not inSUPPORTED_TYPES:AR, textunsupported message type: <MSH-9.1>^<MSH-9.2>- no PID segment:
AE, textPID segment is required - PID-3.1 empty:
AE, textPID-3 is required - PID-5.1 empty:
AE, textPID-5 is required - otherwise
AAwith no text
The ACK is the one from problem 09: MSH with the parties swapped, MSH-9 ACK^<trigger>, MSH-11 and MSH-12 copied, MSA-1 the code, MSA-2 the original MSH-10, MSA-3 the text. Encode it as UTF-8.
Example 1:
Input: b"MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
b"EVN|A01|20260105083000\r"
b"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
Output: b"MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20261112093015||ACK^A01^ACK|6316093015123456ABCD|P|2.5\r"
b"MSA|AA|MSG00001\r"
Example 2:
Input: the same message with version 2.6 in MSH-12
Output: b"MSH|...\rMSA|AR|MSG00001|unsupported version: 2.6\r"
Example 3:
Input: the same message with PID-3 empty and MSH-11 set to T
Output: b"MSH|...\rMSA|AR|MSG00001|unsupported processing id: T\r"
Explanation: the processing ID check comes before the PID checks.
Constraints:
- The payload is UTF-8, uses the default delimiters
|^~\&, and segments end with\r. - MSH is well-formed through MSH-12. MSH-11 and MSH-12 hold a single value with no components.
- There is at most one PID segment. When it is there, it has fields through PID-5.
- The tests check MSA-1 exactly and that MSA-3 contains the offending value or field name.
Follow-up: a well-formed admit arrives for a patient your system has never seen and cannot create. Is that AE, AR, or AA plus a work queue entry? Who reads the text of an AE, and how quickly?
Hint 1
Split the work in two: one function that returns (code, text) from a parsed message as a series of early returns, and the ACK builder from problem 09.
Hint 2
With python-hl7, msg["MSH.F12"] reads the version, and asking for a segment that is not there (msg.segment("PID") or msg["PID.F3.R1.C1"]) raises KeyError.
Write it in problems/10-aa-ae-or-ar/solution.py, then run:
uv run pytest problems/10-*
Reference solution
import hl7
SUPPORTED_TYPES = {"ADT^A01", "ADT^A08", "ORU^R01", "ORM^O01"}
SUPPORTED_VERSIONS = {"2.3", "2.3.1", "2.4", "2.5", "2.5.1"}
def respond(raw: bytes) -> bytes:
message = hl7.parse(raw.decode())
code, text = verdict(message)
ack = message.create_ack(code)
if text:
ack.segment("MSA").assign_field(text, 3)
return str(ack).encode()
def verdict(message: hl7.Message) -> tuple[str, str]:
"""The acknowledgment code and the text for MSA-3, first failed check wins."""
version = message["MSH.F12"]
processing_id = message["MSH.F11"]
message_type = f"{message['MSH.F9.R1.C1']}^{message['MSH.F9.R1.C2']}"
# AR: this interface will never take the message as addressed.
if version not in SUPPORTED_VERSIONS:
return "AR", f"unsupported version: {version}"
if processing_id != "P":
return "AR", f"unsupported processing id: {processing_id}"
if message_type not in SUPPORTED_TYPES:
return "AR", f"unsupported message type: {message_type}"
# AE: the right kind of message with something wrong in it.
try:
message.segment("PID")
except KeyError:
return "AE", "PID segment is required"
if not message["PID.F3.R1.C1"]:
return "AE", "PID-3 is required"
if not message["PID.F5.R1.C1"]:
return "AE", "PID-5 is required"
return "AA", ""
Delivery: at least once
Lecture: Delivery: at least once.
mellp 18: Try, Try Again
Medium · retries · backoff · ack codes · stdlib
A lab result that never reaches the chart is a patient-safety problem, so senders retry. Retrying blindly is its own problem: hammering a receiver that is restarting keeps it down, and resending a message the receiver has refused fills its error queue with copies. A sender needs a policy for every outcome of a send.
class Rejected(Exception): ...
class DeliveryFailed(Exception):
def __init__(self, attempts: int, reason: str) -> None: ... # sets .attempts and .reason
def deliver(
payload: bytes,
send: Callable[[bytes], bytes],
*,
retries: int = 3,
backoff: float = 0.5,
sleep: Callable[[float], None] = time.sleep,
) -> int
send delivers one payload and returns the reply payload: problem 16 with host and port filled in. deliver returns the number of attempts it took.
- Success is a reply with
MSA-1AAandMSA-2equal to the payload'sMSH-10. - Retry on
TimeoutError,ConnectionError(refused, reset, or closed early), anAEreply, and a reply whoseMSA-2is not this message'sMSH-10. Such a reply is a stale ACK for some other message, whatever its code. - Rejection: an
ARreply for this message raisesRejectedat once, withMSA-3as the exception message. A rejected message is never sent again. - Attempts: at most
1 + retries. Before retryk(k = 1, 2, ...) callsleep(backoff * 2 ** (k - 1)). Never sleep after the last attempt. - Giving up: when the attempts run out, raise
DeliveryFailed(attempts, reason), wherereasonis a short non-empty description of the last failure. - Same payload every time. Every attempt sends the identical bytes, same
MSH-10, so the receiver can recognise a duplicate. - Anything else propagates. Any other exception from
sendis not caught, not wrapped, and not retried.
Retrying AE is this problem's policy, not a rule of HL7. In real life the receiving system's interface specification decides which codes are worth a retry.
Example 1:
send outcomes: TimeoutError, reply MSA|AE|MSG00001, reply MSA|AA|MSG00001
deliver(adt, send) -> 3
sleep calls: 0.5, 1.0
Example 2:
send outcomes: reply MSA|AR|MSG00001|unknown patient
deliver(adt, send) -> raises Rejected("unknown patient"), after one attempt and no sleep
Example 3:
send outcomes: TimeoutError, TimeoutError
deliver(adt, send, retries=1, backoff=2.0) -> raises DeliveryFailed, .attempts == 2
sleep calls: 2.0
Constraints:
retries >= 0,backoff > 0.payloadhas a non-emptyMSH-10. Every reply has anMSAsegment whoseMSA-1isAA,AEorAR.- Segments end with
\r. - Tests pass a recording
sleepthat returns at once, plus one test against a real server that closes, stays silent, answersAE, and finally answersAA.
Follow-up: 2 ** k grows without bound and every sender that failed at the same moment retries at the same moment. How would you cap the delay, and why do production retry loops add random jitter?
Hint
A for attempt in range(...) loop with a try / except (TimeoutError, ConnectionError) around send, and continue for everything worth another try. Check MSA-2 before looking at the code: a stale AR belongs to another message.
Write it in problems/18-try-try-again/solution.py, then run:
uv run pytest problems/18-*
Reference solution
import time
from collections.abc import Callable
class Rejected(Exception):
"""The receiver answered AR: resending the same message cannot help."""
class DeliveryFailed(Exception):
def __init__(self, attempts: int, reason: str) -> None:
super().__init__(f"gave up after {attempts} attempts: {reason}")
self.attempts = attempts
self.reason = reason
def field(message: bytes, segment: bytes, number: int) -> str:
"""Field `number` of the first `segment` segment, or "" if there is none."""
for line in message.split(b"\r"):
values = line.split(b"|")
if values[0] == segment:
if segment == b"MSH":
values.insert(1, b"|") # MSH-1 is the field separator itself
return values[number].decode() if number < len(values) else ""
return ""
def deliver(
payload: bytes,
send: Callable[[bytes], bytes],
*,
retries: int = 3,
backoff: float = 0.5,
sleep: Callable[[float], None] = time.sleep,
) -> int:
control_id = field(payload, b"MSH", 10)
attempts = 1 + retries
for attempt in range(1, attempts + 1):
if attempt > 1:
sleep(backoff * 2 ** (attempt - 2))
try:
reply = send(payload)
except (TimeoutError, ConnectionError) as error:
reason = f"{type(error).__name__}: {error}"
continue
code = field(reply, b"MSA", 1)
if field(reply, b"MSA", 2) != control_id:
reason = f"stale {code} for {field(reply, b'MSA', 2)!r}"
elif code == "AR":
raise Rejected(field(reply, b"MSA", 3))
elif code == "AA":
return attempt
else:
reason = code
raise DeliveryFailed(attempts, reason)
mellp 19: Seen It Before
Easy · idempotency · duplicates · stdlib
The sender in problem 18 resends when an ACK goes missing. But a missing ACK does not mean a missing message: often the receiver processed the admit, and only the ACK was lost on the way back. Without protection, the resend admits the patient a second time. The receiver has to recognise the resend by its control ID (MSH-10) and answer it without doing the work again.
class Deduplicator:
def __init__(self, process: Callable[[bytes], bytes], capacity: int = 1000) -> None
def __call__(self, payload: bytes) -> bytes
A Deduplicator wraps a handler. process does the real work and returns the reply payload.
- The first time a control ID is seen, call
process(payload)and return its reply. - If that reply's
MSA-1isAA, remember the reply under the control ID. - When a remembered control ID comes again, return the remembered reply without calling
process. - A reply that is not
AAis not remembered, and neither is a call whereprocessraises (let the exception propagate). The resend must be processed for real. - Remember at most
capacitycontrol IDs. When a new one would exceed that, forget the one remembered longest ago.
Example 1:
dedup = Deduplicator(process)
dedup(admit_MSG00001) -> b"MSH|...\rMSA|AA|MSG00001\r" process called
dedup(admit_MSG00001) -> b"MSH|...\rMSA|AA|MSG00001\r" process not called
Example 2:
dedup = Deduplicator(process)
dedup(admit_MSG00001) -> b"MSH|...\rMSA|AE|MSG00001\r" process called
dedup(admit_MSG00001) -> b"MSH|...\rMSA|AA|MSG00001\r" process called again
Explanation: the first attempt failed, so the resend is real work.
Example 3:
dedup = Deduplicator(process, capacity=2)
dedup(m1); dedup(m2); dedup(m3) process called 3 times, m1 is forgotten
dedup(m1) process called again
Constraints:
MSHis the first segment of every payload and itsMSH-10is non-empty. Segments end with\r.- Every reply from
processis an acknowledgment whose second segment isMSA. - Only the control ID decides: a different message with a control ID already remembered gets the remembered reply.
capacity >= 1. Calls come from one thread.
Follow-up: the memory lives in the process, so a restart forgets everything and two receivers behind a load balancer do not share it. Where would you keep it instead, and for how long?
Hint
collections.OrderedDict remembers insertion order, and popitem(last=False) removes the oldest entry. For the control ID, split the first segment on |: because MSH-1 is the separator itself, MSH-10 is item 9.
Write it in problems/19-seen-it-before/solution.py, then run:
uv run pytest problems/19-*
Reference solution
from collections import OrderedDict
from collections.abc import Callable
class Deduplicator:
def __init__(self, process: Callable[[bytes], bytes], capacity: int = 1000) -> None:
self.process = process
self.capacity = capacity
self._replies: OrderedDict[bytes, bytes] = OrderedDict() # control ID -> AA reply
def __call__(self, payload: bytes) -> bytes:
control_id = payload.split(b"\r")[0].split(b"|")[9] # MSH-10: MSH is always first
if control_id in self._replies:
return self._replies[control_id]
reply = self.process(payload)
if b"\rMSA|AA|" in reply:
self._replies[control_id] = reply
if len(self._replies) > self.capacity:
self._replies.popitem(last=False)
return reply
mellp 23: Exactly Once
Hard · retries · duplicates · chaos · stdlib
When an ACK is lost, the sender cannot know whether the receiver processed the message. It has two choices: give up and risk losing a lab result, or resend and risk admitting the patient twice. The network cannot promise "exactly once", but the two ends together can: the sender resends until it gets an AA (at least once), and the receiver recognises a resend by its control ID and does not process it again (at most once). This problem puts problems 17, 18, 19 and 20 together and runs them through a network that misbehaves on purpose.
ACK = "MSH|^~\\&|||||||ACK|ACK{control_id}|P|2.5\rMSA|{code}|{control_id}\r"
class DeliveryFailed(Exception): ...
class Sender:
def __init__(self, host: str, port: int, timeout: float = 0.5, retries: int = 10) -> None
def send(self, payload: bytes) -> bytes # the AA reply payload
def close(self) -> None
def serve(listener: socket.socket, process: Callable[[bytes], None], stop: threading.Event) -> None
Sender
- Keeps one connection open across sends. It connects when it has no connection, including on the first
send. - Success is a reply with MSA-1
AAand MSA-2 equal to the payload's MSH-10;sendreturns that reply payload. On a timeout (no reply withintimeoutseconds), a lost connection, or any other reply: close the connection, connect again, and resend the identical payload. A connection that failed is never reused. - After
1 + retriesattempts without success, raiseDeliveryFailed.
Receiver (serve blocks until stop is set and returns within 1 s of it, closing its connections)
- Serves connections concurrently; each connection is long-lived, one reply per message, in order.
- For a control ID (MSH-10) not yet processed: call
process(payload), then replyAA. Ifprocessraises, replyAEand do not count the message as processed: the resend must be processed for real. - For a control ID already processed: reply
AAagain without callingprocess. processnever runs twice at the same time for the same control ID. A message whose control ID is being processed on another connection waits for that to finish, then rules 5 and 6 apply.
Replies are ACK.format(control_id=..., code="AA") (or "AE"), framed. Rule 2 matters for the reason problem 17 gave: after a timeout, the late ACK can still arrive on the old connection, and a sender that kept reading there would take it for the reply to whatever it sent next.
Example 1: the ACK is lost.
sender -> MSG00001 on connection 1
receiver processes MSG00001, replies AA
network drops the AA and closes connection 1
sender ConnectionError: closes connection 1
sender -> MSG00001 on connection 2
receiver MSG00001 already processed: replies AA, does not call process
sender returns the AA. process was called once.
Example 2: processing fails.
sender -> MSG00002
receiver process raises (database unavailable): replies AE
sender not an AA: closes the connection, resends MSG00002 on a new one
receiver MSG00002 not processed yet: process succeeds, replies AA
Example 3: the ACK is late.
sender -> MSG00003 on connection 1
receiver processes MSG00003, replies AA; the network holds it for 0.4 s
sender no reply within 0.15 s: TimeoutError, closes connection 1
sender -> MSG00003 on connection 2, gets AA (a duplicate, not processed again)
the late AA arrives on connection 1, which nobody reads any more
Constraints:
- Every logical message has its own non-empty MSH-10; a resend carries the same one.
sendis never called from two threads at once.- Payloads never contain
0x0Bor0x1C; blocks may arrive in pieces, with nothing between them. processmay raise anyException. The receiver's memory of processed IDs may grow without limit here.- The main test sends 300 messages through
harness.chaos.ChaosProxy, which for about 35% of requests (fixed seed) drops the ACK and closes, cuts the request in half and closes, relays one byte per write, or delivers the ACK 0.4 s late. The sender runs withtimeout=0.15. Everysendmust return anAA, andprocessmust see the 300 payloads in order, each once.
Follow-up: the processed IDs live in memory, so a receiver restart forgets them and the next resend is processed twice. Where does that record have to live, and why must it be written in the same transaction as the work process does?
Hint 1
The sender's whole state is one socket (or None) and the bytes read past the last reply. On any failure, close the socket, set it to None and drop those bytes, so the next attempt starts on a clean connection. socket.create_connection((host, port), timeout=timeout) makes every later recv raise TimeoutError after timeout seconds of silence. TimeoutError, ConnectionError and a refused connect are all OSError.
Hint 2
The receiver is problem 20's server with problem 19's memory, but "is it processed? no: process it, remember it" must be one step, or two connections carrying the same resend both see "no". The simplest correct version holds one threading.Lock around that step, which also processes messages one at a time.
Write it in problems/23-exactly-once/solution.py, then run:
uv run pytest problems/23-*
Reference solution
import socket
import threading
from collections.abc import Callable
SB = b"\x0b"
EB = b"\x1c\x0d"
ACK = "MSH|^~\\&|||||||ACK|ACK{control_id}|P|2.5\rMSA|{code}|{control_id}\r"
class DeliveryFailed(Exception):
pass
def field(payload: bytes, segment: bytes, index: int) -> bytes:
"""Field `index` of the first `segment` (for MSH the index is one less than MSH-n)."""
for line in payload.split(b"\r"):
fields = line.split(b"|")
if fields[0] == segment:
return fields[index] if index < len(fields) else b""
return b""
class Sender:
def __init__(self, host: str, port: int, timeout: float = 0.5, retries: int = 10) -> None:
self.address = (host, port)
self.timeout = timeout
self.retries = retries
self._sock: socket.socket | None = None
self._buffer = b""
def send(self, payload: bytes) -> bytes:
control_id = field(payload, b"MSH", 9)
for _ in range(1 + self.retries):
try:
reply = self._exchange(payload)
except OSError: # TimeoutError, ConnectionError, refused
self.close()
continue
if field(reply, b"MSA", 1) == b"AA" and field(reply, b"MSA", 2) == control_id:
return reply
self.close() # an AE, or a stale reply: this connection is out of step
raise DeliveryFailed(f"{control_id.decode()}: no AA after {1 + self.retries} attempts")
def close(self) -> None:
if self._sock is not None:
self._sock.close()
self._sock = None
def _exchange(self, payload: bytes) -> bytes:
if self._sock is None:
self._sock = socket.create_connection(self.address, timeout=self.timeout)
self._buffer = b""
self._sock.sendall(SB + payload + EB)
while EB not in self._buffer:
chunk = self._sock.recv(65536)
if not chunk:
raise ConnectionError("receiver closed the connection")
self._buffer += chunk
end = self._buffer.find(EB)
reply = self._buffer[self._buffer.find(SB) + 1 : end]
self._buffer = self._buffer[end + len(EB) :]
return reply
def serve(
listener: socket.socket,
process: Callable[[bytes], None],
stop: threading.Event,
) -> None:
receiver = Receiver(process)
listener.settimeout(0.1) # accept() wakes up regularly to look at `stop`
while not stop.is_set():
try:
conn, _ = listener.accept()
except TimeoutError:
continue
with receiver.lock:
receiver.connections.add(conn)
threading.Thread(target=receiver.converse, args=(conn,), daemon=True).start()
with receiver.lock:
for conn in receiver.connections:
try:
conn.shutdown(socket.SHUT_RDWR) # wakes the worker blocked in recv()
except OSError:
pass # the sender is already gone
class Receiver:
def __init__(self, process: Callable[[bytes], None]) -> None:
self.process = process
self.processed: set[bytes] = set()
self.processing = threading.Lock() # one at a time: no ID is processed twice at once
self.connections: set[socket.socket] = set()
self.lock = threading.Lock() # guards `connections`
def converse(self, conn: socket.socket) -> None:
buffer = b""
try:
while chunk := conn.recv(65536):
buffer += chunk
while (end := buffer.find(EB)) != -1:
payload = buffer[buffer.find(SB) + 1 : end]
buffer = buffer[end + len(EB) :]
conn.sendall(SB + self.handle(payload) + EB)
except OSError:
pass # the sender went away; it will resend on a new connection
finally:
with self.lock:
self.connections.discard(conn)
conn.close()
def handle(self, payload: bytes) -> bytes:
control_id = field(payload, b"MSH", 9)
with self.processing:
if control_id not in self.processed:
try:
self.process(payload)
except Exception:
return ack(control_id, "AE")
self.processed.add(control_id)
return ack(control_id, "AA")
def ack(control_id: bytes, code: str) -> bytes:
return ACK.format(control_id=control_id.decode(), code=code).encode()
mellp 24: Unbreakable Listener
Hard · sockets · server · limits · graceful shutdown · stdlib
Problem 20's server works as long as every peer behaves. A production listener faces a peer that connects and never speaks, a misconfigured system that streams a block with no end, a handler that throws on a message it cannot store, a port scanner that opens hundreds of connections, and a deployment that restarts the service while a message is half processed. Each one, unhandled, either takes the listener down or quietly loses a message. Harden the server against all of them.
ERROR_ACK = "MSH|^~\\&|||||||ACK|{own_id}|P|2.5\rMSA|AE|{control_id}\r"
def serve(
listener: socket.socket,
handler: Callable[[bytes], bytes],
stop: threading.Event,
*,
idle_timeout: float = 30.0,
max_size: int = 1_048_576,
max_connections: int = 100,
) -> None
serve blocks until stop is set, as in problem 20.
- Concurrent, long-lived connections. Any number of messages per connection, one reply per message, in order. A slow client delays nobody else.
- Idle timeout. A connection on which no bytes arrive for
idle_timeoutseconds is closed. This also catches a peer stuck halfway through a message. Time the server spends inhandlerdoes not count against the peer. - Size limit. When a block's payload is longer than
max_sizebytes, close the connection without a reply, and do not wait for the end of the block to find out: the server never buffers much more thanmax_sizebytes per connection. A payload of exactlymax_sizebytes is fine. - Handler errors. If
handlerraises, reply withERROR_ACK(anAEwhose MSA-2 is the message's MSH-10, with any uniqueown_id) and keep serving the connection. - Graceful stop. After
stop.set(), no new connection is served. A message whose handler is already running still gets its reply. Then every connection is closed andservereturns. - Noise between blocks is ignored, as in problem 04 rule 1: bytes before a block's
0x0Bare dropped. - Connection limit. While
max_connectionsconnections are open, a new connection is closed as soon as it is accepted.
Example 1:
idle_timeout=0.3
client connects and sends nothing -> closed after about 0.3 s
client sends a message every 0.15 s -> stays open, every message answered
Example 2:
max_size=1000
client sends a block with a 1000-byte payload -> AA
client sends a block with a 1001-byte payload -> connection closed, no reply, handler not called
client sends 0x0B and then bytes without end -> closed once the payload passes 1001 bytes
Example 3:
client A's message is in the handler, which takes a while
stop.set()
client B connects and sends a message -> no reply
the handler returns -> client A gets its reply, then A is closed
serve returns
Constraints:
- Tests use
idle_timeout=0.3,max_size=1000,max_connections=3unless they say otherwise. - A complete block's payload never contains
0x0Bor0x1C. Noise between blocks may contain anything except0x0B. - Every message has an MSH segment with an MSH-10.
servedoes not closelistener; the caller does, afterservereturns.
Follow-up: rule 5 waits for the handler however long it takes. Most service managers send SIGTERM, wait a fixed time, then kill the process. What would you do with a handler that is still running when that time is almost up, and what does the sender see in each case?
Hint 1
One flag cannot interrupt a thread blocked in recv(), so do not block forever: conn.settimeout(0.05) makes recv() raise TimeoutError every 0.05 s. On each wake-up check stop and how long ago the last byte arrived (time.monotonic()). The same loop then gives you rules 2 and 5: a thread that is inside handler is not in recv(), so it finishes the reply before it next looks at stop. serve can join() every connection thread before it returns.
Hint 2
For the size limit, check the open block after every read, not only when its end arrives. Allow one byte of slack, as in problem 04 hint 2: a block whose payload is exactly max_size bytes can sit in the buffer with its 0x1C but not yet its 0x0D.
Write it in problems/24-unbreakable-listener/solution.py, then run:
uv run pytest problems/24-*
Reference solution
import socket
import threading
import time
import uuid
from collections.abc import Callable
SB = b"\x0b"
EB = b"\x1c\x0d"
POLL = 0.05 # how often a waiting thread looks at `stop`
ERROR_ACK = "MSH|^~\\&|||||||ACK|{own_id}|P|2.5\rMSA|AE|{control_id}\r"
class TooLarge(Exception):
pass
def serve(
listener: socket.socket,
handler: Callable[[bytes], bytes],
stop: threading.Event,
*,
idle_timeout: float = 30.0,
max_size: int = 1_048_576,
max_connections: int = 100,
) -> None:
server = Server(handler, stop, idle_timeout, max_size)
listener.settimeout(POLL)
while not stop.is_set():
try:
conn, _ = listener.accept()
except TimeoutError:
continue
server.admit(conn, max_connections)
server.finish()
class Server:
def __init__(self, handler, stop: threading.Event, idle_timeout: float, max_size: int):
self.handler = handler
self.stop = stop
self.idle_timeout = idle_timeout
self.max_size = max_size
self.workers: set[threading.Thread] = set()
self.lock = threading.Lock() # guards `workers`
def admit(self, conn: socket.socket, max_connections: int) -> None:
with self.lock:
if len(self.workers) >= max_connections:
conn.close()
return
worker = threading.Thread(target=self.serve_connection, args=(conn,))
self.workers.add(worker)
worker.start()
def finish(self) -> None:
"""Waits for every connection to deliver the reply in flight and close."""
with self.lock:
running = list(self.workers)
for worker in running:
worker.join()
def serve_connection(self, conn: socket.socket) -> None:
try:
with conn:
self.converse(conn)
except (OSError, TooLarge):
pass # the peer went away, or broke the size limit: either way, close
finally:
with self.lock:
self.workers.discard(threading.current_thread())
def converse(self, conn: socket.socket) -> None:
conn.settimeout(POLL)
buffer = b""
last_heard = time.monotonic()
while not self.stop.is_set():
if time.monotonic() - last_heard > self.idle_timeout:
return
try:
chunk = conn.recv(65536)
except TimeoutError:
continue
if not chunk:
return
buffer += chunk
while (block := self.take_block(buffer)) is not None:
payload, buffer = block
conn.sendall(SB + self.reply(payload) + EB)
buffer = self.trim(buffer)
last_heard = time.monotonic() # time spent in the handler is not the peer's
def take_block(self, buffer: bytes) -> tuple[bytes, bytes] | None:
"""The first complete block's payload and what follows it, or None."""
start = buffer.find(SB)
end = buffer.find(EB, start + 1)
if start == -1 or end == -1:
return None
if end - start - 1 > self.max_size:
raise TooLarge
return buffer[start + 1 : end], buffer[end + len(EB) :]
def trim(self, buffer: bytes) -> bytes:
"""Drops noise before the open block and enforces the size limit on it."""
start = buffer.find(SB)
if start == -1:
return b""
if len(buffer) - start - 1 > self.max_size + 1: # +1: a trailing 0x1C may begin EB
raise TooLarge
return buffer[start:]
def reply(self, payload: bytes) -> bytes:
try:
return self.handler(payload)
except Exception: # an AE, not a dropped connection; the error text is not sent back
header = payload.split(b"\r", 1)[0].split(b"|")
control_id = header[9].decode(errors="replace") if len(header) > 9 else ""
return ERROR_ACK.format(own_id=uuid.uuid4().hex[:20], control_id=control_id).encode()
Patient identity
Lecture: Patient identity.
hl7-practice 17: Link patients (MPI)
Medium
INT-204: Same person, but one ID per facility → the system sees 2–3 patients. Merge them.
link_patients(messages: list[str]) -> list[list[str]]
- Each
PID-3repeat → identifier"<PID-3.4>:<PID-3.1>"(authority:id). Skip repeats missing the id or the authority. - Identifiers in the same message = the same person. The same identifier in several messages = link those people together.
- Same ID number but different authority (
HOSP:777vsCLINIC_B:777) = different people. - Message without PID → skip.
- Output: each group sorted; the list of groups sorted.
Write it in p17_link_patients.py, then run python3 test_practice.py p17.
Reference solution
It imports solutions/_hl7.py.
from solutions._hl7 import field, first, part
def link_patients(messages: list[str]) -> list[list[str]]:
parent = {}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for m in messages:
pid = first(m, "PID")
if pid is None:
continue
ids = []
for rep in field(pid, 3).split("~"):
id_, auth = part(rep, "^", 1), part(rep, "^", 4)
if id_ and auth:
ids.append(f"{auth}:{id_}")
for i in ids:
parent.setdefault(i, i)
for i in ids[1:]:
parent[find(i)] = find(ids[0])
groups = {}
for i in parent:
groups.setdefault(find(i), []).append(i)
return sorted(sorted(g) for g in groups.values())
Building the bridge
Lecture: Building the bridge.
mellp 32: Flatten to JSON
Easy · json · parsing · stdlib
The team next door builds dashboards and does not want to learn pipes and carets. Before anyone agrees on a real mapping, a common first step is a lossless JSON copy of each message: every non-empty field, keyed by its number, with the HL7 text left exactly as it arrived. It is enough to load into a document store and query by position.
def to_json(raw: str) -> dict[str, list[dict[str, str]]]
- One top-level key per segment name, in the order the names first appear in the message.
- Its value is a list with one dict per occurrence of that segment, in message order.
- Each occurrence maps the field number, as a string, to the raw text of that field. Components, repetitions and subcomponents are not split.
- Empty fields are left out. The segment name is not a field.
- MSH is numbered the HL7 way: the field separator itself is MSH-1, so
"1": "|","2": "^~\\&", and"9"is the message type.
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE\r"
Output: {"MSH": [{"1": "|", "2": "^~\\&", "3": "EPIC", "4": "HOSP", "5": "LAB", "6": "HOSP",
"7": "20260105083000", "9": "ADT^A01^ADT_A01", "10": "MSG00001",
"11": "P", "12": "2.5"}],
"PID": [{"1": "1", "3": "12345^^^HOSP^MR", "5": "DOE^JANE"}]}
Explanation: MSH-8, PID-2 and PID-4 are empty, so they are left out.
Example 2:
Input: "MSH|...\rPID|1||12345\rOBX|1|NM|2345-7^Glucose^LN||182\rOBX|2|ST|5778-6^Color^LN||YELLOW\r"
Output: {"MSH": [...],
"PID": [{"1": "1", "3": "12345"}],
"OBX": [{"1": "1", "2": "NM", "3": "2345-7^Glucose^LN", "5": "182"},
{"1": "2", "2": "ST", "3": "5778-6^Color^LN", "5": "YELLOW"}]}
Constraints:
- Every segment ends with
\r, the first segment is MSH, and the field separator is|. - Segment names are three characters.
- No escape sequences need decoding: text is copied, never interpreted.
- The result must survive
json.dumpsand come back equal fromjson.loads.
Follow-up: a consumer now wants the patient's given name without knowing what ^ means. What would you add to the shape, and what would you lose if you replaced the raw text instead of adding to it?
Hint
raw.split("\r"), then segment.split("|"). For MSH, insert "|" at index 1 after splitting and the field numbers line up with list positions. dict.setdefault(name, []).append(...) keeps first-appearance order because dicts remember insertion order.
Write it in problems/32-flatten-to-json/solution.py, then run:
uv run pytest problems/32-*
Reference solution
def to_json(raw: str) -> dict[str, list[dict[str, str]]]:
flattened: dict[str, list[dict[str, str]]] = {}
for segment in raw.split("\r"):
if not segment:
continue
fields = segment.split("|")
if fields[0] == "MSH":
fields.insert(1, "|") # MSH-1 is the field separator itself
occurrence = {}
for number, value in enumerate(fields[1:], start=1):
if value:
occurrence[str(number)] = value
flattened.setdefault(fields[0], []).append(occurrence)
return flattened
mellp 33: Patient Resource
Medium · fhir · patient · python-hl7
Sooner or later every v2 feed gets a FHIR consumer. The patient is where it starts: the same PID you have parsed since problem 07, reshaped into an R4 Patient. The mapping is mostly mechanical. What catches people is FHIR's rule that an element without a value is not sent at all, which v2 habits (an empty field is still a field) break constantly.
def to_patient(raw: str) -> dict
Return the R4 Patient as a plain dict, built from the PID segment:
| FHIR | Source | Rule |
|---|---|---|
resourceType |
"Patient" |
|
identifier[] |
each PID-3 repetition whose ID (component 1) is not empty, in order | value = PID-3.1; system = "urn:id:" + the first subcomponent of PID-3.4 when that is not empty; type = {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/v2-0203", "code": PID-3.5}]} when PID-3.5 is not empty |
name[0] |
PID-5, first repetition | family = PID-5.1; given = the non-empty values of PID-5.2 and PID-5.3, in that order |
gender |
PID-8 | F -> "female", M -> "male", O -> "other", anything else (including empty) -> "unknown" |
birthDate |
PID-7 | the first 8 digits as YYYY-MM-DD |
The FHIR rule: every element must have a value or children (invariant ele-1). So there is no empty string, empty list, empty dict or None anywhere in the result. An identifier without a value is skipped, a name with no parts means no name key, and so on. gender is always present.
Example 1:
Input: "MSH|...\rPID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
Output: {"resourceType": "Patient",
"identifier": [{"value": "12345", "system": "urn:id:HOSP",
"type": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MR"}]}}],
"name": [{"family": "DOE", "given": ["JANE", "Q"]}],
"gender": "female",
"birthDate": "1980-02-14"}
Example 2:
Input: "MSH|...\rPID|1||12345\r"
Output: {"resourceType": "Patient", "identifier": [{"value": "12345"}], "gender": "unknown"}
Explanation: no authority, no type, no name, no birth date: those keys are simply not there.
Example 3:
Input: "MSH|...\rPID|1||~^^^HOSP^MR~998877^^^STATE^SS||^JANE|||U\r"
Output: {"resourceType": "Patient",
"identifier": [{"value": "998877", "system": "urn:id:STATE",
"type": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "SS"}]}}],
"name": [{"given": ["JANE"]}],
"gender": "unknown"}
Explanation: the first two repetitions of PID-3 have no ID.
Constraints:
- The message has exactly one PID segment. Fields after the last one present are missing, not empty.
- Delimiters are the standard
|^~\&. No escape sequences. - PID-7 is empty or starts with an 8-digit date
YYYYMMDD; it may continue with a time and an offset. urn:id:is this problem's convention. A real interface uses the URI agreed for each assigning authority.- Key order inside the dicts does not matter.
Follow-up: PID-11 (address) and PID-13 (home phone) are left out here. Add address and telecom, keep the no-empty-values rule, and decide what to do with PID-14 (business phone).
Hint 1
Plain string splitting is the easiest route here. python-hl7 can read single values, hl7.parse(raw)["PID.F3.R1.C1"], but with python-hl7 0.4.5 ["PID.F3.R1.C4"] raises IndexError when PID-3 is just 12345 with no components, and asking for a repetition that does not exist raises too. A small helper that splits and pads with "" avoids both.
Hint 2
Build each dict with every key, then drop the empty ones: {key: value for key, value in element.items() if value}.
Write it in problems/33-patient-resource/solution.py, then run:
uv run pytest problems/33-*
Reference solution
GENDERS = {"F": "female", "M": "male", "O": "other"}
IDENTIFIER_TYPES = "http://terminology.hl7.org/CodeSystem/v2-0203"
def padded(text: str, separator: str, size: int) -> list[str]:
"""Splits `text` and pads with "" so that indexes up to `size - 1` always exist."""
parts = text.split(separator)
return parts + [""] * (size - len(parts))
def without_empty(element: dict) -> dict:
return {key: value for key, value in element.items() if value}
def to_identifier(cx: list[str]) -> dict:
identifier = {"value": cx[0]}
authority = cx[3].split("&")[0]
if authority:
identifier["system"] = "urn:id:" + authority
if cx[4]:
identifier["type"] = {"coding": [{"system": IDENTIFIER_TYPES, "code": cx[4]}]}
return identifier
def to_patient(raw: str) -> dict:
segment = next(line for line in raw.split("\r") if line.startswith("PID|"))
pid = padded(segment, "|", 9)
identifiers = []
for repetition in pid[3].split("~"):
cx = padded(repetition, "^", 5)
if cx[0]:
identifiers.append(to_identifier(cx))
xpn = padded(pid[5].split("~")[0], "^", 3)
name = without_empty({"family": xpn[0], "given": [part for part in xpn[1:3] if part]})
born = pid[7].split("^")[0]
return without_empty(
{
"resourceType": "Patient",
"identifier": identifiers,
"name": [name] if name else [],
"gender": GENDERS.get(pid[8], "unknown"),
"birthDate": f"{born[0:4]}-{born[4:6]}-{born[6:8]}" if born else "",
}
)
mellp 35: Tiny FHIR Server
Medium · http · fhir · fastapi
To test the outbound side of an interface you need something to send to. A real FHIR server is a large install; a few routes in FastAPI cover what a patient feed touches. Building it also teaches the HTTP side of FHIR: which status code means what, and why a feed that retries must never create the same patient twice.
def create_app() -> fastapi.FastAPI
Each call returns a new app with its own in-memory store.
POST /Patienttakes a JSON object. If itsresourceTypeis not"Patient", or it has no non-emptyidentifier[0].value, answer400with an OperationOutcome:{"resourceType": "OperationOutcome", "issue": [{"severity": "error", "code": "invalid", "diagnostics": "<why, not empty>"}]}- A new identifier value creates the patient:
201, headerLocation: /Patient/<id>, body = the posted resource plus a server-assigned"id"(a non-empty string). - An identifier value already stored replaces that patient:
200, sameid, body = the new resource plus thatid. Posting the same patient any number of times leaves exactly one. GET /Patient/<id>answers200with the stored resource, or404with an OperationOutcome whose issue code is"not-found".GET /Patient?identifier=<value>answers200with{"resourceType": "Bundle", "type": "searchset", "total": n, "entry": [{"resource": ...}]}. With no match,totalis0and there is noentrykey (no empty values, as in problem 33).
Rule 3 is not how a standard FHIR server treats POST; there, create and update are separate (PUT is the update, and PUT /Patient?identifier=... is a conditional update). Folding both into one POST keyed on the identifier makes replays from a v2 feed safe, which is what this server is for.
Example 1:
POST /Patient {"resourceType": "Patient", "identifier": [{"value": "12345"}]}
-> 201 Location: /Patient/1
{"resourceType": "Patient", "identifier": [{"value": "12345"}], "id": "1"}
POST /Patient {"resourceType": "Patient", "identifier": [{"value": "12345"}], "gender": "female"}
-> 200 {"resourceType": "Patient", "identifier": [{"value": "12345"}], "gender": "female", "id": "1"}
GET /Patient/1
-> 200 {"resourceType": "Patient", "identifier": [{"value": "12345"}], "gender": "female", "id": "1"}
Example 2:
POST /Patient {"resourceType": "Patient", "identifier": []}
-> 400 {"resourceType": "OperationOutcome",
"issue": [{"severity": "error", "code": "invalid",
"diagnostics": "identifier[0].value is required"}]}
GET /Patient/42
-> 404 {"resourceType": "OperationOutcome", "issue": [{"severity": "error", "code": "not-found", ...}]}
Example 3:
GET /Patient?identifier=12345
-> 200 {"resourceType": "Bundle", "type": "searchset", "total": 1,
"entry": [{"resource": {"resourceType": "Patient", ..., "id": "1"}}]}
GET /Patient?identifier=99999
-> 200 {"resourceType": "Bundle", "type": "searchset", "total": 0}
Constraints:
- Request bodies are always JSON objects. When
identifieris present it is a list of objects. - The search request always has an
identifierparameter. - Ids may be any non-empty string; tests only compare them with each other and with
Location. - Tests use
fastapi.testclient.TestClient; no server is started.
Follow-up: two feeds post the same new patient at the same moment, each on its own worker thread. Can both get 201 with different ids? What would you change?
Hint 1
FastAPI validates request bodies itself and answers 422 when they do not fit the declared type, and this API promises 400. Declare the body as a plain dict (def create(resource: dict)) and check its contents yourself.
Hint 2
A route can return a plain dict (sent as 200) or fastapi.responses.JSONResponse(content, status_code=201, headers={"Location": ...}) when it needs another status or a header. Define the routes inside create_app so they close over that app's own dicts.
Write it in problems/35-tiny-fhir-server/solution.py, then run:
uv run pytest problems/35-*
To run it for real (the directory name has hyphens, so it cannot be imported as a package):
uv run uvicorn --factory --app-dir problems/35-tiny-fhir-server solution:create_app
Reference solution
import itertools
import fastapi
from fastapi.responses import JSONResponse
def outcome(status: int, code: str, diagnostics: str) -> JSONResponse:
issue = {"severity": "error", "code": code, "diagnostics": diagnostics}
return JSONResponse({"resourceType": "OperationOutcome", "issue": [issue]}, status_code=status)
def identifier_of(resource: dict) -> str | None:
identifiers = resource.get("identifier") or [{}]
return identifiers[0].get("value")
def create_app() -> fastapi.FastAPI:
app = fastapi.FastAPI()
patients: dict[str, dict] = {} # id -> stored resource
id_by_identifier: dict[str, str] = {}
next_id = itertools.count(1)
@app.post("/Patient")
def upsert(resource: dict):
if resource.get("resourceType") != "Patient":
return outcome(400, "invalid", "resourceType must be Patient")
identifier = identifier_of(resource)
if not identifier:
return outcome(400, "invalid", "identifier[0].value is required")
existing = id_by_identifier.get(identifier)
patient_id = existing or str(next(next_id))
id_by_identifier[identifier] = patient_id
patients[patient_id] = {**resource, "id": patient_id}
if existing:
return patients[patient_id]
headers = {"Location": f"/Patient/{patient_id}"}
return JSONResponse(patients[patient_id], status_code=201, headers=headers)
@app.get("/Patient/{patient_id}")
def read(patient_id: str):
if patient_id not in patients:
return outcome(404, "not-found", f"no Patient with id {patient_id}")
return patients[patient_id]
@app.get("/Patient")
def search(identifier: str):
found = [patients[id_by_identifier[identifier]]] if identifier in id_by_identifier else []
bundle = {"resourceType": "Bundle", "type": "searchset", "total": len(found)}
if found:
bundle["entry"] = [{"resource": patient} for patient in found]
return bundle
return app
When the FHIR server is down
Lecture: When the FHIR server is down.
mellp 36: Post It
Medium · http · fhir · ack · httpx
This is the bridge between the two worlds: an HL7 v2 feed on one side, a FHIR REST API on the other. The sender of the v2 message is waiting for an ACK and knows nothing about HTTP, so every outcome of the HTTP call has to be translated into AA, AE or AR, with enough text in MSA-3 that whoever reads the error queue can tell what went wrong without the server's logs.
SUPPORTED_TYPES = {"ADT^A01", "ADT^A08"}
def forward(raw: bytes, client: httpx.Client) -> bytes
raw is an HL7 payload (UTF-8). Return the ACK payload.
- MSH-9.1 and MSH-9.2 joined with
^not inSUPPORTED_TYPES->AR, MSA-3unsupported message type: <type>. Nothing is posted. - Otherwise
client.post("/Patient", json=patient)once, wherepatientis{"resourceType": "Patient", "identifier": [{"value": PID-3.1}], "name": [{"family": PID-5.1, "given": [PID-5.2]}]} - Status 2xx ->
AA, no MSA-3. - Any other status ->
AE, MSA-3HTTP <status>. When the body is an OperationOutcome ("resourceType": "OperationOutcome"), append:and thediagnosticsof its first issue:HTTP 400: identifier is required. httpx.TransportError(refused, timed out, connection dropped) ->AE, MSA-3unreachable.- The ACK is built as in problem 09: MSH then MSA, each ending with
\r. MSH-1 and MSH-2 as in the original, MSH-3/4 = original MSH-5/6, MSH-5/6 = original MSH-3/4, MSH-7 = now asYYYYMMDDHHMMSS, MSH-9.1 =ACK, MSH-9.2 = the original trigger event, MSH-10 = a new non-empty ID on every call, MSH-11 and MSH-12 copied. MSA-1 = the code, MSA-2 = the original MSH-10, MSA-3 = the text when there is one.
Example 1:
Input: adt_a01("MSG00001"), the server answers 201
Output: b"MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20260105083001||ACK^A01^ACK|5c1e...|P|2.5\rMSA|AA|MSG00001\r"
Example 2:
Input: adt_a01("MSG00001"), the server answers 400
{"resourceType": "OperationOutcome",
"issue": [{"severity": "error", "code": "invalid", "diagnostics": "identifier is required"}]}
Output: ...\rMSA|AE|MSG00001|HTTP 400: identifier is required\r
Example 3:
Input: oru_r01("MSG00003")
Output: ...\rMSA|AR|MSG00003|unsupported message type: ORU^R01\r
Explanation: nothing was posted.
Constraints:
- MSH has fields through MSH-12 and MSH-9 has at least two components. Messages of a supported type have a PID with PID-3.1, PID-5.1 and PID-5.2.
- Response bodies may be JSON of any shape, plain text or empty. An OperationOutcome always has at least one issue, and its first issue has
diagnostics. - Diagnostics in the tests contain no HL7 delimiters.
- Tests pass a
fastapi.testclient.TestClient, which is anhttpx.Client, and for rule 5 anhttpx.Clientwhose transport raises.
Follow-up: AE on unreachable makes most senders stop or retry the same message. Which HTTP statuses would you rather answer with AA and queue for a retry of your own, and which deserve AR?
Hint 1
response.is_success is true for 2xx. response.json() raises a ValueError subclass when the body is not JSON, and valid JSON can still be a list or a string.
Hint 2
The ACK from your problem 09 build_ack, encoded, covers rule 6. httpx.ConnectError, httpx.ReadTimeout and the other transport failures share the base class httpx.TransportError.
Write it in problems/36-post-it/solution.py, then run:
uv run pytest problems/36-*
Reference solution
import datetime
import uuid
import httpx
SUPPORTED_TYPES = {"ADT^A01", "ADT^A08"}
def build_ack(msh: list[str], code: str, text: str = "") -> bytes:
"""`msh` is the original MSH split on "|": index n holds MSH-(n+1)."""
trigger = msh[8].split("^")[1]
header = [
"MSH", msh[1], msh[4], msh[5], msh[2], msh[3],
datetime.datetime.now().strftime("%Y%m%d%H%M%S"), "",
f"ACK^{trigger}^ACK", uuid.uuid4().hex[:20], msh[10], msh[11],
]
msa = ["MSA", code, msh[9]] + ([text] if text else [])
return ("|".join(header) + "\r" + "|".join(msa) + "\r").encode()
def error_text(response: httpx.Response) -> str:
text = f"HTTP {response.status_code}"
try:
body = response.json()
except ValueError: # not JSON at all
return text
if isinstance(body, dict) and body.get("resourceType") == "OperationOutcome":
return f"{text}: {body['issue'][0]['diagnostics']}"
return text
def forward(raw: bytes, client: httpx.Client) -> bytes:
segments = [line.split("|") for line in raw.decode().split("\r") if line]
msh = segments[0]
message_type = "^".join(msh[8].split("^")[:2])
if message_type not in SUPPORTED_TYPES:
return build_ack(msh, "AR", f"unsupported message type: {message_type}")
pid = next(segment for segment in segments if segment[0] == "PID")
family, given = pid[5].split("^")[:2]
patient = {
"resourceType": "Patient",
"identifier": [{"value": pid[3].split("^")[0]}],
"name": [{"family": family, "given": [given]}],
}
try:
response = client.post("/Patient", json=patient)
except httpx.TransportError:
return build_ack(msh, "AE", "unreachable")
if response.is_success:
return build_ack(msh, "AA")
return build_ack(msh, "AE", error_text(response))
Integration engines
Lecture: Integration engines.
hl7-practice 09: set_value(message, path, value) -> str
Hard
The inverse of get_value: return a new message with the value at path replaced. Same path format as problem 05.
Rules:
1. Everything else stays exactly the same. Output joins segments with \r.
2. Segment appears more than once → change the first one.
3. Field has repeats → change only the first repeat, keep the others.
4. Field/component/subcomponent doesn't exist yet → pad with empty separators up to that position.
5. Segment doesn't exist yet → append a new segment at the end of the message.
6. MSH-1, MSH-2 → raise ValueError. MSH-n (n ≥ 3) is off by one, as in problem 05.
7. value contains no separators (no escaping needed).
PID-5.2 = 'ANH' : NGUYEN&VAN^AN^B → NGUYEN&VAN^ANH^B
PID-5.5 = 'DR' : NGUYEN&VAN^AN^B → NGUYEN&VAN^AN^B^^DR
PID-4.3 = 'Z' : PID-4 empty → ^^Z
PID-13 = 'X' : 0101~0202 → X~0202
ZPI-3 = 'VIP' : no ZPI → append 'ZPI|||VIP'
Write it in p09_set_value.py, then run python3 test_practice.py p09.
Reference solution
def _set_nested(text: str, nums: list[int], seps: str, value: str) -> str:
if not nums:
return value
parts = text.split(seps[0])
i = nums[0] - 1
parts += [""] * (i + 1 - len(parts)) # pad missing components/subcomponents
parts[i] = _set_nested(parts[i], nums[1:], seps[1:], value)
return seps[0].join(parts)
def set_value(message: str, path: str, value: str) -> str:
segment, numbers = path.split("-")
field_num, *sub_nums = [int(n) for n in numbers.split(".")]
if segment == "MSH" and field_num <= 2:
raise ValueError("MSH-1 and MSH-2 hold the separators and cannot be set")
rows = [line.split("|") for line in message.splitlines() if line]
row = next((r for r in rows if r[0] == segment), None)
if row is None:
row = [segment]
rows.append(row)
index = field_num - 1 if segment == "MSH" else field_num
row += [""] * (index + 1 - len(row)) # pad missing fields
repeats = row[index].split("~")
repeats[0] = _set_nested(repeats[0], sub_nums, "^&", value)
row[index] = "~".join(repeats)
return "\r".join("|".join(r) for r in rows)
mellp 25: Route by Type
Easy · routing · python-hl7
An interface engine receives everything on one port and sends each message on to the systems that care about it. Admits go to the bed board, lab results go to the chart, and a catch-all channel keeps whatever nobody claimed. The routing key is the message type in MSH-9.
def route(raw: str, table: dict[str, T], default: T | None = None) -> T
Read the message code (MSH-9.1) and trigger event (MSH-9.2) and look them up in table, in this order:
- The exact type,
"ADT^A01". - The wildcard for the message code,
"ADT^*". - The catch-all
"*".
Return the value of the first key that is present. If no key matches, return default when one was given, otherwise raise LookupError with the type ("ORM^O01") in its message. Table values are opaque: ports, tuples, names, anything, including values that are falsy.
Example 1:
Input: MSH-9 = "ADT^A01^ADT_A01"
table = {"ADT^A01": "bed-board", "ADT^*": "adt-archive", "*": "catch-all"}
Output: "bed-board"
Example 2:
Input: MSH-9 = "ADT^A08^ADT_A01", same table
Output: "adt-archive"
Explanation: no exact key, so the wildcard for ADT applies.
Example 3:
Input: MSH-9 = "ORM^O01^ORM_O01", table = {"ADT^*": 2575}
Output: LookupError("no route for ORM^O01")
Constraints:
rawis one message, segments separated by\r, starting with MSH.- MSH-9 always has at least the code and the trigger event. The message structure (MSH-9.3) plays no part in routing.
default=Nonemeans no default was given.- The table is not modified.
Follow-up: some routes depend on more than the type: ORU results for one facility go to a different lab system. How would you extend the table without turning it into a chain of if statements?
Hint
msg = hl7.parse(raw), then msg["MSH.F9.R1.C1"] and msg["MSH.F9.R1.C2"]. Test membership with in, not with the truthiness of table.get(key).
Write it in problems/25-route-by-type/solution.py, then run:
uv run pytest problems/25-*
Reference solution
from typing import TypeVar
import hl7
T = TypeVar("T")
def route(raw: str, table: dict[str, T], default: T | None = None) -> T:
message = hl7.parse(raw)
code = message["MSH.F9.R1.C1"]
message_type = f"{code}^{message['MSH.F9.R1.C2']}"
for key in (message_type, f"{code}^*", "*"):
if key in table:
return table[key]
if default is not None:
return default
raise LookupError(f"no route for {message_type}")
mellp 26: Clean It Up
Medium · transform · python-hl7
Two systems rarely agree on the details. The receiver wants its own application name in the header, names in capitals, sex coded from HL7 Table 0001, no Social Security numbers, and none of the sender's custom Z-segments. Everything else must pass through exactly as it came, because the receiver's parser is stricter than yours.
def transform(raw: str, receiving_app: str, receiving_facility: str) -> str
Return a copy of raw with these changes:
- MSH-5 (receiving application) and MSH-6 (receiving facility) are set to the arguments.
- PID-5.1 (family name) and PID-5.2 (given name) are upper-cased. Other components of PID-5 are untouched.
- PID-8 (administrative sex) is normalised to Table 0001, case-insensitively:
M,MALE,1becomeM;F,FEMALE,2becomeF; an empty value stays empty; anything else becomesU. - PID-19 (SSN) is blanked: the field stays, its value becomes empty.
- Segments whose name starts with
Zare removed. - Everything else is unchanged, character for character: segment order, the
\rafter every segment, MSH-2, empty fields, and the number of fields in every segment. A PID with fewer than 19 fields must not grow one.
Example 1:
Input: MSH|^~\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|C1|P|2.5\r
PID|1||12345^^^HOSP^MR||doe^jane^q||19800214|female\r
ZPI|VIP|Y\r
receiving_app="CHART", receiving_facility="EAST"
Output: MSH|^~\&|EPIC|HOSP|CHART|EAST|20260105083000||ADT^A01^ADT_A01|C1|P|2.5\r
PID|1||12345^^^HOSP^MR||DOE^JANE^q||19800214|F\r
Explanation: the middle name stays lower-case, the PID keeps its 8 fields, the ZPI is gone.
Example 2:
Input: PID|1||7||ROE^RICHARD||19700101|2|||||||||||123-45-6789|D1234\r (after an MSH)
Output: PID|1||7||ROE^RICHARD||19700101|F||||||||||||D1234\r
Explanation: PID-19 is emptied, PID-20 survives.
Example 3:
Input: MSH|...\rEVN|A08|20260105091500\r (no PID at all)
Output: the same message with only MSH-5 and MSH-6 changed
Constraints:
rawis one message: segments separated by\r, the last one followed by\r. The first segment is MSH with at least 12 fields.- Separators are the defaults: MSH-2 is
^~\&. - There is at most one PID and PID-5 does not repeat. A PID may have any number of fields, or there may be none.
- Names are ASCII.
Follow-up: the next receiver wants the same cleanup but a different sex table and keeps PID-19. How would you make the rules configuration instead of code, without writing a general-purpose mapping language?
Hint 1
The python-hl7 route: msg = hl7.parse(raw), msg.assign_field("CHART", "MSH", 1, 5), then str(msg), which ends with \r like the input. Three traps, all verified on python-hl7 0.4.5: assign_field on a field past the end of a segment appends empty fields to reach it, so blanking PID-19 grows a short PID; assigning to a component of a field that has none (PID-5 = SMITH) raises TypeError; and the segment must exist (KeyError: 'No PID segments').
Hint 2
The by-hand route: raw.split("\r"), then segment.split("|") and "|".join(...) back. Only touch indexes that exist. The trap is MSH: MSH-1 is the field separator itself, so after splitting the MSH segment on |, MSH-5 is at index 4. In every other segment, field n is at index n.
Write it in problems/26-clean-it-up/solution.py, then run:
uv run pytest problems/26-*
Reference solution
SEX_CODES = {"M": "M", "MALE": "M", "1": "M", "F": "F", "FEMALE": "F", "2": "F", "": ""}
def transform(raw: str, receiving_app: str, receiving_facility: str) -> str:
output = []
for segment in raw.split("\r"):
if segment.startswith("Z"):
continue
fields = segment.split("|")
if fields[0] == "MSH":
# MSH-1 is the "|" the split consumed, so MSH-n sits at index n - 1.
fields[4] = receiving_app
fields[5] = receiving_facility
elif fields[0] == "PID":
clean_pid(fields)
output.append("|".join(fields))
return "\r".join(output)
def clean_pid(fields: list[str]) -> None:
"""Edits the PID fields in place, touching only fields that already exist."""
if len(fields) > 5:
name = fields[5].split("^")
name[:2] = [part.upper() for part in name[:2]]
fields[5] = "^".join(name)
if len(fields) > 8:
fields[8] = SEX_CODES.get(fields[8].upper(), "U")
if len(fields) > 19:
fields[19] = ""
The broken message set
Lecture: The broken message set.
hl7-practice 12: Validate header
Easy
INT-103: The engine's queue is backing up because of junk messages. Block them at the door and return a list of error codes.
validate_header(message: str, expected_version: str = "2.5.1") -> list[str]
- First segment isn't
MSH→ return["NOT_MSH"]immediately. - Otherwise check in exactly this order, collecting every error:
BAD_ENCODING:MSH-2≠^~\&NO_MESSAGE_TYPE:MSH-9.1orMSH-9.2emptyNO_CONTROL_ID:MSH-10emptyBAD_PROCESSING_ID:MSH-11not one ofP,T,DVERSION_MISMATCH:MSH-12.1≠expected_version(MSH-12may have components, e.g.2.4^AUS&&ISO3166_1)- A missing field = empty. Valid →
[].
Write it in p12_validate_header.py, then run python3 test_practice.py p12.
Reference solution
It imports solutions/_hl7.py.
from solutions._hl7 import field, part, segments
def validate_header(message: str, expected_version: str = "2.5.1") -> list[str]:
segs = segments(message)
if not segs or segs[0][0] != "MSH":
return ["NOT_MSH"]
msh = segs[0]
errors = []
if field(msh, 2) != "^~\\&":
errors.append("BAD_ENCODING")
if not part(field(msh, 9), "^", 1) or not part(field(msh, 9), "^", 2):
errors.append("NO_MESSAGE_TYPE")
if not field(msh, 10):
errors.append("NO_CONTROL_ID")
if field(msh, 11) not in ("P", "T", "D"):
errors.append("BAD_PROCESSING_ID")
if part(field(msh, 12), "^", 1) != expected_version:
errors.append("VERSION_MISMATCH")
return errors
hl7-practice 14: Validate results (LOINC on ingest)
Medium
INT-202: Results go "missing" because of bad LOINC codes and nobody reports an error. Validate each OBX.
validate_results(message: str, known_loinc: set[str]) -> list[str]
For each OBX in order (<id> = OBX-1), check and collect every error:
1. OBX-3.3 ≠ LN → "OBX <id>: not LOINC"; otherwise if OBX-3.1 is not in known_loinc → "OBX <id>: unknown LOINC <code>"
2. OBX-2 = NM but OBX-5 doesn't parse as a number → "OBX <id>: non-numeric value"
3. OBX-11 empty → "OBX <id>: missing status"
Write it in p14_validate_results.py, then run python3 test_practice.py p14.
Reference solution
It imports solutions/_hl7.py.
from solutions._hl7 import all_of, field, part
def _is_number(text: str) -> bool:
try:
float(text)
return True
except ValueError:
return False
def validate_results(message: str, known_loinc: set[str]) -> list[str]:
errors = []
for obx in all_of(message, "OBX"):
sid = field(obx, 1)
code_field = field(obx, 3)
if part(code_field, "^", 3) != "LN":
errors.append(f"OBX {sid}: not LOINC")
elif part(code_field, "^", 1) not in known_loinc:
errors.append(f"OBX {sid}: unknown LOINC {part(code_field, '^', 1)}")
if field(obx, 2) == "NM" and not _is_number(field(obx, 5)):
errors.append(f"OBX {sid}: non-numeric value")
if not field(obx, 11):
errors.append(f"OBX {sid}: missing status")
return errors
mellp 13: Rule Book
Medium · validation · python-hl7
Every site has its own list of things an inbound message must get right before it is allowed in: a control ID to acknowledge, a patient that can be identified, a birth date that is a real date and not in the future. A message can be perfectly legal HL7 and still fail all of them (problem 14 checks the standard's structure; this one checks one site's business rules). Report every rule a message breaks, so the sender can fix them all in one round.
def validate(raw: str, today: datetime.date | None = None) -> list[str]
Return the IDs of the violated rules, in table order, each at most once. An empty list means the message passes. today defaults to date.today(); it exists so the tests are deterministic.
| ID | Applies to | Violated when |
|---|---|---|
MSH-10 |
all | the control ID is empty |
PID |
all | there is no PID segment (then no PID-x rule is reported) |
PID-3 |
all | no repetition of PID-3 has a non-empty ID (component 1) |
PID-5 |
all | the family name (PID-5.1) is empty |
PID-7 |
all | PID-7 is not empty, and its first 8 characters are not a real calendar date YYYYMMDD or that date is after today |
PID-8 |
all | PID-8 is not empty and not one of F M O U A N (HL7 Table 0001) |
PV1 |
ADT^A01 |
there is no PV1 segment |
OBX |
ORU^R01 |
there is no OBX segment |
"Applies to" is matched against MSH-9.1 and MSH-9.2.
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F\r"
"PV1|1|I|ICU^101^A\r"
Output: []
Example 2:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01||P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||^^^HOSP^MR||^JANE||19800230|X\r"
Output: ["MSH-10", "PID-3", "PID-5", "PID-7", "PID-8", "PV1"]
Explanation: no control ID; PID-3 names an assigning authority but no ID; no family name;
there is no 30 February; X is not in Table 0001; an admit needs a PV1.
Example 3:
Input: "MSH|^~\\&|LAB|HOSP|EPIC|HOSP|20260105083000||ORU^R01^ORU_R01|MSG00003|P|2.5\r"
"PID|1||~12345^^^HOSP^MR||DOE^JANE||20990101|F\r"
"OBR|1|ORD448^EPIC|LAB7731^LAB|24323-8^Comprehensive metabolic panel^LN\r"
today = date(2026, 1, 5)
Output: ["PID-7", "OBX"]
Explanation: the first repetition of PID-3 is empty but the second has an ID, which is fine.
A birth date in 2099 is in the future. A result needs at least one OBX.
Constraints:
- Segments end with
\rand the message uses the default delimiters|^~\&. - MSH is well-formed through MSH-12. There is at most one PID, and when it is there it has fields through PID-8.
- PID-7 and PID-8 hold a single value with no components.
Follow-up: these rules are hard-coded. A second sender needs PID-8 optional and the PV1 rule dropped. How would you turn the table into data, so one validator serves both senders?
Hint 1
Collect the segment names once ({str(segment[0]) for segment in msg} with python-hl7), then go down the table appending IDs. Put the four PID-x rules behind a single "is there a PID" check.
Hint 2
datetime.datetime.strptime(text, "%Y%m%d") raises ValueError for 19800230. In python-hl7, len(msg.segment("PID")(3)) is the number of repetitions of PID-3, and msg["PID.F3.R2.C1"] reads the ID of the second one.
Write it in problems/13-rule-book/solution.py, then run:
uv run pytest problems/13-*
Reference solution
import datetime
import hl7
SEXES = {"F", "M", "O", "U", "A", "N"} # HL7 Table 0001
def validate(raw: str, today: datetime.date | None = None) -> list[str]:
message = hl7.parse(raw)
present = {str(segment[0]) for segment in message}
message_type = f"{message['MSH.F9.R1.C1']}^{message['MSH.F9.R1.C2']}"
violated = []
if not message["MSH.F10"]:
violated.append("MSH-10")
if "PID" in present:
violated += patient_rules(message, today or datetime.date.today())
else:
violated.append("PID")
if message_type == "ADT^A01" and "PV1" not in present:
violated.append("PV1")
if message_type == "ORU^R01" and "OBX" not in present:
violated.append("OBX")
return violated
def patient_rules(message: hl7.Message, today: datetime.date) -> list[str]:
violated = []
repetitions = len(message.segment("PID")(3))
if not any(message[f"PID.F3.R{number}.C1"] for number in range(1, repetitions + 1)):
violated.append("PID-3")
if not message["PID.F5.R1.C1"]:
violated.append("PID-5")
birth = message["PID.F7"]
if birth and not is_past_date(birth[:8], today):
violated.append("PID-7")
sex = message["PID.F8"]
if sex and sex not in SEXES:
violated.append("PID-8")
return violated
def is_past_date(text: str, today: datetime.date) -> bool:
"""True for a real YYYYMMDD calendar date on or before today."""
try:
return datetime.datetime.strptime(text, "%Y%m%d").date() <= today
except ValueError:
return False
mellp 14: By the Book
Easy · validation · conformance · hl7apy
Problem 13 checked one site's business rules. The HL7 standard has rules of its own: each message structure lists which segments it requires, which are optional and how often each may repeat, and each version defines its own fields and data types. hl7apy ships those definitions for every version it supports. A real interface needs both kinds of check: a message can follow the standard to the letter and still be useless to you, or carry everything you need in a shape the standard does not allow.
def conforms(raw: str) -> bool
Return True when the message is valid for its own HL7 version (MSH-12) under hl7apy's strict validation, and False otherwise, including when hl7apy cannot parse it at all.
Example 1:
Input: "MSH|^~\\&|EPIC|HOSP|LAB|HOSP|20260105083000||ADT^A01^ADT_A01|MSG00001|P|2.5\r"
"EVN|A01|20260105083000\r"
"PID|1||12345^^^HOSP^MR||DOE^JANE^Q||19800214|F|||123 MAIN ST^^SPRINGFIELD^IL^62701^USA||(217)555-0142\r"
"PV1|1|I|ICU^101^A||||1234^WELBY^MARCUS\r"
Output: True
Example 2:
Input: the same message without its PV1
Output: False
Explanation: ADT_A01 requires a PV1. hl7apy raises ValidationError: Missing required child ADT_A01.PV1
Example 3:
Input: a 2.5 ORU^R01 lab result with no PID segment
Output: True
Explanation: the patient group is optional in ORU_R01. Problem 13's site rules reject this message.
Every case in the tests, with the reason for its verdict:
| Message | Verdict | Why |
|---|---|---|
admit (ADT^A01), version 2.3.1, 2.4, 2.5 or 2.5.1 |
True |
all required segments present, each once |
update (ADT^A08^ADT_A01) |
True |
an A08 uses the admit's structure, ADT_A01 |
lab result (ORU^R01) |
True |
MSH, PID, OBR and OBX in a valid ORU_R01 shape |
| lab result with no OBX | True |
the observation group is optional in ORU_R01 |
| lab result with no PID | True |
the patient group is optional in ORU_R01 |
| admit with an OBX after the PV1 | True |
ADT_A01 allows OBX segments after the visit |
admit with PID-8 Q |
True |
strict validation reports a code outside an HL7 table as a warning, not an error |
| admit with a birth date in 2099 | True |
the standard does not know what day it is |
version 2.3 admit with MSH-9 ADT^A01 |
True |
in 2.3, MSH-9 has two components |
| admit without PV1, or without EVN | False |
both are required in ADT_A01 |
| admit with two PID segments | False |
PID may appear only once in ADT_A01 |
| lab result with no OBR | False |
every order observation group in ORU_R01 needs its OBR |
| empty MSH-10 | False |
the message control ID is required |
| empty PID-3 | False |
the patient identifier list is required in 2.5 |
PID-7 19800230 |
False |
there is no 30 February, so it is not a valid date value |
version 2.3 admit with MSH-9 ADT^A01^ADT_A01 |
False |
the third component of MSH-9 (message structure) does not exist in 2.3 |
MSH-12 9.9 |
False |
there is no such HL7 version |
MSH-9 XYZ^Q99^XYZ_Q99 |
False |
there is no such message type |
MSH-9.3 ADT_A01 on the segments of a lab result |
False |
the segments do not fit the declared structure |
segments separated by \n |
False |
HL7 v2 separates segments with \r |
"" or "this is not hl7" |
False |
not a message at all |
Constraints:
- The tests run hl7apy as installed in this repo, on Python 3.12.
- Messages use the default delimiters
|^~\&.
Follow-up: validate() raises only the first error. Given a report_file path it also writes every error and warning it found to that file (and still raises). When would you keep the full report, and what would you send back in MSA-3?
Hint 1
from hl7apy.consts import VALIDATION_LEVEL
from hl7apy.parser import parse_message
message = parse_message(raw, validation_level=VALIDATION_LEVEL.STRICT)
message.validate() # True, or raises the first error it found
Hint 2
Problems show up both while parsing and while validating. hl7apy's own exceptions derive from hl7apy.exceptions.HL7apyException, but a malformed date raises a plain ValueError.
Write it in problems/14-by-the-book/solution.py, then run:
uv run pytest problems/14-*
Reference solution
from hl7apy.consts import VALIDATION_LEVEL
from hl7apy.exceptions import HL7apyException
from hl7apy.parser import parse_message
def conforms(raw: str) -> bool:
try:
message = parse_message(raw, validation_level=VALIDATION_LEVEL.STRICT)
return message.validate() # True, or raises ValidationError
except (HL7apyException, ValueError): # a malformed date raises a plain ValueError
return False
mellp statements and solutions are copied from mellp at commit 5d8e459.
Course content © 2026 HeyItWorked. All rights reserved.
Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.