From b8f84eba72cac70cd05667f5dcb2e29d2e38676c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 01:00:58 -0600 Subject: [PATCH 1/7] Strict validation compares MSH-9.2 before a same-code borrow keeps the any-segment exemption BACKLOG #5920 step 1. A structure borrowed through MSH-9.3 under the message's own code (MFN^M02^MFN_M01) kept the any-HL7-segment exemption. It now keeps it only where the structure is _, or where MSH-9.2 is a non-empty trigger event hl7apy's tables give no structure of its own (PGL^PC7^PGL_PC6). MFN^M02, MFN^M05 and an empty MSH-9.2 borrow are now refused. --- docs/HL7-VALIDATION.md | 7 +++--- messagefoundry/parsing/validate.py | 32 ++++++++++++++++++------- tests/test_validate_dropped_segments.py | 28 +++++++++++++++++----- 3 files changed, 50 insertions(+), 17 deletions(-) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index da3f53f354..71bd0f2bf2 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -88,9 +88,10 @@ refused, and so is a dropped bare defined ID with no field separator (a lone `OR `MFN_M01`); a bare line `hl7apy` placed is not. A dropped `MSH`, `DSC`, `MSA`, `ERR`, `QAK` or `MFA` line is refused too. A batch or file envelope line (`BHS`, `BTS`, `FHS`, `FTS`) is exempted like any other defined segment, because batch splitting can leave one on a message. Every dropped segment is refused where MSH-9.3 -borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`); a structure -borrowed under the same message code (`MFN^M02^MFN_M01`) still gets the exemption, since MSH-9.2 -is not compared. Where the slot is required and its group is present, `hl7apy`'s own check +borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`), and where it +borrows one under the same code for a trigger event in MSH-9.2 that has a structure of its own in +`hl7apy`'s tables (`MFN^M02^MFN_M01`, since `MFN_M02` is one). A same-code borrow for a trigger +event with no structure of its own there (`PGL^PC7^PGL_PC6`) keeps the exemption. Where the slot is required and its group is present, `hl7apy`'s own check refuses at least some such messages, since the slot is never filled (`Missing required child ... ANYHL7SEGMENT`; `MFN_M03` for one), but not where the slot is one alternative of a choice: a `PRR_PC5` order with its `OBR` passes. Where the slot sits inside a nested group (at least the diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index 85dd1c58f8..cdd6f5699e 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -40,8 +40,10 @@ refused, and so is a dropped MSH, DSC, MSA, ERR, QAK or MFA line (``_NEVER_EXEMPT`` says why). The exemption is per structure, not per slot: it does not count against the slot's cardinality or position. It holds only where MSH-9.1 names the structure's own message code, so a -structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none; one -borrowed under the same code (``MFN^M02^MFN_M01``) still gets it. Where the slot sits inside a +structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none. One +borrowed under the same code gets none either where the trigger event in MSH-9.2 has a structure +of its own in hl7apy's tables (``MFN^M02^MFN_M01``, since MFN_M02 is one); where it has none +(``PGL^PC7^PGL_PC6``), the borrowed structure keeps the exemption. Where the slot sits inside a nested group (at least PRR_PC5 and PPV_PCA), such a segment can still break hl7apy's grouping of what follows. Segment order is not checked as such: hl7apy keeps each segment where the message has it, so an out-of-order message may pass. @@ -356,13 +358,27 @@ def _exempts_defined_segments(message: Any) -> bool: hl7apy takes the structure from MSH-9.3 when one is given, so ``ADT^A01^MFN_M01`` would borrow MFN_M01's slot for an ADT body. The exemption holds only where MSH-9.1 names the structure's own message code, which fails closed on a structure borrowed under another code. - One borrowed under the same code (``MFN^M02^MFN_M01``) still gets it: MSH-9.2 is not - compared, since one structure can serve several trigger events (PGL_PC6 serves PC6 to PC8, - for one).""" + Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1): the structure is the + message's own when it is ``_``, and a borrow keeps the exemption only for + a non-empty trigger event hl7apy's tables give no structure of its own. So + ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, while ``PGL^PC7^PGL_PC6`` keeps + it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one).""" code = message.msh.msh_9.msh_9_1.to_er7() - return code == message.name.split("_", 1)[0] and _has_any_segment_slot( - message.name, message.classname, message.version - ) + if code != message.name.split("_", 1)[0]: + return False + if not _has_any_segment_slot(message.name, message.classname, message.version): + return False + event = message.msh.msh_9.msh_9_2.to_er7() + own = f"{code}_{event}" + return own == message.name or (bool(event) and not _has_structure(own, message.version)) + + +@cache +def _has_structure(name: str, hl7_version: str) -> bool: + """True if hl7apy's tables for ``hl7_version`` define the message structure ``name``.""" + import hl7apy + + return name in hl7apy.load_library(hl7_version).MESSAGES # Six IDs a dropped line of which is refused even in a structure with the "any HL7 segment" slot diff --git a/tests/test_validate_dropped_segments.py b/tests/test_validate_dropped_segments.py index 8c72bd7f33..6876fd39c4 100644 --- a/tests/test_validate_dropped_segments.py +++ b/tests/test_validate_dropped_segments.py @@ -195,13 +195,29 @@ def test_batch_envelope_lines_on_a_split_member_keep_the_exemption() -> None: assert result.unvalidated_segments == (("BTS", 4), ("BHS", 5), ("FTS", 6), ("FHS", 7)) -def test_a_structure_borrowed_under_the_same_message_code_keeps_the_exemption() -> None: - """MSH-9.2 is not compared, so ``MFN^M02^MFN_M01`` is exempted as ``MFN^M01`` is. - - This pins the current behaviour the module docstring states: only a borrow under another - message code (``ADT^A01^MFN_M01``) loses the exemption.""" - borrowed = _MFN_M01.replace("MFN^M01^MFN_M01", "MFN^M02^MFN_M01") +@pytest.mark.parametrize("msh_9", ["MFN^M02^MFN_M01", "MFN^M05^MFN_M01", "MFN^^MFN_M01"]) +def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemption( + msh_9: str, +) -> None: + """MSH-9.2 is compared (BACKLOG #5920 step 1): MFN_M02 and MFN_M05 are structures of their + own, so borrowing MFN_M01's slot for either is refused, as is a borrow with no trigger event.""" + borrowed = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(borrowed + "\rORC|NW|ORD1\r" + _PV1) + assert not result.ok + assert result.errors == [ + "segment ORC at line 4 has no place in this message's structure (and 1 more)" + ] + assert result.unvalidated_segments == () + + +@pytest.mark.parametrize("msh_9", ["MFN^M01^MFN_M01", "MFN^M01", "MFN^M14^MFN_M01"]) +def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( + msh_9: str, +) -> None: + """Control for the test above: the structure MSH-9.1 and MSH-9.2 name keeps it, and so does + a same-code borrow for an event hl7apy's tables give no structure of its own (no MFN_M14).""" + message = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) + result = validate(message + "\rORC|NW|ORD1\r" + _PV1) assert result.ok, result.errors assert result.unvalidated_segments == (("ORC", 4), ("PV1", 5)) From 6417ba287b0a6f30f27e78e75e6f8242d9c70ec7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 01:02:44 -0600 Subject: [PATCH 2/7] Batch delivery reads the head's MSH-10 from its first line, not a full parse BACKLOG #5919 step 1. The batch caller ran Message.parse on the whole head member to read MSH-10 for BHS-11. head_control_id in parsing/split.py checks the escape budget on the whole text, as the parse does first, and parses the first line alone where that reads MSH-10 as the full parse does; every other head is parsed in full, so it reads or raises as before. wiring_runner.py changes only the read at the batch head. --- messagefoundry/parsing/split.py | 50 ++++++++++++-- messagefoundry/pipeline/wiring_runner.py | 14 ++-- tests/test_encode_batch.py | 84 +++++++++++++++++++++++- tests/test_outbound_batch.py | 50 ++++++++++---- 4 files changed, 176 insertions(+), 22 deletions(-) diff --git a/messagefoundry/parsing/split.py b/messagefoundry/parsing/split.py index 3848de25c2..a517ccc15a 100644 --- a/messagefoundry/parsing/split.py +++ b/messagefoundry/parsing/split.py @@ -40,12 +40,18 @@ filled_default_collides, ) from messagefoundry.parsing.message import COLLIDING_DELIMITERS_WRITE, Message -from messagefoundry.parsing.peek import enforce_expansion_budget, normalize, starts_with_msh +from messagefoundry.parsing.peek import ( + enforce_expansion_budget, + normalize, + parse_or_refuse, + starts_with_msh, +) from messagefoundry.parsing.sniff import _LEADING_WS_STR __all__ = [ "batch_member_collides", "encode_batch", + "head_control_id", "split_batch", "split_batch_bytes", "one_message_bytes", @@ -493,9 +499,10 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]: budget (:func:`~messagefoundry.parsing.peek.enforce_expansion_budget`, ASVS 1.3.3), run on ``norm`` itself, the text encode_batch frames: a head a parse refuses for its escapes raises the same ``HL7PeekError`` here, whatever its caller checked. On the delivery path that text is - the hydrated head, and the caller's own parse of the head's stored payload checks the same - budget first, so there this is a second check, not the only one. What else a parse checks in the - rest of the head is not checked: at least a later header line too short to read.""" + the hydrated head, and the caller's own read of the head's stored payload + (:func:`head_control_id`) checks the same budget first, so there this is a second check, not + the only one. What else a parse checks in the rest of the head is not checked: at least a + later header line too short to read.""" line = _first_line_head(norm) # The parse's _encoding_chars returns exactly what _extract_separators reads from this line, # a short MSH-2 filled with the same defaults (BACKLOG #5972), so any MSH line the parse would @@ -512,6 +519,41 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]: return field_sep, comp_sep, rep_sep, esc, sub_sep +#: A header line after the first that is too short for the parse to read (``_builtin_hl7.parse`` +#: refuses one): a line that is a header ID alone, or the text's last line once the parse's strip +#: leaves only a header ID there. +_SHORT_LATER_HEADER = re.compile(r"\r(?:MSH|BHS|FHS)(?:\r|\s*\Z)") + + +def head_control_id(text: str) -> str | None: + """MSH-10 of a batch's head member as stored, what ``Message.parse(text).control_id`` + returns, read from its first line alone where that gives the same result (BACKLOG #5919). + + A full parse of a large head to read one field copied the whole head. For a head whose first + line opens with ``MSH`` after whitespace and holds MSH-1 and one more character, the parse's + escape budget (:func:`~messagefoundry.parsing.peek.enforce_expansion_budget`) is checked on + the whole text, as the parse checks it first, and that one line is parsed. The MSH segment is + split from its own line and separators alone, so its MSH-10 is the full parse's. Every other + head, and one the full parse could refuse for a later line or read differently, is parsed in + full, so it reads or raises exactly as the parse does: at least an ``FHS``/``BHS``-led or + non-HL7 head, one with a later header line too short to read, and one whose first line ends in + whitespace, which the parse's strip keeps or drops depending on what follows.""" + norm = normalize(text) + end = len(norm) + start = _whitespace_end(norm, 0, end) + cr = norm.find("\r", start) + stop = end if cr == -1 else cr + if ( + norm.startswith(_MSH, start) + and stop - start >= _SEPARATORS_WIDTH + and not norm[stop - 1].isspace() + and _SHORT_LATER_HEADER.search(norm, stop) is None + ): + enforce_expansion_budget(norm) + return Message(parse_or_refuse(norm[start:stop])).control_id + return Message.parse(norm).control_id + + def _framed(text: str) -> tuple[str, ...]: """The pieces that frame one member's ``text`` in a batch: its segments with no leading or trailing CR, then one CR. ``text`` itself when it already has that shape, so the common diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 45070a4da3..cbc135a155 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -178,7 +178,7 @@ b64_head, text_sniff_head, ) -from messagefoundry.parsing.split import batch_member_collides +from messagefoundry.parsing.split import batch_member_collides, head_control_id from messagefoundry.pipeline.alerts import REMINDER_SECONDS, AlertSink, LoggingAlertSink from messagefoundry.pipeline.cluster import ClusterCoordinator, NullCoordinator from messagefoundry.pipeline.dryrun import TransformOutcome, route_only, transform_one @@ -12078,7 +12078,7 @@ async def _deliver_coalesced_batch( # payload-agnostic, ADR 0004, so a non-hl7v2 feed can reach here) routes to the internal-error # policy below (dead-letter / STOP) instead of stranding every claimed row INFLIGHT forever with # no send and no disposition. Members are carried VERBATIM (the head too — never re-encoded); only - # the head is PARSED here, for the BHS-11 control id. How encode_batch reads the BHS + # the head's MSH-10 is READ here, for the BHS-11 control id. How encode_batch reads the BHS # separators, parsing the head where its MSH line alone does not hold them, is in # parsing/split.py, _head_separators (BACKLOG #5919). refused: list[_RefusedMember] = [] @@ -12169,11 +12169,13 @@ async def _deliver_coalesced_batch( first = kept[0] # the envelope's head is the first member that survived # The head's own fields: a non-HL7 head faults here, and it is this member's. current = first.id - # This parse and encode_batch below each run in a thread (BACKLOG #5706). Both scale + # This read and encode_batch below each run in a thread (BACKLOG #5706). Both scale # with the members' size, and on the event loop a large member would stall every - # lane, listener and the API while it parsed. - parsed = await asyncio.to_thread(Message.parse, first.payload) - control_id = parsed.control_id or first.id # stable + # lane, listener and the API while it was read. head_control_id reads MSH-10 as a + # parse of the head does, parsing only its first line where that reads the same + # (BACKLOG #5919). + head_id = await asyncio.to_thread(head_control_id, first.payload) + control_id = head_id or first.id # stable timestamp = _hl7_batch_timestamp(first.created_at) # encode_batch reads the HYDRATED head's MSH-1 and MSH-2 and frames every member in # one call, so a fault inside it cannot be told apart by member; the send is the diff --git a/tests/test_encode_batch.py b/tests/test_encode_batch.py index cb30fcb4e6..c8df13a11f 100644 --- a/tests/test_encode_batch.py +++ b/tests/test_encode_batch.py @@ -17,7 +17,7 @@ from messagefoundry.parsing import HL7PeekError, encode_batch, split_batch from messagefoundry.parsing.message import COLLIDING_DELIMITERS_WRITE, Message from messagefoundry.parsing.peek import normalize -from messagefoundry.parsing.split import batch_member_collides +from messagefoundry.parsing.split import batch_member_collides, head_control_id M1 = "MSH|^~\\&|A|B|C|D|20260101010101||ADT^A01|MSG1|P|2.5.1\rPID|1||100||DOE^JOHN\r" M2 = "MSH|^~\\&|A|B|C|D|20260101010102||ADT^A02|MSG2|P|2.5.1\rPID|1||200||ROE^JANE\r" @@ -296,3 +296,85 @@ def test_the_head_separators_match_the_parser_over_random_heads() -> None: def test_each_member_is_framed_with_one_trailing_cr(member: str, framed: str) -> None: env = encode_batch([M1, member], control_id="1", timestamp=_TS) assert env == "BHS|^~\\&|||||" + _TS + "||||1\r" + M1 + framed + "BTS|2\r" + + +# --- BACKLOG #5919 step 1: the delivery reads the head's MSH-10 for BHS-11 without a full parse --- + + +def _parsed_control_id(head: str) -> tuple[str | None, ...]: + try: + return (Message.parse(head).control_id,) + except ValueError as exc: # HL7PeekError is one + return type(exc).__name__, str(exc) + + +def _read_control_id(head: str) -> tuple[str | None, ...]: + try: + return (head_control_id(head),) + except ValueError as exc: + return type(exc).__name__, str(exc) + + +@pytest.mark.parametrize("head", [M1, M1.replace("\r", "\n"), " \r" + M1]) +def test_the_head_control_id_is_read_without_a_full_parse( + monkeypatch: pytest.MonkeyPatch, head: str +) -> None: + monkeypatch.setattr(Message, "parse", staticmethod(_no_parse)) + assert head_control_id(head) == "MSG1" + # Negative control: an envelope-led head is parsed in full. + with pytest.raises(AssertionError, match="parsed a member"): + head_control_id("BHS|^~\\&\r" + head) + + +@pytest.mark.parametrize( + "head", + [ + pytest.param("MSH|^~\\&|A|B|C|D|T||ADT^A01|ID1 \rPID|1", id="first-line-trailing-space"), + pytest.param("MSH|^~\\&|A|B|C|D|T||ADT^A01|ID1\rMSH", id="later-short-header"), + pytest.param("MSH|^~\\&|A|B|C|D|T||ADT^A01|ID1\rBHS \r", id="later-short-header-at-end"), + pytest.param("MSH|^~\\&|A|B|C|D|T||ADT^A01|" + "\\.sp512\\" * 40_000, id="escape-budget"), + pytest.param("MSH|^~\\&|A|B|C|D|T||ADT^A01|I\\T\\D~2", id="escaped-repeating-id"), + pytest.param("NOT-HL7|X\r", id="non-hl7"), + pytest.param("MSH|", id="short-header"), + ], +) +def test_the_head_control_id_reads_or_refuses_as_a_parse_does(head: str) -> None: + assert _read_control_id(head) == _parsed_control_id(head) + + +def _random_control_head(rng: random.Random) -> str: + """A head with an MSH-10 of noise, then noise lines that may be short headers or blank.""" + lead_ws = "".join(rng.choice(" \t\r\n") for _ in range(rng.choice((0, 0, 0, 1, 2)))) + lead = rng.choice(("MSH", "MSH", "MSH", "MSH", "BHS", "FHS", "PID", "MS")) + first = lead + rng.choice(("|^~\\&", "|^~\\&", "#^~\\&", "|^", "|")) + first += "|A|B|C|D|T||ADT^A01|" + "".join(rng.choice("AB^~\\&| \t") for _ in range(5)) + tail = "".join( + rng.choice(("\r", "\n", "\r\n")) + rng.choice(("PID|1", "MSH", "BHS", "FHS ", "", " ")) + for _ in range(rng.randrange(0, 3)) + ) + return lead_ws + first + tail + + +def test_the_head_control_id_matches_the_parser_over_random_heads( + monkeypatch: pytest.MonkeyPatch, +) -> None: + rng = random.Random(59191) + heads = [_random_control_head(rng) for _ in range(5000)] + expected = {h: _parsed_control_id(h) for h in heads} + full_parses: list[object] = [] + real_parse = Message.parse + + def counting_parse(raw: str | bytes) -> Message: + full_parses.append(raw) + return real_parse(raw) + + monkeypatch.setattr(Message, "parse", staticmethod(counting_parse)) + for head in heads: + assert _read_control_id(head) == expected[head], repr(head) + # Positive controls for the generator: heads read and heads refused, heads with a later header + # line too short to read, and enough heads read from their first line alone. + read = [h for h in heads if len(expected[h]) == 1] + assert len(read) >= 1000, len(read) + assert len(heads) - len(read) >= 100 + assert sum(_has_a_short_later_header(h) for h in heads) >= 100 + assert len(heads) - len(full_parses) >= 500, len(full_parses) diff --git a/tests/test_outbound_batch.py b/tests/test_outbound_batch.py index beed19650f..c6fae4e426 100644 --- a/tests/test_outbound_batch.py +++ b/tests/test_outbound_batch.py @@ -25,6 +25,7 @@ from messagefoundry.config.settings import EgressSettings from messagefoundry.config.wiring import Registry from messagefoundry.framing import MLLP_CODEC +from messagefoundry.parsing.message import Message from messagefoundry.parsing.split import split_batch from messagefoundry.pipeline import stage_dispatcher, wiring_runner from messagefoundry.pipeline.alerts import LoggingAlertSink @@ -487,6 +488,33 @@ async def test_head_carried_verbatim(store: Any) -> None: assert "PID|1||100||DOE^P1" in env and "MSG1" in env +async def test_the_head_control_id_is_read_without_a_full_parse( + store: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + # BACKLOG #5919 step 1: BHS-11 is the head's MSH-10, read from its first line, so a large + # head is not parsed in full to read one field. + await _enqueue(store, 2) + runner = _runner(store) + rec = _Recorder() + _wire_batch(runner, rec, BatchConfig(max_count=5, max_wait_ms=1)) + parses: list[object] = [] + real_parse = Message.parse + + def counting_parse(raw: str | bytes) -> Message: + parses.append(raw) + return real_parse(raw) + + monkeypatch.setattr(Message, "parse", staticmethod(counting_parse)) + head = await store.claim_next_fifo(DEST) + await runner._process_delivery_batch(DEST, head, runner._batch[DEST]) + assert parses == [] + env = rec.sent[0] + assert env.split("\r", 1)[0].split("|")[10] == "MSG1" # BHS-11, as a parse reads it + # Negative control: the patch sees a parse when one happens. + Message.parse(_msg(1)) + assert len(parses) == 1 + + # --- count trigger: max_count caps a batch even when more are available -------------------------- @@ -1077,11 +1105,11 @@ async def _claim_then_halt(name: str, *args: Any, **kwargs: Any) -> Any: assert await real_claim(DEST) is None # rescheduled: the head is not due yet -async def test_the_batch_head_is_parsed_off_the_event_loop( +async def test_the_batch_head_is_read_off_the_event_loop( store: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - """The head member's parse for the BHS control id runs in a worker thread, not on the event - loop, so a large member cannot stall every other lane while it parses.""" + """The head member's read for the BHS control id runs in a worker thread, not on the event + loop, so a large member cannot stall every other lane while it is read.""" import threading await _enqueue(store, 2) @@ -1089,18 +1117,18 @@ async def test_the_batch_head_is_parsed_off_the_event_loop( rec = _Recorder() _wire_batch(runner, rec, BatchConfig(max_count=5, max_wait_ms=1)) loop_thread = threading.get_ident() - parse_threads: list[int] = [] - real_parse = wiring_runner.Message.parse + read_threads: list[int] = [] + real_read = wiring_runner.head_control_id - def _recording_parse(raw: str | bytes) -> Any: - parse_threads.append(threading.get_ident()) - return real_parse(raw) + def _recording_read(text: str) -> str | None: + read_threads.append(threading.get_ident()) + return real_read(text) - monkeypatch.setattr(wiring_runner.Message, "parse", _recording_parse) + monkeypatch.setattr(wiring_runner, "head_control_id", _recording_read) head = await store.claim_next_fifo(DEST) await runner._process_delivery_batch(DEST, head, runner._batch[DEST]) - assert len(rec.sent) == 1 # the control: the batch did go out, so the head was parsed - assert parse_threads and loop_thread not in parse_threads + assert len(rec.sent) == 1 # the control: the batch did go out, so the head was read + assert read_threads and loop_thread not in read_threads async def test_a_pause_that_lands_while_the_envelope_is_framed_sends_nothing( From 46cf430a933d86c314dd749645ffd808f132ba90 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 01:54:09 -0600 Subject: [PATCH 3/7] Review round 1: fail closed on odd MSH-9.2, keep no sender text in a cache BACKLOG #5920 and #5919. The structure lookup is cached by version alone, so a sender's MSH-9.2 is never kept. A same-code borrow keeps the exemption only for an event of three capital letters or digits, so a lower-case, padded or blank event fails closed. The rule is stated once, in _exempts_defined_segments; the module docstring and HL7-VALIDATION.md point to it. PGL^PC7^PGL_PC6 is pinned in 2.5 with a 2.5.1 control. _SHORT_LATER_HEADER is built from HEADER_IDS. The _head_separators docstring no longer calls its budget check a second one on hydrated text. Changelog fragment added; a stale test comment fixed. --- ...-same-code-borrow-no-exemption.security.md | 6 +++ docs/HL7-VALIDATION.md | 8 ++-- messagefoundry/parsing/split.py | 10 ++--- messagefoundry/parsing/validate.py | 28 ++++++++----- tests/test_delivery_document_reattach.py | 4 +- tests/test_validate_dropped_segments.py | 39 ++++++++++++++++++- 6 files changed, 72 insertions(+), 23 deletions(-) create mode 100644 changelog.d/5920-same-code-borrow-no-exemption.security.md diff --git a/changelog.d/5920-same-code-borrow-no-exemption.security.md b/changelog.d/5920-same-code-borrow-no-exemption.security.md new file mode 100644 index 0000000000..7753887ff0 --- /dev/null +++ b/changelog.d/5920-same-code-borrow-no-exemption.security.md @@ -0,0 +1,6 @@ +- **Strict validation compares MSH-9.2 before a borrowed "any HL7 segment" structure keeps its + exemption.** A message that names such a structure in MSH-9.3 under its own message code, as + `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in + `unvalidated_segments`. Where MSH-9.2 names a trigger event that has a structure of its own in + `hl7apy`'s tables, or is not three capital letters or digits, they are now refused. + (`BACKLOG #5920`) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index 71bd0f2bf2..f591cf6960 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -88,10 +88,10 @@ refused, and so is a dropped bare defined ID with no field separator (a lone `OR `MFN_M01`); a bare line `hl7apy` placed is not. A dropped `MSH`, `DSC`, `MSA`, `ERR`, `QAK` or `MFA` line is refused too. A batch or file envelope line (`BHS`, `BTS`, `FHS`, `FTS`) is exempted like any other defined segment, because batch splitting can leave one on a message. Every dropped segment is refused where MSH-9.3 -borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`), and where it -borrows one under the same code for a trigger event in MSH-9.2 that has a structure of its own in -`hl7apy`'s tables (`MFN^M02^MFN_M01`, since `MFN_M02` is one). A same-code borrow for a trigger -event with no structure of its own there (`PGL^PC7^PGL_PC6`) keeps the exemption. Where the slot is required and its group is present, `hl7apy`'s own check +borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). A borrow under +the same code is also held to MSH-9.2, so `MFN^M02^MFN_M01` is refused because `MFN_M02` is a +structure of its own; the exact rule is in `_exempts_defined_segments` in +[`validate.py`](../messagefoundry/parsing/validate.py). Where the slot is required and its group is present, `hl7apy`'s own check refuses at least some such messages, since the slot is never filled (`Missing required child ... ANYHL7SEGMENT`; `MFN_M03` for one), but not where the slot is one alternative of a choice: a `PRR_PC5` order with its `OBR` passes. Where the slot sits inside a nested group (at least the diff --git a/messagefoundry/parsing/split.py b/messagefoundry/parsing/split.py index a517ccc15a..766efac7bc 100644 --- a/messagefoundry/parsing/split.py +++ b/messagefoundry/parsing/split.py @@ -499,10 +499,10 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]: budget (:func:`~messagefoundry.parsing.peek.enforce_expansion_budget`, ASVS 1.3.3), run on ``norm`` itself, the text encode_batch frames: a head a parse refuses for its escapes raises the same ``HL7PeekError`` here, whatever its caller checked. On the delivery path that text is - the hydrated head, and the caller's own read of the head's stored payload - (:func:`head_control_id`) checks the same budget first, so there this is a second check, not - the only one. What else a parse checks in the rest of the head is not checked: at least a - later header line too short to read.""" + the hydrated head. The caller's own read (:func:`head_control_id`) checks the same budget on + the head's stored payload, which is other text wherever a document was re-attached, so on + the hydrated text this check is the one that runs. What else a parse checks in the rest of + the head is not checked: at least a later header line too short to read.""" line = _first_line_head(norm) # The parse's _encoding_chars returns exactly what _extract_separators reads from this line, # a short MSH-2 filled with the same defaults (BACKLOG #5972), so any MSH line the parse would @@ -522,7 +522,7 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]: #: A header line after the first that is too short for the parse to read (``_builtin_hl7.parse`` #: refuses one): a line that is a header ID alone, or the text's last line once the parse's strip #: leaves only a header ID there. -_SHORT_LATER_HEADER = re.compile(r"\r(?:MSH|BHS|FHS)(?:\r|\s*\Z)") +_SHORT_LATER_HEADER = re.compile(r"\r(?:" + "|".join(map(re.escape, HEADER_IDS)) + r")(?:\r|\s*\Z)") def head_control_id(text: str) -> str | None: diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index cdd6f5699e..ca11738a4e 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -41,9 +41,8 @@ The exemption is per structure, not per slot: it does not count against the slot's cardinality or position. It holds only where MSH-9.1 names the structure's own message code, so a structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none. One -borrowed under the same code gets none either where the trigger event in MSH-9.2 has a structure -of its own in hl7apy's tables (``MFN^M02^MFN_M01``, since MFN_M02 is one); where it has none -(``PGL^PC7^PGL_PC6``), the borrowed structure keeps the exemption. Where the slot sits inside a +borrowed under the same code is also held to MSH-9.2 (``MFN^M02^MFN_M01`` gets none), by the rule +:func:`_exempts_defined_segments` states. Where the slot sits inside a nested group (at least PRR_PC5 and PPV_PCA), such a segment can still break hl7apy's grouping of what follows. Segment order is not checked as such: hl7apy keeps each segment where the message has it, so an out-of-order message may pass. @@ -360,9 +359,10 @@ def _exempts_defined_segments(message: Any) -> bool: structure's own message code, which fails closed on a structure borrowed under another code. Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1): the structure is the message's own when it is ``_``, and a borrow keeps the exemption only for - a non-empty trigger event hl7apy's tables give no structure of its own. So - ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, while ``PGL^PC7^PGL_PC6`` keeps - it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one).""" + a trigger event of exactly three capital letters or digits that hl7apy's tables give no + structure of its own. So ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, nor + does an empty, lower-case or padded event, while ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one + structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one).""" code = message.msh.msh_9.msh_9_1.to_er7() if code != message.name.split("_", 1)[0]: return False @@ -370,15 +370,23 @@ def _exempts_defined_segments(message: Any) -> bool: return False event = message.msh.msh_9.msh_9_2.to_er7() own = f"{code}_{event}" - return own == message.name or (bool(event) and not _has_structure(own, message.version)) + if own == message.name: + return True + return _TRIGGER_EVENT.fullmatch(event) is not None and own not in _structures(message.version) + + +#: The shape of a trigger event a same-code borrow may keep the exemption for; any other value, +#: such as ``m02`` or ``M02 `` for an event that has its own structure, fails closed. +_TRIGGER_EVENT = re.compile(r"[A-Z0-9]{3}") +# Keyed by version alone, so a sender's MSH-9.2 text is never kept. @cache -def _has_structure(name: str, hl7_version: str) -> bool: - """True if hl7apy's tables for ``hl7_version`` define the message structure ``name``.""" +def _structures(hl7_version: str) -> frozenset[str]: + """The message structures hl7apy's tables for ``hl7_version`` define.""" import hl7apy - return name in hl7apy.load_library(hl7_version).MESSAGES + return frozenset(hl7apy.load_library(hl7_version).MESSAGES) # Six IDs a dropped line of which is refused even in a structure with the "any HL7 segment" slot diff --git a/tests/test_delivery_document_reattach.py b/tests/test_delivery_document_reattach.py index 861c2f30f0..60393e7a15 100644 --- a/tests/test_delivery_document_reattach.py +++ b/tests/test_delivery_document_reattach.py @@ -884,8 +884,8 @@ async def _hydrate(payload: str, message_id: str) -> str: async def test_a_non_hl7_head_names_the_head(store: MessageStore) -> None: - # Vault BACKLOG #5100: the head's parse for BHS-11 is that member's own step, so a non-HL7 head - # names the head, not the last member. + # Vault BACKLOG #5100: the head's MSH-10 read for BHS-11 is that member's own step, so a + # non-HL7 head, which that read parses in full and refuses, names the head, not the last member. mids, ids = await _enqueue(store, ["not an HL7 message at all", _hl7_with_value("clean")]) col = _Collector() runner, _ = _batch_runner(store, col) diff --git a/tests/test_validate_dropped_segments.py b/tests/test_validate_dropped_segments.py index 6876fd39c4..b40a82fd83 100644 --- a/tests/test_validate_dropped_segments.py +++ b/tests/test_validate_dropped_segments.py @@ -195,12 +195,23 @@ def test_batch_envelope_lines_on_a_split_member_keep_the_exemption() -> None: assert result.unvalidated_segments == (("BTS", 4), ("BHS", 5), ("FTS", 6), ("FHS", 7)) -@pytest.mark.parametrize("msh_9", ["MFN^M02^MFN_M01", "MFN^M05^MFN_M01", "MFN^^MFN_M01"]) +@pytest.mark.parametrize( + "msh_9", + [ + "MFN^M02^MFN_M01", + "MFN^M05^MFN_M01", + "MFN^^MFN_M01", + "MFN^ ^MFN_M01", + "MFN^m02^MFN_M01", + "MFN^M02 ^MFN_M01", + ], +) def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemption( msh_9: str, ) -> None: """MSH-9.2 is compared (BACKLOG #5920 step 1): MFN_M02 and MFN_M05 are structures of their - own, so borrowing MFN_M01's slot for either is refused, as is a borrow with no trigger event.""" + own, so borrowing MFN_M01's slot for either is refused, as is a borrow whose event is not + three capital letters or digits (empty, blank, lower-case or padded), which fails closed.""" borrowed = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(borrowed + "\rORC|NW|ORD1\r" + _PV1) assert not result.ok @@ -222,6 +233,30 @@ def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( assert result.unvalidated_segments == (("ORC", 4), ("PV1", 5)) +def test_the_structure_lookup_keeps_no_sender_text() -> None: + """The MSH-9.2 lookup is cached by version alone, so distinct events add no cache entry.""" + validate_module._structures.cache_clear() + for n in range(30): + validate(_MFN_M01.replace("MFN^M01^MFN_M01", f"MFN^Q{n:02d}^MFN_M01") + "\rORC|NW|1") + assert validate_module._structures.cache_info().currsize == 1 + + +_PGL = "\rPID|1||1^^^A||DOE^J\rGOL|AD|20260101|G1^Goal|1\rLOC|L1^Loc||C" + + +@pytest.mark.parametrize("msh_9", ["PGL^PC6^PGL_PC6", "PGL^PC7^PGL_PC6"]) +def test_a_structure_serving_several_events_keeps_the_exemption_for_each(msh_9: str) -> None: + """PGL_PC6 serves PC6 to PC8, and hl7apy has no PGL_PC7, so the borrow keeps it. hl7apy's + 2.5 PGL_PC6 has the "any HL7 segment" slot; its 2.5.1 one does not (the control).""" + head = "MSH|^~\\&|A|B|C|D|20260101||" + msh_9 + "|N1|P|" + result = validate(head + "2.5" + _PGL) + assert result.ok, result.errors + assert result.unvalidated_segments == (("LOC", 4),) + assert validate(head + "2.5.1" + _PGL).errors == [ + "segment LOC at line 4 has no place in this message's structure" + ] + + _PRR_PC5 = ( "MSH|^~\\&|A|B|C|D|20260101||PRR^PC5^PRR_PC5|N1|P|2.5.1\rMSA|AA|1\r" "QRD|20260101|R|I|Q1|||1^RD|1^Who|RES^Res|DEP^Dep\r" + _PID + "\r" From 6a155f185214843547a6cf1ab9902ed88b8d83f6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 03:09:54 -0600 Subject: [PATCH 4/7] Review round 2: literal later-header pattern, table 0003 events, no-borrow case BACKLOG #5920 and #5919. _SHORT_LATER_HEADER is a literal again, so the static ReDoS scanner reads it (test_security_static was red); a test holds its IDs to HEADER_IDS. A same-code borrow keeps the exemption only for an MSH-9.2 in the version's HL7 table 0003 as hl7apy ships it, so a made-up event fails closed. A message with no MSH-9.3 borrows nothing and keeps the exemption as on origin/main. Docs, changelog and comments say what the rule does, including the borrows that keep it. --- ...-same-code-borrow-no-exemption.security.md | 6 +-- docs/HL7-VALIDATION.md | 10 +++-- messagefoundry/parsing/split.py | 5 ++- messagefoundry/parsing/validate.py | 44 +++++++++++-------- messagefoundry/pipeline/wiring_runner.py | 6 +-- tests/test_encode_batch.py | 15 +++++-- tests/test_validate_dropped_segments.py | 20 ++++++--- 7 files changed, 65 insertions(+), 41 deletions(-) diff --git a/changelog.d/5920-same-code-borrow-no-exemption.security.md b/changelog.d/5920-same-code-borrow-no-exemption.security.md index 7753887ff0..bc186dac1a 100644 --- a/changelog.d/5920-same-code-borrow-no-exemption.security.md +++ b/changelog.d/5920-same-code-borrow-no-exemption.security.md @@ -1,6 +1,6 @@ - **Strict validation compares MSH-9.2 before a borrowed "any HL7 segment" structure keeps its exemption.** A message that names such a structure in MSH-9.3 under its own message code, as `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in - `unvalidated_segments`. Where MSH-9.2 names a trigger event that has a structure of its own in - `hl7apy`'s tables, or is not three capital letters or digits, they are now refused. - (`BACKLOG #5920`) + `unvalidated_segments`. They are now refused where MSH-9.2 names a trigger event that has a + structure of its own in `hl7apy`'s tables, or one that is not in the version's HL7 table 0003 + as `hl7apy` ships it. A message with no MSH-9.3 is unchanged. (`BACKLOG #5920`) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index f591cf6960..1d6a8e0b48 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -88,10 +88,12 @@ refused, and so is a dropped bare defined ID with no field separator (a lone `OR `MFN_M01`); a bare line `hl7apy` placed is not. A dropped `MSH`, `DSC`, `MSA`, `ERR`, `QAK` or `MFA` line is refused too. A batch or file envelope line (`BHS`, `BTS`, `FHS`, `FTS`) is exempted like any other defined segment, because batch splitting can leave one on a message. Every dropped segment is refused where MSH-9.3 -borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). A borrow under -the same code is also held to MSH-9.2, so `MFN^M02^MFN_M01` is refused because `MFN_M02` is a -structure of its own; the exact rule is in `_exempts_defined_segments` in -[`validate.py`](../messagefoundry/parsing/validate.py). Where the slot is required and its group is present, `hl7apy`'s own check +borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). Under the same +code, MSH-9.2 decides: a dropped segment in `MFN^M02^MFN_M01` is refused, because `MFN_M02` is a +structure of its own, while some same-code borrows keep the exemption, at least `PGL^PC7^PGL_PC6` +in 2.5 and a table 0003 event `hl7apy` gives no structure, such as `MFN^M14^MFN_M01`. The exact +rule is in `_exempts_defined_segments` in [`validate.py`](../messagefoundry/parsing/validate.py). +Where the slot is required and its group is present, `hl7apy`'s own check refuses at least some such messages, since the slot is never filled (`Missing required child ... ANYHL7SEGMENT`; `MFN_M03` for one), but not where the slot is one alternative of a choice: a `PRR_PC5` order with its `OBR` passes. Where the slot sits inside a nested group (at least the diff --git a/messagefoundry/parsing/split.py b/messagefoundry/parsing/split.py index 766efac7bc..14c01b8b86 100644 --- a/messagefoundry/parsing/split.py +++ b/messagefoundry/parsing/split.py @@ -521,8 +521,9 @@ def _head_separators(norm: str) -> tuple[str, str, str, str, str]: #: A header line after the first that is too short for the parse to read (``_builtin_hl7.parse`` #: refuses one): a line that is a header ID alone, or the text's last line once the parse's strip -#: leaves only a header ID there. -_SHORT_LATER_HEADER = re.compile(r"\r(?:" + "|".join(map(re.escape, HEADER_IDS)) + r")(?:\r|\s*\Z)") +#: leaves only a header ID there. A literal, so the static ReDoS scanner can read it; a test +#: holds its IDs to HEADER_IDS. +_SHORT_LATER_HEADER = re.compile(r"\r(?:MSH|BHS|FHS)(?:\r|\s*\Z)") def head_control_id(text: str) -> str | None: diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index ca11738a4e..36557ca9eb 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -40,9 +40,9 @@ refused, and so is a dropped MSH, DSC, MSA, ERR, QAK or MFA line (``_NEVER_EXEMPT`` says why). The exemption is per structure, not per slot: it does not count against the slot's cardinality or position. It holds only where MSH-9.1 names the structure's own message code, so a -structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none. One -borrowed under the same code is also held to MSH-9.2 (``MFN^M02^MFN_M01`` gets none), by the rule -:func:`_exempts_defined_segments` states. Where the slot sits inside a +structure borrowed through MSH-9.3 under another message code (``ADT^A01^MFN_M01``) gets none. +Under the same code, MSH-9.2 decides whether a borrow keeps it (``MFN^M02^MFN_M01`` does not; +some do), by the rule :func:`_exempts_defined_segments` states. Where the slot sits inside a nested group (at least PRR_PC5 and PPV_PCA), such a segment can still break hl7apy's grouping of what follows. Segment order is not checked as such: hl7apy keeps each segment where the message has it, so an out-of-order message may pass. @@ -357,36 +357,42 @@ def _exempts_defined_segments(message: Any) -> bool: hl7apy takes the structure from MSH-9.3 when one is given, so ``ADT^A01^MFN_M01`` would borrow MFN_M01's slot for an ADT body. The exemption holds only where MSH-9.1 names the structure's own message code, which fails closed on a structure borrowed under another code. - Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1): the structure is the - message's own when it is ``_``, and a borrow keeps the exemption only for - a trigger event of exactly three capital letters or digits that hl7apy's tables give no - structure of its own. So ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, nor - does an empty, lower-case or padded event, while ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one - structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one).""" + Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1). A message with no + MSH-9.3 borrows nothing: hl7apy names its structure from MSH-9.1 and MSH-9.2. One with an + MSH-9.3 keeps the exemption where the structure is ``_``, or where MSH-9.2 + is a trigger event in the version's HL7 table 0003 as hl7apy ships it and hl7apy's tables give + it no structure of its own. So ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, + nor does an event outside that table (empty, lower-case, padded or made up, such as ``ZZZ``), + nor any borrow in a version hl7apy ships no tables for (2.3), while ``PGL^PC7^PGL_PC6`` in 2.5 + keeps it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one). + So does an event in the table that the borrowed structure does not serve in the standard + (``MFN^M14^MFN_M01``): hl7apy has no table of which structure serves which event.""" code = message.msh.msh_9.msh_9_1.to_er7() if code != message.name.split("_", 1)[0]: return False if not _has_any_segment_slot(message.name, message.classname, message.version): return False + if len(message.msh.msh_9.to_er7().split(message.encoding_chars["COMPONENT"])) < 3: + return True event = message.msh.msh_9.msh_9_2.to_er7() own = f"{code}_{event}" if own == message.name: return True - return _TRIGGER_EVENT.fullmatch(event) is not None and own not in _structures(message.version) - - -#: The shape of a trigger event a same-code borrow may keep the exemption for; any other value, -#: such as ``m02`` or ``M02 `` for an event that has its own structure, fails closed. -_TRIGGER_EVENT = re.compile(r"[A-Z0-9]{3}") + structures, events = _structures_and_events(message.version) + return event in events and own not in structures -# Keyed by version alone, so a sender's MSH-9.2 text is never kept. +# Keyed by version alone, so the cache holds none of a sender's MSH-9.2 text. @cache -def _structures(hl7_version: str) -> frozenset[str]: - """The message structures hl7apy's tables for ``hl7_version`` define.""" +def _structures_and_events(hl7_version: str) -> tuple[frozenset[str], frozenset[str]]: + """The message structures and the trigger events (HL7 table 0003) hl7apy's tables for + ``hl7_version`` define; no events where hl7apy ships no tables for the version.""" import hl7apy - return frozenset(hl7apy.load_library(hl7_version).MESSAGES) + library = hl7apy.load_library(hl7_version) + tables = getattr(library, "TABLES", {}) + events = tables["HL70003"][1] if "HL70003" in tables else () + return frozenset(library.MESSAGES), frozenset(events) # Six IDs a dropped line of which is refused even in a structure with the "any HL7 segment" slot diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index cbc135a155..3b36b12ccf 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -12278,9 +12278,9 @@ async def _deliver_coalesced_batch( # dead-letters the members still present (bad data can never frame/deliver — # replayable from the DLQ) so a code bug or a mis-typed feed can't wedge the lane. # A fault one member's own step raised (its re-attach, its frame check, or the head's - # parse) names that member by its outbox id, never its content, in the log, the stored - # error and the alert (vault BACKLOG #5100). One the send of a connector a reload - # retired raised is the reload's (BACKLOG #5718), as the single row. + # MSH-10 read) names that member by its outbox id, never its content, in the log, + # the stored error and the alert (vault BACKLOG #5100). One the send of a connector + # a reload retired raised is the reload's (BACKLOG #5718), as the single row. if sending and self._connector_retired(name, connector): return await self._release_retired(name, [it.id for it in items]) member = _batch_member(current) diff --git a/tests/test_encode_batch.py b/tests/test_encode_batch.py index c8df13a11f..bd3069c25c 100644 --- a/tests/test_encode_batch.py +++ b/tests/test_encode_batch.py @@ -95,7 +95,7 @@ def test_message_objects_and_strings_both_accepted() -> None: def _no_parse(*_args: object, **_kwargs: object) -> Message: - raise AssertionError("encode_batch parsed a member") + raise AssertionError("a member was parsed in full") @pytest.mark.parametrize("head", [M1, M1.replace("\r", "\n")]) @@ -105,7 +105,7 @@ def test_the_head_member_is_not_parsed(monkeypatch: pytest.MonkeyPatch, head: st env = encode_batch([head, M2], control_id="1", timestamp=_TS) assert env.startswith("BHS|^~\\&|") # Negative control: the patch sees a parse when one happens. An envelope-led head is parsed. - with pytest.raises(AssertionError, match="parsed a member"): + with pytest.raises(AssertionError, match="parsed in full"): encode_batch(["BHS|^~\\&\r" + head, M2], control_id="1", timestamp=_TS) @@ -322,7 +322,7 @@ def test_the_head_control_id_is_read_without_a_full_parse( monkeypatch.setattr(Message, "parse", staticmethod(_no_parse)) assert head_control_id(head) == "MSG1" # Negative control: an envelope-led head is parsed in full. - with pytest.raises(AssertionError, match="parsed a member"): + with pytest.raises(AssertionError, match="parsed in full"): head_control_id("BHS|^~\\&\r" + head) @@ -378,3 +378,12 @@ def counting_parse(raw: str | bytes) -> Message: assert len(heads) - len(read) >= 100 assert sum(_has_a_short_later_header(h) for h in heads) >= 100 assert len(heads) - len(full_parses) >= 500, len(full_parses) + + +def test_the_short_later_header_pattern_names_the_parsers_header_ids() -> None: + # A literal for the static ReDoS scanner, so a change to HEADER_IDS must reach it by hand. + from messagefoundry.parsing._builtin_hl7 import HEADER_IDS + from messagefoundry.parsing.split import _SHORT_LATER_HEADER + + named = _SHORT_LATER_HEADER.pattern.split("(?:", 2)[1].split(")", 1)[0].split("|") + assert sorted(named) == sorted(HEADER_IDS) diff --git a/tests/test_validate_dropped_segments.py b/tests/test_validate_dropped_segments.py index b40a82fd83..59ebf09448 100644 --- a/tests/test_validate_dropped_segments.py +++ b/tests/test_validate_dropped_segments.py @@ -204,14 +204,16 @@ def test_batch_envelope_lines_on_a_split_member_keep_the_exemption() -> None: "MFN^ ^MFN_M01", "MFN^m02^MFN_M01", "MFN^M02 ^MFN_M01", + "MFN^ZZZ^MFN_M01", + "MFN^XY1^MFN_M01", ], ) def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemption( msh_9: str, ) -> None: """MSH-9.2 is compared (BACKLOG #5920 step 1): MFN_M02 and MFN_M05 are structures of their - own, so borrowing MFN_M01's slot for either is refused, as is a borrow whose event is not - three capital letters or digits (empty, blank, lower-case or padded), which fails closed.""" + own, so borrowing MFN_M01's slot for either is refused, as is a borrow whose event is not in + HL7 table 0003 (empty, blank, lower-case, padded or made up), which fails closed.""" borrowed = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(borrowed + "\rORC|NW|ORD1\r" + _PV1) assert not result.ok @@ -221,12 +223,16 @@ def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemptio assert result.unvalidated_segments == () -@pytest.mark.parametrize("msh_9", ["MFN^M01^MFN_M01", "MFN^M01", "MFN^M14^MFN_M01"]) +@pytest.mark.parametrize( + "msh_9", ["MFN^M01^MFN_M01", "MFN^M01", "MFN^M01 ", "MFN^m01", "MFN^M14^MFN_M01"] +) def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( msh_9: str, ) -> None: - """Control for the test above: the structure MSH-9.1 and MSH-9.2 name keeps it, and so does - a same-code borrow for an event hl7apy's tables give no structure of its own (no MFN_M14).""" + """Control for the test above: a message with no MSH-9.3 borrows nothing and keeps it, as on + origin/main, padded or lower-case; so does the structure MSH-9.1 and MSH-9.2 name, and a + same-code borrow for a table 0003 event hl7apy gives no structure of its own (no MFN_M14). + The last is a known limit: the standard gives M14 the MFN_Znn structure, not MFN_M01.""" message = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(message + "\rORC|NW|ORD1\r" + _PV1) assert result.ok, result.errors @@ -235,10 +241,10 @@ def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( def test_the_structure_lookup_keeps_no_sender_text() -> None: """The MSH-9.2 lookup is cached by version alone, so distinct events add no cache entry.""" - validate_module._structures.cache_clear() + validate_module._structures_and_events.cache_clear() for n in range(30): validate(_MFN_M01.replace("MFN^M01^MFN_M01", f"MFN^Q{n:02d}^MFN_M01") + "\rORC|NW|1") - assert validate_module._structures.cache_info().currsize == 1 + assert validate_module._structures_and_events.cache_info().currsize == 1 _PGL = "\rPID|1||1^^^A||DOE^J\rGOL|AD|20260101|G1^Goal|1\rLOC|L1^Loc||C" From 79033af9884641608110e8cf4d2154987de0b569 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:02:54 -0600 Subject: [PATCH 5/7] Keep the exemption for a padded own event and a site-defined Z event Two regressions against origin/main in _exempts_defined_segments: a same-code borrow naming its own structure with a padded or lower-case MSH-9.2 (MFN^m01^MFN_M01, MFN^M01 ^MFN_M01), and a Z event borrowing a structure (QBP^Z44^QBP_Q15 in 2.5, QBP^Z44^QBP_Q11 and RSP^Z44^RSP_K11 in 2.8), were refused. Both keep the exemption again, with a test per case. The changelog fragment now reads as a consistency check, since a sender controls all of MSH-9, and the docstring names at least 2.1 to 2.3 as the versions with no table 0003. BACKLOG #5920 --- ...-same-code-borrow-no-exemption.security.md | 13 +++-- docs/HL7-VALIDATION.md | 3 +- messagefoundry/parsing/validate.py | 19 ++++--- tests/test_validate_dropped_segments.py | 50 ++++++++++++++++--- 4 files changed, 65 insertions(+), 20 deletions(-) diff --git a/changelog.d/5920-same-code-borrow-no-exemption.security.md b/changelog.d/5920-same-code-borrow-no-exemption.security.md index bc186dac1a..7dc1cf04fe 100644 --- a/changelog.d/5920-same-code-borrow-no-exemption.security.md +++ b/changelog.d/5920-same-code-borrow-no-exemption.security.md @@ -1,6 +1,9 @@ -- **Strict validation compares MSH-9.2 before a borrowed "any HL7 segment" structure keeps its - exemption.** A message that names such a structure in MSH-9.3 under its own message code, as - `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in +- **Strict validation checks MSH-9.2 against MSH-9.3 before a borrowed "any HL7 segment" + structure keeps its exemption.** This is a consistency check on what a message says about + itself, not a barrier: a sender controls all of MSH-9, and one that names a structure's own + event keeps the exemption. A message that names such a structure in MSH-9.3 under its own + message code, as `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in `unvalidated_segments`. They are now refused where MSH-9.2 names a trigger event that has a - structure of its own in `hl7apy`'s tables, or one that is not in the version's HL7 table 0003 - as `hl7apy` ships it. A message with no MSH-9.3 is unchanged. (`BACKLOG #5920`) + structure of its own in `hl7apy`'s tables, or a non-Z event that is not in the version's HL7 + table 0003 as `hl7apy` ships it. A site-defined Z event (`QBP^Z44^QBP_Q15`) and a message with + no MSH-9.3 are unchanged. (`BACKLOG #5920`) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index 1d6a8e0b48..53633d519b 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -91,7 +91,8 @@ defined segment, because batch splitting can leave one on a message. Every dropp borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). Under the same code, MSH-9.2 decides: a dropped segment in `MFN^M02^MFN_M01` is refused, because `MFN_M02` is a structure of its own, while some same-code borrows keep the exemption, at least `PGL^PC7^PGL_PC6` -in 2.5 and a table 0003 event `hl7apy` gives no structure, such as `MFN^M14^MFN_M01`. The exact +in 2.5, a site-defined Z event such as `QBP^Z44^QBP_Q15`, and a table 0003 event `hl7apy` gives +no structure, such as `MFN^M14^MFN_M01`. The exact rule is in `_exempts_defined_segments` in [`validate.py`](../messagefoundry/parsing/validate.py). Where the slot is required and its group is present, `hl7apy`'s own check refuses at least some such messages, since the slot is never filled (`Missing required child ... diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index 36557ca9eb..288022db1a 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -359,11 +359,13 @@ def _exempts_defined_segments(message: Any) -> bool: structure's own message code, which fails closed on a structure borrowed under another code. Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1). A message with no MSH-9.3 borrows nothing: hl7apy names its structure from MSH-9.1 and MSH-9.2. One with an - MSH-9.3 keeps the exemption where the structure is ``_``, or where MSH-9.2 - is a trigger event in the version's HL7 table 0003 as hl7apy ships it and hl7apy's tables give - it no structure of its own. So ``MFN^M02^MFN_M01`` gets none, since MFN_M02 is a structure, - nor does an event outside that table (empty, lower-case, padded or made up, such as ``ZZZ``), - nor any borrow in a version hl7apy ships no tables for (2.3), while ``PGL^PC7^PGL_PC6`` in 2.5 + MSH-9.3 keeps the exemption where the structure is ``_`` (MSH-9.2 stripped + and upper-cased), where MSH-9.2 is a site-defined Z event (``QBP^Z44^QBP_Q15``), which table + 0003 lists none of, or where MSH-9.2 is a trigger event in the version's HL7 table 0003 as + hl7apy ships it and hl7apy's tables give it no structure of its own. So ``MFN^M02^MFN_M01`` + gets none, since MFN_M02 is a structure, nor does another event outside that table (empty, + lower-case, padded or made up, such as ``XY1``), nor a borrow for a non-Z event in a version + hl7apy ships no table 0003 for (at least 2.1 to 2.3), while ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one). So does an event in the table that the borrowed structure does not serve in the standard (``MFN^M14^MFN_M01``): hl7apy has no table of which structure serves which event.""" @@ -375,9 +377,14 @@ def _exempts_defined_segments(message: Any) -> bool: if len(message.msh.msh_9.to_er7().split(message.encoding_chars["COMPONENT"])) < 3: return True event = message.msh.msh_9.msh_9_2.to_er7() - own = f"{code}_{event}" + # Normalized so a padded or lower-case own event (``MFN^m01^MFN_M01``) keeps the exemption, + # as ``MFN^m01`` with no MSH-9.3 does. + own = f"{code}_{event.strip().upper()}" if own == message.name: return True + # A site-defined Z event borrows a structure by design, and table 0003 lists none. + if event.startswith("Z"): + return True structures, events = _structures_and_events(message.version) return event in events and own not in structures diff --git a/tests/test_validate_dropped_segments.py b/tests/test_validate_dropped_segments.py index 59ebf09448..03e01f4961 100644 --- a/tests/test_validate_dropped_segments.py +++ b/tests/test_validate_dropped_segments.py @@ -204,7 +204,6 @@ def test_batch_envelope_lines_on_a_split_member_keep_the_exemption() -> None: "MFN^ ^MFN_M01", "MFN^m02^MFN_M01", "MFN^M02 ^MFN_M01", - "MFN^ZZZ^MFN_M01", "MFN^XY1^MFN_M01", ], ) @@ -212,8 +211,8 @@ def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemptio msh_9: str, ) -> None: """MSH-9.2 is compared (BACKLOG #5920 step 1): MFN_M02 and MFN_M05 are structures of their - own, so borrowing MFN_M01's slot for either is refused, as is a borrow whose event is not in - HL7 table 0003 (empty, blank, lower-case, padded or made up), which fails closed.""" + own, so borrowing MFN_M01's slot for either is refused, as is a borrow whose non-Z event is + not in HL7 table 0003 (empty, blank, lower-case, padded or made up), which fails closed.""" borrowed = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(borrowed + "\rORC|NW|ORD1\r" + _PV1) assert not result.ok @@ -224,15 +223,26 @@ def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemptio @pytest.mark.parametrize( - "msh_9", ["MFN^M01^MFN_M01", "MFN^M01", "MFN^M01 ", "MFN^m01", "MFN^M14^MFN_M01"] + "msh_9", + [ + "MFN^M01^MFN_M01", + "MFN^m01^MFN_M01", + "MFN^M01 ^MFN_M01", + "MFN^M01", + "MFN^M01 ", + "MFN^m01", + "MFN^ZZZ^MFN_M01", + "MFN^M14^MFN_M01", + ], ) def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( msh_9: str, ) -> None: - """Control for the test above: a message with no MSH-9.3 borrows nothing and keeps it, as on - origin/main, padded or lower-case; so does the structure MSH-9.1 and MSH-9.2 name, and a - same-code borrow for a table 0003 event hl7apy gives no structure of its own (no MFN_M14). - The last is a known limit: the standard gives M14 the MFN_Znn structure, not MFN_M01.""" + """Control for the test above: a message with no MSH-9.3 borrows nothing and keeps it, + padded or lower-case, as it did before this check; so does the structure MSH-9.1 and MSH-9.2 + name, padded or lower-case in MSH-9.2, a site-defined Z event, and a same-code borrow for a + table 0003 event hl7apy gives no structure of its own (no MFN_M14). The last is a known + limit: the standard gives M14 the MFN_Znn structure, not MFN_M01.""" message = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(message + "\rORC|NW|ORD1\r" + _PV1) assert result.ok, result.errors @@ -247,6 +257,30 @@ def test_the_structure_lookup_keeps_no_sender_text() -> None: assert validate_module._structures_and_events.cache_info().currsize == 1 +@pytest.mark.parametrize( + ("msh_9", "version", "body", "line"), + [ + ("QBP^Z44^QBP_Q15", "2.5", "QPD|Z44^Query|Q1\rPID|1||1^^^A||DOE^J\rRCP|I", 3), + ("QBP^Z44^QBP_Q11", "2.8", "QPD|Z44^Query|Q1\rPID|1||1^^^A||DOE^J\rRCP|I", 3), + ( + "RSP^Z44^RSP_K11", + "2.8", + "MSA|AA|1\rQAK|Q1|OK\rQPD|Z44^Query|Q1\rPID|1||1^^^A||DOE^J", + 5, + ), + ], +) +def test_a_site_defined_z_event_borrowing_a_structure_keeps_the_exemption( + msh_9: str, version: str, body: str, line: int +) -> None: + """A Z event borrows a structure by design and table 0003 lists none, so the PID in the + "any HL7 segment" slot is passed and listed, as it was before MSH-9.2 was compared.""" + head = "MSH|^~\\&|A|B|C|D|20260101||" + msh_9 + "|N1|P|" + version + "\r" + result = validate(head + body) + assert result.ok, result.errors + assert result.unvalidated_segments == (("PID", line),) + + _PGL = "\rPID|1||1^^^A||DOE^J\rGOL|AD|20260101|G1^Goal|1\rLOC|L1^Loc||C" From 9168542813bc01ecd39d6c8dcbe7f8e43f8d448f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:28:33 -0600 Subject: [PATCH 6/7] Review round cfcd7160: a Z event with its own structure gets no exemption The Z test now runs after the own-structure lookup, so QBP^Z73^QBP_Q15 in 2.5 is refused as MFN^M02^MFN_M01 is, and the changelog's refusal condition is true of the code. The docstring, the changelog and docs/HL7-VALIDATION.md state the check order, the raw-value Z test, and the known limit that an event of another family (MFN^A01^MFN_M01) keeps the exemption. The 2.1 to 2.3 clause is dropped: hl7apy refuses an MSH-9.3 there before this check runs. BACKLOG #5920 --- ...-same-code-borrow-no-exemption.security.md | 10 +++--- docs/HL7-VALIDATION.md | 4 +-- messagefoundry/parsing/validate.py | 31 ++++++++++--------- tests/test_validate_dropped_segments.py | 19 ++++++++++-- 4 files changed, 41 insertions(+), 23 deletions(-) diff --git a/changelog.d/5920-same-code-borrow-no-exemption.security.md b/changelog.d/5920-same-code-borrow-no-exemption.security.md index 7dc1cf04fe..48f70de163 100644 --- a/changelog.d/5920-same-code-borrow-no-exemption.security.md +++ b/changelog.d/5920-same-code-borrow-no-exemption.security.md @@ -3,7 +3,9 @@ itself, not a barrier: a sender controls all of MSH-9, and one that names a structure's own event keeps the exemption. A message that names such a structure in MSH-9.3 under its own message code, as `MFN^M02^MFN_M01` does, had dropped defined segments passed and listed in - `unvalidated_segments`. They are now refused where MSH-9.2 names a trigger event that has a - structure of its own in `hl7apy`'s tables, or a non-Z event that is not in the version's HL7 - table 0003 as `hl7apy` ships it. A site-defined Z event (`QBP^Z44^QBP_Q15`) and a message with - no MSH-9.3 are unchanged. (`BACKLOG #5920`) + `unvalidated_segments`. Where MSH-9.2, stripped and upper-cased, names the borrowed structure's + own event, that is unchanged. Otherwise the dropped segments are now refused where `hl7apy`'s + tables have a structure named for MSH-9.1 and MSH-9.2 (`MFN_M02`, or `QBP_Z73` in 2.5), or + where MSH-9.2 neither starts with Z nor is in the version's HL7 table 0003 as `hl7apy` ships + it. A site-defined Z event (`QBP^Z44^QBP_Q15`), an event in that table with no structure of + that name, and a message with no MSH-9.3 are unchanged. (`BACKLOG #5920`) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index 53633d519b..74e4f71866 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -91,8 +91,8 @@ defined segment, because batch splitting can leave one on a message. Every dropp borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). Under the same code, MSH-9.2 decides: a dropped segment in `MFN^M02^MFN_M01` is refused, because `MFN_M02` is a structure of its own, while some same-code borrows keep the exemption, at least `PGL^PC7^PGL_PC6` -in 2.5, a site-defined Z event such as `QBP^Z44^QBP_Q15`, and a table 0003 event `hl7apy` gives -no structure, such as `MFN^M14^MFN_M01`. The exact +in 2.5, a Z event with no structure of that name in `hl7apy`, such as `QBP^Z44^QBP_Q15`, and a +table 0003 event with none, such as `MFN^M14^MFN_M01` or even `MFN^A01^MFN_M01`. The exact rule is in `_exempts_defined_segments` in [`validate.py`](../messagefoundry/parsing/validate.py). Where the slot is required and its group is present, `hl7apy`'s own check refuses at least some such messages, since the slot is never filled (`Missing required child ... diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index 288022db1a..d8d330dd33 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -359,16 +359,19 @@ def _exempts_defined_segments(message: Any) -> bool: structure's own message code, which fails closed on a structure borrowed under another code. Under the same code, MSH-9.2 is compared too (BACKLOG #5920 step 1). A message with no MSH-9.3 borrows nothing: hl7apy names its structure from MSH-9.1 and MSH-9.2. One with an - MSH-9.3 keeps the exemption where the structure is ``_`` (MSH-9.2 stripped - and upper-cased), where MSH-9.2 is a site-defined Z event (``QBP^Z44^QBP_Q15``), which table - 0003 lists none of, or where MSH-9.2 is a trigger event in the version's HL7 table 0003 as - hl7apy ships it and hl7apy's tables give it no structure of its own. So ``MFN^M02^MFN_M01`` - gets none, since MFN_M02 is a structure, nor does another event outside that table (empty, - lower-case, padded or made up, such as ``XY1``), nor a borrow for a non-Z event in a version - hl7apy ships no table 0003 for (at least 2.1 to 2.3), while ``PGL^PC7^PGL_PC6`` in 2.5 - keeps it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one). - So does an event in the table that the borrowed structure does not serve in the standard - (``MFN^M14^MFN_M01``): hl7apy has no table of which structure serves which event.""" + MSH-9.3 is checked in this order. Where the structure is ``_``, MSH-9.2 + stripped and upper-cased, it keeps the exemption. Otherwise, where hl7apy's tables have a + structure named ``_``, it gets none: ``MFN^M02^MFN_M01``, since MFN_M02 is + a structure, and ``QBP^Z73^QBP_Q15`` in 2.5, since QBP_Z73 is one. Otherwise it keeps the + exemption where MSH-9.2 starts with Z, a site-defined event (``QBP^Z44^QBP_Q15``) of which + table 0003 lists none, or is a trigger event in the version's HL7 table 0003 as hl7apy ships + it, and gets none for any other value (empty, lower-case, padded or made up, such as + ``XY1``). So ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one structure serving several trigger + events (PGL_PC6 serves PC6 to PC8, for one). So does an event in the table that the borrowed + structure does not serve in the standard, such as ``MFN^M14^MFN_M01``, or one of another + message's family, such as ``MFN^A01^MFN_M01``: hl7apy has no table of which structure serves + which event, and only ``_`` is looked up. A Z test is on the raw MSH-9.2, so + ``MFN^Z44 ^MFN_M01`` keeps the exemption and ``MFN^z44^MFN_M01`` does not.""" code = message.msh.msh_9.msh_9_1.to_er7() if code != message.name.split("_", 1)[0]: return False @@ -382,11 +385,11 @@ def _exempts_defined_segments(message: Any) -> bool: own = f"{code}_{event.strip().upper()}" if own == message.name: return True - # A site-defined Z event borrows a structure by design, and table 0003 lists none. - if event.startswith("Z"): - return True structures, events = _structures_and_events(message.version) - return event in events and own not in structures + if own in structures: + return False + # A site-defined Z event borrows a structure by design, and table 0003 lists none. + return event.startswith("Z") or event in events # Keyed by version alone, so the cache holds none of a sender's MSH-9.2 text. diff --git a/tests/test_validate_dropped_segments.py b/tests/test_validate_dropped_segments.py index 03e01f4961..9d3b7cd3ea 100644 --- a/tests/test_validate_dropped_segments.py +++ b/tests/test_validate_dropped_segments.py @@ -205,6 +205,7 @@ def test_batch_envelope_lines_on_a_split_member_keep_the_exemption() -> None: "MFN^m02^MFN_M01", "MFN^M02 ^MFN_M01", "MFN^XY1^MFN_M01", + "MFN^z44^MFN_M01", ], ) def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemption( @@ -232,7 +233,9 @@ def test_a_same_code_borrow_for_an_event_with_its_own_structure_gets_no_exemptio "MFN^M01 ", "MFN^m01", "MFN^ZZZ^MFN_M01", + "MFN^Z44 ^MFN_M01", "MFN^M14^MFN_M01", + "MFN^A01^MFN_M01", ], ) def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( @@ -240,9 +243,10 @@ def test_the_own_structure_or_one_for_an_event_without_one_keeps_the_exemption( ) -> None: """Control for the test above: a message with no MSH-9.3 borrows nothing and keeps it, padded or lower-case, as it did before this check; so does the structure MSH-9.1 and MSH-9.2 - name, padded or lower-case in MSH-9.2, a site-defined Z event, and a same-code borrow for a - table 0003 event hl7apy gives no structure of its own (no MFN_M14). The last is a known - limit: the standard gives M14 the MFN_Znn structure, not MFN_M01.""" + name, padded or lower-case in MSH-9.2, a site-defined Z event (the Z test is on the raw + MSH-9.2, so a trailing pad keeps it), and a same-code borrow for a table 0003 event with no + ``MFN_`` structure in hl7apy (no MFN_M14, no MFN_A01). The last two are a known + limit: the standard gives M14 the MFN_Znn structure, and A01 is an ADT event.""" message = _MFN_M01.replace("MFN^M01^MFN_M01", msh_9) result = validate(message + "\rORC|NW|ORD1\r" + _PV1) assert result.ok, result.errors @@ -281,6 +285,15 @@ def test_a_site_defined_z_event_borrowing_a_structure_keeps_the_exemption( assert result.unvalidated_segments == (("PID", line),) +def test_a_z_event_with_a_structure_of_its_own_gets_no_exemption() -> None: + """hl7apy's 2.5 has a QBP_Z73 structure, so borrowing QBP_Q15's slot for Z73 is refused, as + ``MFN^M02^MFN_M01`` is: the Z test comes after the own-structure lookup.""" + head = "MSH|^~\\&|A|B|C|D|20260101||QBP^Z73^QBP_Q15|N1|P|2.5\r" + result = validate(head + "QPD|Z73^Query|Q1\rPID|1||1^^^A||DOE^J\rRCP|I") + assert result.errors == ["segment PID at line 3 has no place in this message's structure"] + assert result.unvalidated_segments == () + + _PGL = "\rPID|1||1^^^A||DOE^J\rGOL|AD|20260101|G1^Goal|1\rLOC|L1^Loc||C" From c565c82b58c93c08f68a457e44ef703616ca5d8e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 05:50:17 -0600 Subject: [PATCH 7/7] Review round a28aed3e: correct the exemption docstring's false claims Text only. hl7apy's 2.7 table 0003 lists Z73 to Z99, so the Z branch is no longer said to exist because the table lists no Z event; the summary line no longer says the structure must be the message's own; and the docstring names that any Z-led value and the table's Varies placeholder pass. The doc's QBP^Z44^QBP_Q15 example names 2.5. BACKLOG #5920 --- docs/HL7-VALIDATION.md | 2 +- messagefoundry/parsing/validate.py | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/HL7-VALIDATION.md b/docs/HL7-VALIDATION.md index 74e4f71866..81f3cce1ee 100644 --- a/docs/HL7-VALIDATION.md +++ b/docs/HL7-VALIDATION.md @@ -91,7 +91,7 @@ defined segment, because batch splitting can leave one on a message. Every dropp borrows a slot-bearing structure under another message code (`ADT^A01^MFN_M01`). Under the same code, MSH-9.2 decides: a dropped segment in `MFN^M02^MFN_M01` is refused, because `MFN_M02` is a structure of its own, while some same-code borrows keep the exemption, at least `PGL^PC7^PGL_PC6` -in 2.5, a Z event with no structure of that name in `hl7apy`, such as `QBP^Z44^QBP_Q15`, and a +in 2.5, a Z event with no structure of that name in `hl7apy`, such as `QBP^Z44^QBP_Q15` in 2.5, and a table 0003 event with none, such as `MFN^M14^MFN_M01` or even `MFN^A01^MFN_M01`. The exact rule is in `_exempts_defined_segments` in [`validate.py`](../messagefoundry/parsing/validate.py). Where the slot is required and its group is present, `hl7apy`'s own check diff --git a/messagefoundry/parsing/validate.py b/messagefoundry/parsing/validate.py index d8d330dd33..e3094e59ac 100644 --- a/messagefoundry/parsing/validate.py +++ b/messagefoundry/parsing/validate.py @@ -352,7 +352,8 @@ def _has_any_segment_slot(name: str, classname: str, hl7_version: str) -> bool: def _exempts_defined_segments(message: Any) -> bool: - """True if ``message``'s structure has the "any HL7 segment" slot and is its own. + """True if ``message``'s structure has the "any HL7 segment" slot and MSH-9 passes the + consistency check below, which some borrowed structures pass too. hl7apy takes the structure from MSH-9.3 when one is given, so ``ADT^A01^MFN_M01`` would borrow MFN_M01's slot for an ADT body. The exemption holds only where MSH-9.1 names the @@ -363,10 +364,11 @@ def _exempts_defined_segments(message: Any) -> bool: stripped and upper-cased, it keeps the exemption. Otherwise, where hl7apy's tables have a structure named ``_``, it gets none: ``MFN^M02^MFN_M01``, since MFN_M02 is a structure, and ``QBP^Z73^QBP_Q15`` in 2.5, since QBP_Z73 is one. Otherwise it keeps the - exemption where MSH-9.2 starts with Z, a site-defined event (``QBP^Z44^QBP_Q15``) of which - table 0003 lists none, or is a trigger event in the version's HL7 table 0003 as hl7apy ships + exemption where MSH-9.2 starts with Z, taken as a site-defined event (``QBP^Z44^QBP_Q15``) + that table 0003 need not list, or is a value in the version's HL7 table 0003 as hl7apy ships it, and gets none for any other value (empty, lower-case, padded or made up, such as - ``XY1``). So ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one structure serving several trigger + ``XY1``). Any Z-led value passes the Z test (``MFN^Zebra^MFN_M01``), and the table holds at + least one placeholder that is no event (``Varies`` from 2.4), which passes too. So ``PGL^PC7^PGL_PC6`` in 2.5 keeps it, one structure serving several trigger events (PGL_PC6 serves PC6 to PC8, for one). So does an event in the table that the borrowed structure does not serve in the standard, such as ``MFN^M14^MFN_M01``, or one of another message's family, such as ``MFN^A01^MFN_M01``: hl7apy has no table of which structure serves @@ -388,7 +390,7 @@ def _exempts_defined_segments(message: Any) -> bool: structures, events = _structures_and_events(message.version) if own in structures: return False - # A site-defined Z event borrows a structure by design, and table 0003 lists none. + # A site-defined Z event borrows a structure by design, and table 0003 need not list it. return event.startswith("Z") or event in events