From e46550ce65d2137af7ac922d9f52961ec308240c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:22:41 -0600 Subject: [PATCH 1/8] Dry run: the shared non-HL7 payload is build_payload's, not a copy of its branch _shareable_payload repeated build_payload's non-HL7 branch inline. It now returns build_payload(raw, content_type), the one construction the per-consumer path and the sandbox child use, so the fan-out's shared object cannot drift from the others. No behaviour change: both built the same RawMessage. Adjudicated: the duplication is real; the correctness half of the claim is not a defect of this function. A bytes body that is not UTF-8, or a binary body handed to route_message raw, raises UnicodeDecodeError the same way in build_payload, and dry_run carries a binary feed and decodes a text feed before route_message (_dry_run_raw), as the listener does. Test: test_shareable_payload_delegates_to_build_payload, which failed on the code before the change (the object was not build_payload's). BACKLOG #6819. --- messagefoundry/pipeline/dryrun.py | 7 +++++-- tests/test_dryrun.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index 4dc9095a4c..e00f85978f 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -239,10 +239,13 @@ def _shareable_payload(raw: str | bytes, content_type: str) -> Message | RawMess high-fan-out non-HL7 feed. Because it IS shared, a consumer that broke the convention and mutated ``.raw`` would be visible to later consumers of the same message. An HL7 :class:`Message` is *mutable* (Handlers transform it in place), so it cannot be shared: this returns ``None`` and each consumer - re-parses (the optimal isolation strategy — see :func:`_payload`).""" + re-parses (the optimal isolation strategy — see :func:`_payload`). + + The object is :func:`build_payload`'s, the one construction every consumer and the sandbox child + use, rather than a copy of its non-HL7 branch that could drift from it (BACKLOG #6819).""" if content_type == ContentType.HL7V2.value: return None - return RawMessage(raw if isinstance(raw, str) else raw.decode("utf-8"), content_type) + return build_payload(raw, content_type) @dataclass(frozen=True) diff --git a/tests/test_dryrun.py b/tests/test_dryrun.py index 6297835eee..fd310bcafc 100644 --- a/tests/test_dryrun.py +++ b/tests/test_dryrun.py @@ -853,3 +853,26 @@ def __getitem__(self, path: Any) -> Any: with pytest.raises(ValueError, match="unsupported _Watched"): transform_one(reg, "h", ADT_A01) assert seen == [], f"the return value was iterated, not classified: {seen}" + + +# --- BACKLOG #6819: the shared payload is build_payload's, not a copy of its branch ------------- + + +def test_shareable_payload_delegates_to_build_payload(monkeypatch: pytest.MonkeyPatch) -> None: + """The non-HL7 shared payload is built by ``build_payload``, the one definition the sandbox + child also uses, so the fan-out's shared object cannot drift from the per-consumer one + (BACKLOG #6819). It used to repeat that branch inline.""" + from messagefoundry.pipeline import dryrun + + built = RawMessage("{}", "json") + calls: list[tuple[str | bytes, str]] = [] + + def spy(raw: str | bytes, content_type: str) -> Message | RawMessage: + calls.append((raw, content_type)) + return built + + monkeypatch.setattr(dryrun, "build_payload", spy) + assert dryrun._shareable_payload(b"{}", "json") is built + assert calls == [(b"{}", "json")] + assert dryrun._shareable_payload(ADT_A01, ContentType.HL7V2.value) is None + assert len(calls) == 1 # HL7 is never shared, so never built here From e64a9e9fee9858370f9ef759d39346e52f2b9c58 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:32:11 -0600 Subject: [PATCH 2/8] Dry run: an unchanged reference file is read once, not on every preview route_message rebuilt _dry_run_reference_view on every call, so check, which previews every fixture on every inbound, re-read and re-parsed each file-backed reference set each time. _encoded_reference_file now keeps each file's table, as the store encodes it, keyed by path and the file's stat signature (mtime_ns, size, inode), taken before the read. A changed signature reads the file again. Values are decoded per preview, so each preview still gets its own copy of a container value. The cache holds at most 64 paths, oldest out first. A failed load or an unencodable value is never cached, so the once-per-set skip warning and the unencodable warning behave as before. Adjudicated: the per-message rebuild is real (three previews read the file three times; the test fails 3 == 1 with the cache disabled). The "bare continue on CodeSetError" half is NOT-A-BUG at origin/main: it logs a warning naming the set, once per set per process (vault #3340, test_dryrun_logs_a_reference_file_it_skips_once). The "no file-size cap" half matches the live sync, whose _load_file_source has none either; the file is operator configuration. Tests: test_dryrun_reads_an_unchanged_reference_file_once (fails on the code before the change), test_dryrun_reference_containers_are_fresh_per_preview (guards the per-preview copy). BACKLOG #6820. --- changelog.d/6820.changed.md | 5 +++ messagefoundry/pipeline/dryrun.py | 35 +++++++++++++++-- tests/test_reference_sets.py | 65 +++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 changelog.d/6820.changed.md diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md new file mode 100644 index 0000000000..94800713c4 --- /dev/null +++ b/changelog.d/6820.changed.md @@ -0,0 +1,5 @@ +- **A dry run reads an unchanged reference file once.** `messagefoundry check` previews every + fixture on every inbound, and each preview re-read and re-parsed every file-backed reference + set. The preview now keeps each file's table while the file's size, modification time and + inode are unchanged, and reads it again when any of them changes. Each preview still gets its + own copy of every value. (`BACKLOG #6820`) diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index e00f85978f..45e6d88eca 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -611,6 +611,37 @@ def transform_one( #: in this process; the path too, so another config's set of the same name still logs. A test resets it. _skipped_reference_sets_logged: set[tuple[str, str]] = set() +#: Each FILE-backed reference set the preview has loaded, by path: the file's stat signature at the +#: load and the table as the store encodes it (BACKLOG #6820). ``check`` previews every fixture on +#: every inbound, and each preview re-read and re-parsed every file; an unchanged file is now read +#: once. Stat is taken before the read, so a file edited during it is read again on the next +#: preview. Values are kept encoded and decoded per preview, so a Handler that edits a container +#: value changes its own preview only. Bounded, oldest out first. A test resets it. +_reference_file_cache: dict[str, tuple[tuple[int, int, int], dict[str, str]]] = {} +_REFERENCE_FILE_CACHE_MAX = 64 + + +def _encoded_reference_file(path: str) -> dict[str, str]: + """The set at ``path``, each value as the store encodes it, from the cache while the file's + stat signature is unchanged. Raises as :func:`load_code_set` and + :func:`encode_reference_value` do; neither outcome is cached.""" + try: + st = os.stat(path) + except OSError: + signature = None # the load below raises the loader's own refusal + else: + signature = (st.st_mtime_ns, st.st_size, st.st_ino) + cached = _reference_file_cache.get(path) + if cached is not None and cached[0] == signature: + return cached[1] + encoded = {k: encode_reference_value(v) for k, v in load_code_set(path).items()} + if signature is not None: + _reference_file_cache.pop(path, None) # re-inserted last, so eviction takes the oldest + _reference_file_cache[path] = (signature, encoded) + while len(_reference_file_cache) > _REFERENCE_FILE_CACHE_MAX: + _reference_file_cache.pop(next(iter(_reference_file_cache)), None) + return encoded + def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: """Best-effort preview of reference snapshots for a dry-run (ADR 0006): load each FILE-backed @@ -630,9 +661,7 @@ def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run continue try: - view[spec.name] = { - k: json.loads(encode_reference_value(v)) for k, v in load_code_set(path).items() - } + view[spec.name] = {k: json.loads(v) for k, v in _encoded_reference_file(path).items()} except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it # missing with nothing to say why. The set name only, never the loader's text: that can diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index 96cea3b208..02378995e3 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -1212,3 +1212,68 @@ async def racing_execute(sql: str, params: Any = None): assert [r["key"] for r in rows] == ["OLD"], "the freshly-eligible rows were destroyed" finally: await store.close() + + +# --- BACKLOG #6820: the preview reads a reference file once while it is unchanged ---------------- + +_REF_RAW = "MSH|^~\\&|A|B|C|D|20260101||ADT^A01|M1|P|2.5.1\rPID|1||100^^^H^MR||DOE^JANE\r" + + +def test_dryrun_reads_an_unchanged_reference_file_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`check` calls the preview once per fixture per inbound, and each call used to re-read and + re-parse every file-backed reference set (BACKLOG #6820). An unchanged file is now read once; + an edited one is read again, so the preview still shows the file as it stands.""" + import os + + from messagefoundry.pipeline import dryrun + + monkeypatch.setattr(dryrun, "_reference_file_cache", {}) + loads: list[str] = [] + real = dryrun.load_code_set + + def counting(path: str) -> Any: + loads.append(path) + return real(path) + + monkeypatch.setattr(dryrun, "load_code_set", counting) + csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") + reg = _ref_graph(csv) + reg.handlers["h"] = lambda m: [Send("OB_REF", reference("provider_npi")["MED1"])] + + first = [route_message(reg, reg.inbound["IB_REF"], _REF_RAW) for _ in range(3)] + assert [o.deliveries[0].payload for o in first] == ["9991"] * 3 + assert len(loads) == 1 + + _csv(csv, "code,npi\nMED1,9992222\n") + stat = csv.stat() + os.utime(csv, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000_000)) + again = route_message(reg, reg.inbound["IB_REF"], _REF_RAW) + assert again.deliveries[0].payload == "9992222" + assert len(loads) == 2 + + +def test_dryrun_reference_containers_are_fresh_per_preview( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A cached set hands each preview its own copy of a container value, so a Handler that edits + one in a fixture does not change what the next fixture reads (BACKLOG #6820).""" + from messagefoundry.pipeline import dryrun + + monkeypatch.setattr(dryrun, "_reference_file_cache", {}) + toml = tmp_path / "npi.toml" + toml.write_text('MED1 = ["9991"]\n', encoding="utf-8") + reg = _ref_graph(toml) + seen: list[list[str]] = [] + + def handle(m: Message) -> list[Send]: + value = reference("provider_npi")["MED1"] + seen.append(list(value)) + value.append("EDITED") + return [Send("OB_REF", m)] + + reg.handlers["h"] = handle + for _ in range(2): + route_message(reg, reg.inbound["IB_REF"], _REF_RAW) + assert seen == [["9991"], ["9991"]] From 8b466587634ae102f925d21596ad141320496abf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:34:21 -0600 Subject: [PATCH 3/8] Dry run: a fault in a peek read is a recorded ERROR, as on the listener dry_run caught only HL7PeekError around Peek.parse and read message_type, control_id, summarize(peek) and doc_ref_marker_refusal outside it. The live listener takes the same reads inside one guard over PEEK_READ_FAULTS (BACKLOG #1594). A parser fault in one of them raised out of dry_run, and so out of messagefoundry check. They now sit inside the guard: HL7PeekError keeps its text, and any other PEEK_READ_FAULTS member is ERROR "parse error: peek read failed ()", the listener's text, naming the type alone. Adjudicated: S08-34 is real; test_a_peek_read_fault_is_an_error_result (eight cases: IndexError, KeyError, TypeError, ValueError at summarize and at the marker check) raised on the code before the change. S08-35 is NOT-A-BUG at origin/main: dry_run already gates the strict validate with ingress_guards.strict_validation_due(ic, text). Proposed banners, for the Lander: #6819: BUILT. _shareable_payload delegates to build_payload (no behaviour change); the decode half is not a defect of this function, since build_payload decodes the same way and dry_run carries or decodes before route_message. #6820: BUILT. An unchanged reference file is read once per process, keyed on its stat signature; the CodeSetError half was already met (logged once per set, vault #3340) and the size-cap half matches the live sync. #6821: BUILT for S08-34; S08-35 already met (strict_validation_due). #5105: CLOSE, already met by engine PR 2867 (batch 609): a cast's sys.exit refuses the reload (test_env_cast_sys_exit.py), and one class, UserCodeCalledSysExit in dryrun.py, formats the code with int.__int__ (test_user_code_system_exit.py). No change on this branch. #5107: CLOSE, all three steps met: step 1 by ERROR in .expect and the timeout exclusion in checks.py (PR 2867), step 2 by warm_validation before the clock (PR 2867), step 3 by PR 2811. No change on this branch. BACKLOG #6821. --- changelog.d/6821.fixed.md | 6 ++++++ messagefoundry/pipeline/dryrun.py | 22 +++++++++++++++------- tests/test_dryrun.py | 23 +++++++++++++++++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 changelog.d/6821.fixed.md diff --git a/changelog.d/6821.fixed.md b/changelog.d/6821.fixed.md new file mode 100644 index 0000000000..0bd8e5b0da --- /dev/null +++ b/changelog.d/6821.fixed.md @@ -0,0 +1,6 @@ +- **A dry run records a fault in a peek read as ERROR, as the listener does.** `dry_run` caught + only `HL7PeekError` around the parse, and read the message type, control id, summary and + document-marker check outside that guard, so a parser fault in one raised out of the preview + and out of `messagefoundry check`. They now sit inside the guard, and a fault is an ERROR + reading `parse error: peek read failed ()`, the listener's text, naming the type alone. + (`BACKLOG #6821`) diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index 45e6d88eca..a60bf0ae06 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -52,7 +52,7 @@ summarize, validate, ) -from messagefoundry.parsing.peek import DEFAULT_MAX_MESSAGE_BYTES +from messagefoundry.parsing.peek import DEFAULT_MAX_MESSAGE_BYTES, PEEK_READ_FAULTS from messagefoundry.parsing.split import _BOM, _BOM_BYTES, one_message_bytes from messagefoundry.parsing.validate import warm_validation from messagefoundry.pipeline._sandbox_codec import build_payload @@ -1185,17 +1185,25 @@ def dry_run( error=exc.reason, ) + # The peek's field reads and the marker check sit inside the guard with the parse, under the + # listener's PEEK_READ_FAULTS, so a parser fault in one is an ERROR naming its type alone, as the + # listener records it, rather than an exception out of the preview (BACKLOG #6821, #1594). + parse_error: str | None = None try: peek = Peek.parse(text, max_bytes=peek_max_bytes(ic)) - except HL7PeekError as exc: + mt, cid, summ = peek.message_type, peek.control_id, (summarize(peek) or None) + # The listener's marker refusal, at the same point after the parse (BACKLOG #5099). + marker_refused = doc_ref_marker_refusal(peek, text) + except HL7PeekError as exc: # a ValueError, so it is caught before the faults below + parse_error = f"parse error: {exc}" + except PEEK_READ_FAULTS as exc: + parse_error = f"parse error: peek read failed ({type(exc).__name__})" + if parse_error is not None: return DryRunResult( - inbound=ic.name, disposition=MessageStatus.ERROR, raw=text, error=f"parse error: {exc}" + inbound=ic.name, disposition=MessageStatus.ERROR, raw=text, error=parse_error ) - mt, cid, summ = peek.message_type, peek.control_id, (summarize(peek) or None) - - # The listener's marker refusal, at the same point after the parse (BACKLOG #5099). - if (marker_refused := doc_ref_marker_refusal(peek, text)) is not None: + if marker_refused is not None: return DryRunResult( inbound=ic.name, disposition=MessageStatus.ERROR, diff --git a/tests/test_dryrun.py b/tests/test_dryrun.py index fd310bcafc..78be13e54d 100644 --- a/tests/test_dryrun.py +++ b/tests/test_dryrun.py @@ -876,3 +876,26 @@ def spy(raw: str | bytes, content_type: str) -> Message | RawMessage: assert calls == [(b"{}", "json")] assert dryrun._shareable_payload(ADT_A01, ContentType.HL7V2.value) is None assert len(calls) == 1 # HL7 is never shared, so never built here + + +# --- BACKLOG #6821: a fault in a peek read is a recorded ERROR, as on the listener -------------- + + +@pytest.mark.parametrize("fault", [IndexError, KeyError, TypeError, ValueError]) +@pytest.mark.parametrize("site", ["summarize", "doc_ref_marker_refusal"]) +def test_a_peek_read_fault_is_an_error_result( + monkeypatch: pytest.MonkeyPatch, fault: type[Exception], site: str +) -> None: + """A field read on an accepted peek that faults is ``ERROR`` naming the fault's type alone, + the listener's ``parse error: peek read failed ()`` (BACKLOG #6821, #1594). It used to + raise straight out of ``dry_run``, since only ``HL7PeekError`` was caught around the parse.""" + from messagefoundry.pipeline import dryrun + + def boom(*_a: object, **_k: object) -> object: + raise fault("MRN999SECRET") + + monkeypatch.setattr(dryrun, site, boom) + result = dry_run(_registry(lambda m: ["h"], {"h": lambda m: Send("out", m)}), ADT_A01) + assert result.disposition is MessageStatus.ERROR + assert result.error == f"parse error: peek read failed ({fault.__name__})" + assert result.handlers == [] and result.deliveries == [] From 6497c8912178a87bc6209f750ac4e406b9d53ec6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:41:31 -0600 Subject: [PATCH 4/8] Reference-set cache tests type-check under the strict tests profile The tests mypy leg refused two lines of the new #6820 tests: the counting loader read load_code_set off the dryrun module, which does not export it, and the edited Handler took Message where a Handler takes Message or RawMessage. The loader now comes from config.code_sets and the Handler takes the union. No behaviour change. BACKLOG #6820. --- tests/test_reference_sets.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index 02378995e3..c40c2ee008 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -31,7 +31,7 @@ Send, env, ) -from messagefoundry.parsing.message import Message +from messagefoundry.parsing.message import Message, RawMessage from messagefoundry.pipeline.alerts import LoggingAlertSink from messagefoundry.pipeline.dryrun import route_message from messagefoundry.pipeline.reference_sync import ReferenceSyncRunner @@ -1227,11 +1227,11 @@ def test_dryrun_reads_an_unchanged_reference_file_once( an edited one is read again, so the preview still shows the file as it stands.""" import os + from messagefoundry.config.code_sets import load_code_set as real from messagefoundry.pipeline import dryrun monkeypatch.setattr(dryrun, "_reference_file_cache", {}) loads: list[str] = [] - real = dryrun.load_code_set def counting(path: str) -> Any: loads.append(path) @@ -1267,7 +1267,7 @@ def test_dryrun_reference_containers_are_fresh_per_preview( reg = _ref_graph(toml) seen: list[list[str]] = [] - def handle(m: Message) -> list[Send]: + def handle(m: Message | RawMessage) -> list[Send]: value = reference("provider_npi")["MED1"] seen.append(list(value)) value.append("EDITED") From e7bd2c29c1b4f2752ca6c42cc678e3a4f76eca7c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:23:09 -0600 Subject: [PATCH 5/8] Review round 1: check builds the reference view once per run instead of a process cache The round's code-review (round-1ea6927283) found the #6820 process-wide, stat-keyed cache unsound: a same-size rewrite inside one timestamp tick or a time-preserving in-place copy served a stale table, a policy sidecar edit never invalidated it, FIFO eviction missed every lookup past 64 sets, its eviction raced another thread, and os.stat raised ValueError where the loader had refused with CodeSetError. The cache is gone. route_message, _dry_run_raw and dry_run take reference_view; None, the default, builds the view on the call as before. check builds it once per run and passes it for every fixture, so each file is read once and every fixture reads one snapshot, as messages read the live cache. The tests now pin the passed view (no load) and check's single load over three fixtures, which reads four loads with the view dropped. #6821: ingress_guards.py's module docstring said the dry run catches only HL7PeekError; it now says both catch PEEK_READ_FAULTS with one text, and that only the HL7PeekError text still differs. dry_run returns from each except arm rather than through a sentinel. Declined, as open findings for the report: sharing the listener's peek reads and fault text through ingress_guards (it touches wiring_runner, which another Builder holds this wave); the HL7PeekError text parity (pre-existing and documented). BACKLOG #6820, #6821. --- changelog.d/6820.changed.md | 9 ++- messagefoundry/checks.py | 19 ++++- messagefoundry/pipeline/dryrun.py | 80 +++++++++----------- messagefoundry/pipeline/ingress_guards.py | 5 +- tests/test_reference_sets.py | 91 +++++++++++++---------- 5 files changed, 113 insertions(+), 91 deletions(-) diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md index 94800713c4..09ff8b7bc6 100644 --- a/changelog.d/6820.changed.md +++ b/changelog.d/6820.changed.md @@ -1,5 +1,6 @@ -- **A dry run reads an unchanged reference file once.** `messagefoundry check` previews every +- **`messagefoundry check` reads each reference file once per run.** `check` previews every fixture on every inbound, and each preview re-read and re-parsed every file-backed reference - set. The preview now keeps each file's table while the file's size, modification time and - inode are unchanged, and reads it again when any of them changes. Each preview still gets its - own copy of every value. (`BACKLOG #6820`) + set. It now builds the reference view once per run and passes it to every preview, through a + new `reference_view` keyword on `dry_run` and `route_message`. Every fixture reads the same + snapshot, as every message reads the live engine's cache. A caller that passes no view keeps + the old behaviour. (`BACKLOG #6820`) diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index ce879e230d..4e1dac9c2e 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -1943,7 +1943,12 @@ def _check_dryrun( ) -> CheckResult: from messagefoundry.config.snapshot import ConfigDirMissing from messagefoundry.config.wiring import WiringError, load_config - from messagefoundry.pipeline.dryrun import dry_run, fixture_cap, read_message_sets + from messagefoundry.pipeline.dryrun import ( + _dry_run_reference_view, + dry_run, + fixture_cap, + read_message_sets, + ) from messagefoundry.redaction import safe_error from messagefoundry.store import MessageStatus @@ -2026,6 +2031,10 @@ def _check_dryrun( asserted = ( 0 # runs checked against a declared .expect disposition (executable acceptance criteria) ) + # Built once for the whole run, so each file-backed reference set is read once rather than once + # per fixture per inbound (BACKLOG #6820). Every fixture then reads the same snapshot, as every + # message reads the live engine's sealed cache. + reference_view = _dry_run_reference_view(reg) for label, path, raw, target in message_sets: try: expected = _expected_disposition(path, cap=cap) @@ -2037,7 +2046,13 @@ def _check_dryrun( pinned += 1 for ic_name in targets: total += 1 - result = dry_run(reg, raw, inbound=ic_name, snapshot_on_send=snapshot_on_send) + result = dry_run( + reg, + raw, + inbound=ic_name, + snapshot_on_send=snapshot_on_send, + reference_view=reference_view, + ) # A Router/Handler's own `raise` can quote field values, so its text goes through # `safe_error` before it enters the detail string (BACKLOG #1668). **No `show_phi=` keyword, # and this surface must never grow one:** `check` is the commit/CI gate, its stdout lands in diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index a60bf0ae06..52a30f7059 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -611,37 +611,6 @@ def transform_one( #: in this process; the path too, so another config's set of the same name still logs. A test resets it. _skipped_reference_sets_logged: set[tuple[str, str]] = set() -#: Each FILE-backed reference set the preview has loaded, by path: the file's stat signature at the -#: load and the table as the store encodes it (BACKLOG #6820). ``check`` previews every fixture on -#: every inbound, and each preview re-read and re-parsed every file; an unchanged file is now read -#: once. Stat is taken before the read, so a file edited during it is read again on the next -#: preview. Values are kept encoded and decoded per preview, so a Handler that edits a container -#: value changes its own preview only. Bounded, oldest out first. A test resets it. -_reference_file_cache: dict[str, tuple[tuple[int, int, int], dict[str, str]]] = {} -_REFERENCE_FILE_CACHE_MAX = 64 - - -def _encoded_reference_file(path: str) -> dict[str, str]: - """The set at ``path``, each value as the store encodes it, from the cache while the file's - stat signature is unchanged. Raises as :func:`load_code_set` and - :func:`encode_reference_value` do; neither outcome is cached.""" - try: - st = os.stat(path) - except OSError: - signature = None # the load below raises the loader's own refusal - else: - signature = (st.st_mtime_ns, st.st_size, st.st_ino) - cached = _reference_file_cache.get(path) - if cached is not None and cached[0] == signature: - return cached[1] - encoded = {k: encode_reference_value(v) for k, v in load_code_set(path).items()} - if signature is not None: - _reference_file_cache.pop(path, None) # re-inserted last, so eviction takes the oldest - _reference_file_cache[path] = (signature, encoded) - while len(_reference_file_cache) > _REFERENCE_FILE_CACHE_MAX: - _reference_file_cache.pop(next(iter(_reference_file_cache)), None) - return encoded - def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: """Best-effort preview of reference snapshots for a dry-run (ADR 0006): load each FILE-backed @@ -652,7 +621,11 @@ def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: engine's sealed reference cache returns (BACKLOG #1174): a TOML date is an ISO string in both. A set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is a set whose file did not load (vault BACKLOG #3340); both log a warning naming it, the second once - per set per process.""" + per set per process. + + Every call reads every file again. A caller previewing many messages against one graph, as + ``check`` does, builds the view once and passes it to :func:`dry_run` as ``reference_view`` + (BACKLOG #6820).""" view: dict[str, Mapping[str, Any]] = {} for spec in registry.references.values(): if spec.source.kind != "file": @@ -661,14 +634,16 @@ def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run continue try: - view[spec.name] = {k: json.loads(v) for k, v in _encoded_reference_file(path).items()} + view[spec.name] = { + k: json.loads(encode_reference_value(v)) for k, v in load_code_set(path).items() + } except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it # missing with nothing to say why. The set name only, never the loader's text: that can # quote a KEY (a duplicate one), which may be PHI for a patient-keyed set, and `check` # writes this line into a CI log. No cause either: a guess from the path (missing versus - # malformed) misnames a permission or a directory. Once per set per process, since - # `check` reloads the view for every fixture on every inbound. + # malformed) misnames a permission or a directory. Once per set per process, since a + # caller that passes no view reloads it for every message it previews. if (spec.name, path) not in _skipped_reference_sets_logged: _skipped_reference_sets_logged.add((spec.name, path)) log.warning("dry-run: reference set %r skipped, its file did not load", spec.name) @@ -752,6 +727,7 @@ def route_message( tracer: TraceHook | None = None, sandbox: SandboxSession | None = None, snapshot_on_send: bool = True, + reference_view: Mapping[str, Mapping[str, Any]] | None = None, ) -> RouteOutcome: """Run ``ic``'s Router then the named Handlers; return what they selected and would send. @@ -779,6 +755,12 @@ def route_message( value here (falling back to the Settings-model default, ON, when none load — #230 P4); a programmatic caller or the Test Bench should likewise pass ``settings.pipeline.snapshot_on_send`` where the site has set it. + + ``reference_view`` is the reference sets the preview reads, as + :func:`_dry_run_reference_view` builds them. ``None``, the default, builds them from the graph + on this call, reading every file-backed set again. A caller previewing many messages against + one graph builds it once and passes it, so each file is read once (BACKLOG #6820); the + previews then share its values, as the live engine's messages share its sealed cache. """ # Publish the graph's code sets so a call-time code_set(...) inside a Router/Handler resolves # during a dry-run / Test Bench / `messagefoundry check` preview (the loader only had them active @@ -793,7 +775,7 @@ def route_message( # view from the graph's FILE-backed declarations (literal paths) so a reference(...) read resolves # during `check`/Test Bench. DB-backed or env()-path sets can't be reached in a pure dry-run and are # simply absent (a read of one then raises, surfaced as that message's preview error). - sim_reference = _dry_run_reference_view(registry) + sim_reference = _dry_run_reference_view(registry) if reference_view is None else reference_view deliveries: list[DeliveryPreview] = [] state_ops: list[StateOpPreview] = [] meta_ops: list[MetaOpPreview] = [] @@ -989,6 +971,7 @@ def _dry_run_raw( *, tracer: TraceHook | None = None, snapshot_on_send: bool = True, + reference_view: Mapping[str, Mapping[str, Any]] | None = None, ) -> DryRunResult: """Dry-run a non-HL7 inbound (ADR 0004): no HL7 peek/validate; route the body as a RawMessage. @@ -1019,6 +1002,7 @@ def _dry_run_raw( ingest_time=time.time(), tracer=tracer, snapshot_on_send=snapshot_on_send, + reference_view=reference_view, ) except Exception as exc: # a router/handler script raised return DryRunResult( @@ -1129,6 +1113,7 @@ def dry_run( inbound: str | None = None, tracer: TraceHook | None = None, snapshot_on_send: bool = True, + reference_view: Mapping[str, Mapping[str, Any]] | None = None, ) -> DryRunResult: """Decode → guard → parse → (strict-validate) → route one message; return disposition + payloads. @@ -1156,6 +1141,9 @@ def dry_run( ``snapshot_on_send`` (ADR 0104) is threaded to :func:`route_message` — see its docstring. The library default is ``True``, as the engine's is (BACKLOG #5794); the CLI passes its resolved ``[pipeline].snapshot_on_send`` (#230). + ``reference_view`` is threaded to :func:`route_message` too; ``check`` builds it once per + graph and passes it for every fixture (BACKLOG #6820). + **THIS FUNCTION TAKES NO ``sandbox`` ARGUMENT AND ALWAYS RUNS ROUTERS/HANDLERS IN-PROCESS.** It is therefore blind to ``[sandbox].mode``. That matches ``serve`` on the shipped default (``off``), and diverges from it at ``[sandbox].mode=subprocess``: ``messagefoundry check`` and @@ -1173,7 +1161,14 @@ def dry_run( """ ic = select_inbound(registry, inbound) if ic.content_type is not ContentType.HL7V2: - return _dry_run_raw(registry, ic, raw, tracer=tracer, snapshot_on_send=snapshot_on_send) + return _dry_run_raw( + registry, + ic, + raw, + tracer=tracer, + snapshot_on_send=snapshot_on_send, + reference_view=reference_view, + ) try: text = decode_ingress(raw, ic) @@ -1188,20 +1183,18 @@ def dry_run( # The peek's field reads and the marker check sit inside the guard with the parse, under the # listener's PEEK_READ_FAULTS, so a parser fault in one is an ERROR naming its type alone, as the # listener records it, rather than an exception out of the preview (BACKLOG #6821, #1594). - parse_error: str | None = None try: peek = Peek.parse(text, max_bytes=peek_max_bytes(ic)) mt, cid, summ = peek.message_type, peek.control_id, (summarize(peek) or None) # The listener's marker refusal, at the same point after the parse (BACKLOG #5099). marker_refused = doc_ref_marker_refusal(peek, text) except HL7PeekError as exc: # a ValueError, so it is caught before the faults below - parse_error = f"parse error: {exc}" - except PEEK_READ_FAULTS as exc: - parse_error = f"parse error: peek read failed ({type(exc).__name__})" - if parse_error is not None: return DryRunResult( - inbound=ic.name, disposition=MessageStatus.ERROR, raw=text, error=parse_error + inbound=ic.name, disposition=MessageStatus.ERROR, raw=text, error=f"parse error: {exc}" ) + except PEEK_READ_FAULTS as exc: + fault = f"parse error: peek read failed ({type(exc).__name__})" + return DryRunResult(inbound=ic.name, disposition=MessageStatus.ERROR, raw=text, error=fault) if marker_refused is not None: return DryRunResult( @@ -1240,6 +1233,7 @@ def dry_run( ingest_time=time.time(), tracer=tracer, snapshot_on_send=snapshot_on_send, + reference_view=reference_view, ) except Exception as exc: # a router/handler script raised return DryRunResult( diff --git a/messagefoundry/pipeline/ingress_guards.py b/messagefoundry/pipeline/ingress_guards.py index 346af5943d..1e97f5f581 100644 --- a/messagefoundry/pipeline/ingress_guards.py +++ b/messagefoundry/pipeline/ingress_guards.py @@ -24,8 +24,9 @@ ``tests/test_ingress_guard_parity.py`` fails if it grows one back. **The two callers still differ in at least these places.** The HL7 parse step, which each caller -runs itself: the stored ``parse error`` text differs, and the dry-run catches only ``HL7PeekError`` -where the listener catches every peek-read fault. The detach's refusals of an escaped ``OBX-5.5`` +runs itself: the stored ``parse error`` text for an ``HL7PeekError`` differs, since the listener +renders it through ``safe_exc`` and the dry-run does not. Both catch every peek-read fault +(``PEEK_READ_FAULTS``) and store the same ``peek read failed`` text for one (BACKLOG #6821). The detach's refusals of an escaped ``OBX-5.5`` document (:class:`~messagefoundry.parsing.binary.EscapedDocumentError`), of a received document handle or marker (:class:`~messagefoundry.parsing.binary.InboundDocRefError`), of a document under a base64 delimiter (:class:`~messagefoundry.parsing.binary.Base64DelimiterError`) and of a diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index c40c2ee008..a2ea7b143d 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -31,7 +31,7 @@ Send, env, ) -from messagefoundry.parsing.message import Message, RawMessage +from messagefoundry.parsing.message import Message from messagefoundry.pipeline.alerts import LoggingAlertSink from messagefoundry.pipeline.dryrun import route_message from messagefoundry.pipeline.reference_sync import ReferenceSyncRunner @@ -1214,23 +1214,16 @@ async def racing_execute(sql: str, params: Any = None): await store.close() -# --- BACKLOG #6820: the preview reads a reference file once while it is unchanged ---------------- +# --- BACKLOG #6820: check reads each reference file once per run, not once per fixture ----------- _REF_RAW = "MSH|^~\\&|A|B|C|D|20260101||ADT^A01|M1|P|2.5.1\rPID|1||100^^^H^MR||DOE^JANE\r" -def test_dryrun_reads_an_unchanged_reference_file_once( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """`check` calls the preview once per fixture per inbound, and each call used to re-read and - re-parse every file-backed reference set (BACKLOG #6820). An unchanged file is now read once; - an edited one is read again, so the preview still shows the file as it stands.""" - import os - +def _counting_loader(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Count the dry run's reference-file loads; the list grows by one path per load.""" from messagefoundry.config.code_sets import load_code_set as real from messagefoundry.pipeline import dryrun - monkeypatch.setattr(dryrun, "_reference_file_cache", {}) loads: list[str] = [] def counting(path: str) -> Any: @@ -1238,42 +1231,60 @@ def counting(path: str) -> Any: return real(path) monkeypatch.setattr(dryrun, "load_code_set", counting) + return loads + + +def test_route_message_reads_a_passed_reference_view( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A caller that passes ``reference_view`` previews against it, and no file is read; with + none passed, each call builds the view and reads the file again (BACKLOG #6820).""" + loads = _counting_loader(monkeypatch) csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") reg = _ref_graph(csv) reg.handlers["h"] = lambda m: [Send("OB_REF", reference("provider_npi")["MED1"])] + ic = reg.inbound["IB_REF"] - first = [route_message(reg, reg.inbound["IB_REF"], _REF_RAW) for _ in range(3)] - assert [o.deliveries[0].payload for o in first] == ["9991"] * 3 - assert len(loads) == 1 + view = {"provider_npi": {"MED1": "PASSED"}} + passed = [route_message(reg, ic, _REF_RAW, reference_view=view) for _ in range(2)] + assert [o.deliveries[0].payload for o in passed] == ["PASSED", "PASSED"] + assert loads == [] - _csv(csv, "code,npi\nMED1,9992222\n") - stat = csv.stat() - os.utime(csv, ns=(stat.st_atime_ns, stat.st_mtime_ns + 1_000_000_000)) - again = route_message(reg, reg.inbound["IB_REF"], _REF_RAW) - assert again.deliveries[0].payload == "9992222" - assert len(loads) == 2 + built = [route_message(reg, ic, _REF_RAW) for _ in range(2)] + assert [o.deliveries[0].payload for o in built] == ["9991", "9991"] + assert loads == [str(csv), str(csv)] -def test_dryrun_reference_containers_are_fresh_per_preview( +def test_check_reads_each_reference_file_once_per_run( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """A cached set hands each preview its own copy of a container value, so a Handler that edits - one in a fixture does not change what the next fixture reads (BACKLOG #6820).""" - from messagefoundry.pipeline import dryrun + """`check` previews every fixture on every inbound, and each preview used to re-read and + re-parse every file-backed reference set (BACKLOG #6820). It now builds the view once per run: + three fixtures read the file once, and each still reads the set.""" + from messagefoundry import checks - monkeypatch.setattr(dryrun, "_reference_file_cache", {}) - toml = tmp_path / "npi.toml" - toml.write_text('MED1 = ["9991"]\n', encoding="utf-8") - reg = _ref_graph(toml) - seen: list[list[str]] = [] - - def handle(m: Message | RawMessage) -> list[Send]: - value = reference("provider_npi")["MED1"] - seen.append(list(value)) - value.append("EDITED") - return [Send("OB_REF", m)] - - reg.handlers["h"] = handle - for _ in range(2): - route_message(reg, reg.inbound["IB_REF"], _REF_RAW) - assert seen == [["9991"], ["9991"]] + loads = _counting_loader(monkeypatch) + csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") + cfg = tmp_path / "config" + cfg.mkdir() + (cfg / "c.py").write_text( + "from messagefoundry import inbound, outbound, router, handler, File, Send\n" + "from messagefoundry import Reference, FileRef, reference\n" + f"Reference('provider_npi', source=FileRef(path={str(csv)!r}))\n" + "inbound('IB_REF', File(directory='in'), router='r')\n" + "outbound('OB_REF', File(directory='out'))\n" + "@router('r')\n" + "def r(m): return ['h']\n" + "@handler('h')\n" + "def h(m): return Send('OB_REF', reference('provider_npi')['MED1'])\n", + encoding="utf-8", + ) + msgs = tmp_path / "messages" + msgs.mkdir() + for n in range(3): + (msgs / f"m{n}.hl7").write_text(_REF_RAW, encoding="utf-8") + + result = checks._check_dryrun(cfg, msgs) + assert result.ok, result.detail + assert "3/3" in result.detail or "3 run" in result.detail, result.detail + assert loads == [str(csv)] From 72cc8a75fe7344cd378d1767b147e8c564c223c5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:52:30 -0600 Subject: [PATCH 6/8] Review round 2: the run's reference view decodes a fresh copy per read, and a loader fault fails the leg The round's code-review (round-a793edb7e7) found that check's one view handed every fixture the same mutable values, so a Handler that edited a container it read changed what later fixtures read; reproduced as 2/3 false failures. Each set is now the live engine's own sealed reference cache (sealed_reference_set), so every read decodes its own copy, as the engine's does. test_check_fixtures_each_read_a_fresh_reference_value fails "2/3 run(s) failed" with a plain shared view. The view is built before the fixture loop, outside each fixture's guard, so a loader fault it does not turn into a skipped set (a RecursionError from deep TOML, a ValueError from a NUL in the path) ended check with a traceback. It now fails the dry-run leg naming the type alone. The builder is public as dry_run_reference_view, in __all__, so a caller building a view once does not reach into a private name. The parity prose in dryrun.py, checks.py and the fragment now says what is shared and that reads are fresh copies. The check test passes suppress_search=True and asserts "3 run(s) clean". Not built, for the report: the dryrun CLI and trace_dry_run loops still rebuild the view per message (dryrun_trace.py is another Builder's file this wave); the fragment says so. Proposed banner for #6820: PARTIAL. check builds the reference view once per run (each set a sealed cache, fresh copy per read); the CodeSetError half was already met (vault #3340) and the size-cap half matches the live sync. Open: the dryrun CLI and trace_dry_run still rebuild it per message. BACKLOG #6820. --- changelog.d/6820.changed.md | 11 ++-- messagefoundry/checks.py | 18 +++++-- messagefoundry/pipeline/dryrun.py | 29 +++++++---- tests/test_reference_sets.py | 84 +++++++++++++++++++++++++------ tests/test_sealed_cache.py | 4 +- 5 files changed, 110 insertions(+), 36 deletions(-) diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md index 09ff8b7bc6..9a4d081aa6 100644 --- a/changelog.d/6820.changed.md +++ b/changelog.d/6820.changed.md @@ -1,6 +1,9 @@ - **`messagefoundry check` reads each reference file once per run.** `check` previews every fixture on every inbound, and each preview re-read and re-parsed every file-backed reference - set. It now builds the reference view once per run and passes it to every preview, through a - new `reference_view` keyword on `dry_run` and `route_message`. Every fixture reads the same - snapshot, as every message reads the live engine's cache. A caller that passes no view keeps - the old behaviour. (`BACKLOG #6820`) + set. It now builds the reference view once per run, with the new public + `dry_run_reference_view`, and passes it to every preview through a new `reference_view` + keyword on `dry_run` and `route_message`. Each set in the view is the live engine's sealed + reference cache, so every read decodes its own copy of a value, and a Handler that edits one + in a fixture does not change what a later fixture reads. A caller that passes no view keeps + the old behaviour. The `dryrun` command and the traced dry run still read the files for every + message. (`BACKLOG #6820`) diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index 4e1dac9c2e..4fd7d7f35b 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -1944,8 +1944,8 @@ def _check_dryrun( from messagefoundry.config.snapshot import ConfigDirMissing from messagefoundry.config.wiring import WiringError, load_config from messagefoundry.pipeline.dryrun import ( - _dry_run_reference_view, dry_run, + dry_run_reference_view, fixture_cap, read_message_sets, ) @@ -2032,9 +2032,19 @@ def _check_dryrun( 0 # runs checked against a declared .expect disposition (executable acceptance criteria) ) # Built once for the whole run, so each file-backed reference set is read once rather than once - # per fixture per inbound (BACKLOG #6820). Every fixture then reads the same snapshot, as every - # message reads the live engine's sealed cache. - reference_view = _dry_run_reference_view(reg) + # per fixture per inbound (BACKLOG #6820). Every fixture reads the same snapshot, and each read + # of a value decodes its own copy, as the live engine's sealed cache does. A loader fault the + # builder does not turn into a skipped set fails this leg, naming its type alone, rather than + # ending the report: per fixture it was an ERROR, through dry_run's own guard. + try: + reference_view = dry_run_reference_view(reg) + except Exception as exc: # noqa: BLE001 - the type alone reaches the detail + return CheckResult( + "dryrun", + ok=False, + required=True, + detail=f"reference sets did not load for the preview ({type(exc).__name__})", + ) for label, path, raw, target in message_sets: try: expected = _expected_disposition(path, cap=cap) diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index 52a30f7059..6adf8ada76 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -69,6 +69,7 @@ from messagefoundry.pipeline.sandbox import SandboxMode, SandboxSession, run_sandboxed from messagefoundry.store import MessageStatus from messagefoundry.store.metadata import encode_reference_value +from messagefoundry.store.sealed_cache import sealed_reference_set __all__ = [ "DeliveryPreview", @@ -83,6 +84,7 @@ "transform_one", "disposition_for", "dry_run", + "dry_run_reference_view", "select_inbound", "AmbiguousInboundError", "NoInboundError", @@ -607,18 +609,20 @@ def transform_one( return TransformOutcome(deliveries, state_ops, meta_ops, declined) -#: The ``(set name, file path)`` pairs whose skip :func:`_dry_run_reference_view` has already logged +#: The ``(set name, file path)`` pairs whose skip :func:`dry_run_reference_view` has already logged #: in this process; the path too, so another config's set of the same name still logs. A test resets it. _skipped_reference_sets_logged: set[tuple[str, str]] = set() -def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: +def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: """Best-effort preview of reference snapshots for a dry-run (ADR 0006): load each FILE-backed declaration with a literal path. DB-backed or ``env()``-path sets can't be materialized without a store/environment, so they're omitted (a read of one then raises, as a preview error). - Each value goes through the same JSON encoding the store applies, so a preview reads what the live - engine's sealed reference cache returns (BACKLOG #1174): a TOML date is an ISO string in both. A + Each set is the live engine's own sealed reference cache, filled through the JSON encoding the + store applies, so a preview reads what the engine returns (BACKLOG #1174): a TOML date is an ISO + string in both, and every read decodes a fresh copy, so a Handler that edits a value it read + changes neither the view nor a later read of it (BACKLOG #6820). A set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is a set whose file did not load (vault BACKLOG #3340); both log a warning naming it, the second once per set per process. @@ -634,9 +638,10 @@ def _dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run continue try: - view[spec.name] = { - k: json.loads(encode_reference_value(v)) for k, v in load_code_set(path).items() - } + view[spec.name] = sealed_reference_set( + spec.name, + ((k, encode_reference_value(v)) for k, v in load_code_set(path).items()), + ) except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it # missing with nothing to say why. The set name only, never the loader's text: that can @@ -757,10 +762,12 @@ def route_message( where the site has set it. ``reference_view`` is the reference sets the preview reads, as - :func:`_dry_run_reference_view` builds them. ``None``, the default, builds them from the graph + :func:`dry_run_reference_view` builds them; a view built another way may share mutable + values between previews, which this one does not. ``None``, the default, builds them from the graph on this call, reading every file-backed set again. A caller previewing many messages against - one graph builds it once and passes it, so each file is read once (BACKLOG #6820); the - previews then share its values, as the live engine's messages share its sealed cache. + one graph builds it once and passes it, so each file is read once (BACKLOG #6820). The previews + then share one snapshot of each set, and each read of a value decodes its own copy, as the + live engine's sealed cache does. """ # Publish the graph's code sets so a call-time code_set(...) inside a Router/Handler resolves # during a dry-run / Test Bench / `messagefoundry check` preview (the loader only had them active @@ -775,7 +782,7 @@ def route_message( # view from the graph's FILE-backed declarations (literal paths) so a reference(...) read resolves # during `check`/Test Bench. DB-backed or env()-path sets can't be reached in a pure dry-run and are # simply absent (a read of one then raises, surfaced as that message's preview error). - sim_reference = _dry_run_reference_view(registry) if reference_view is None else reference_view + sim_reference = dry_run_reference_view(registry) if reference_view is None else reference_view deliveries: list[DeliveryPreview] = [] state_ops: list[StateOpPreview] = [] meta_ops: list[MetaOpPreview] = [] diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index a2ea7b143d..ad9a5d4fce 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -1255,36 +1255,90 @@ def test_route_message_reads_a_passed_reference_view( assert loads == [str(csv), str(csv)] -def test_check_reads_each_reference_file_once_per_run( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """`check` previews every fixture on every inbound, and each preview used to re-read and - re-parse every file-backed reference set (BACKLOG #6820). It now builds the view once per run: - three fixtures read the file once, and each still reads the set.""" - from messagefoundry import checks - - loads = _counting_loader(monkeypatch) - csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") +def _check_repo( + tmp_path: Path, ref: Path, handler_body: str, fixtures: int = 3 +) -> tuple[Path, Path]: + """A config dir declaring ``provider_npi`` from ``ref`` and one Handler, and ``fixtures`` + copies of one ADT fixture.""" cfg = tmp_path / "config" cfg.mkdir() (cfg / "c.py").write_text( "from messagefoundry import inbound, outbound, router, handler, File, Send\n" "from messagefoundry import Reference, FileRef, reference\n" - f"Reference('provider_npi', source=FileRef(path={str(csv)!r}))\n" + f"Reference('provider_npi', source=FileRef(path={str(ref)!r}))\n" "inbound('IB_REF', File(directory='in'), router='r')\n" "outbound('OB_REF', File(directory='out'))\n" "@router('r')\n" "def r(m): return ['h']\n" "@handler('h')\n" - "def h(m): return Send('OB_REF', reference('provider_npi')['MED1'])\n", + f"def h(m):\n{handler_body}", encoding="utf-8", ) msgs = tmp_path / "messages" msgs.mkdir() - for n in range(3): + for n in range(fixtures): (msgs / f"m{n}.hl7").write_text(_REF_RAW, encoding="utf-8") + return cfg, msgs + + +def test_check_reads_each_reference_file_once_per_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`check` previews every fixture on every inbound, and each preview used to re-read and + re-parse every file-backed reference set (BACKLOG #6820). It now builds the view once per run: + three fixtures read the file once, and each still reads the set.""" + from messagefoundry import checks + + loads = _counting_loader(monkeypatch) + csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") + body = " return Send('OB_REF', reference('provider_npi')['MED1'])\n" + cfg, msgs = _check_repo(tmp_path, csv, body) - result = checks._check_dryrun(cfg, msgs) + result = checks._check_dryrun(cfg, msgs, suppress_search=True) assert result.ok, result.detail - assert "3/3" in result.detail or "3 run" in result.detail, result.detail + assert result.detail.startswith("3 run(s) clean"), result.detail assert loads == [str(csv)] + + +def test_check_fixtures_each_read_a_fresh_reference_value(tmp_path: Path) -> None: + """The run's one view hands every read its own copy of a value, as the live sealed cache does, + so a Handler that edits a container it read in one fixture does not change what the next + fixture reads (BACKLOG #6820). A shared plain view failed the second and third fixtures.""" + from messagefoundry import checks + + toml = tmp_path / "npi.toml" + toml.write_text('MED1 = ["9991"]\n', encoding="utf-8") + body = ( + " value = reference('provider_npi')['MED1']\n" + " if value != ['9991']:\n" + " raise ValueError('the reference value changed between fixtures')\n" + " value.append('EDITED')\n" + " return Send('OB_REF', m)\n" + ) + cfg, msgs = _check_repo(tmp_path, toml, body) + + result = checks._check_dryrun(cfg, msgs, suppress_search=True) + assert result.ok, result.detail + assert result.detail.startswith("3 run(s) clean"), result.detail + + +def test_check_fails_the_leg_when_the_reference_view_faults( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A loader fault the view builder does not turn into a skipped set fails the dry-run leg, + naming its type alone, rather than raising out of ``check`` and losing the report: built once + per run, the view sits outside each fixture's own guard (BACKLOG #6820).""" + from messagefoundry import checks + from messagefoundry.pipeline import dryrun + + def faulting(path: str) -> Any: + raise RecursionError("MRN999SECRET") + + monkeypatch.setattr(dryrun, "load_code_set", faulting) + csv = _csv(tmp_path / "npi.csv", "code,npi\nMED1,9991\n") + body = " return Send('OB_REF', m)\n" + cfg, msgs = _check_repo(tmp_path, csv, body) + + result = checks._check_dryrun(cfg, msgs, suppress_search=True) + assert not result.ok and result.required and not result.skipped + assert result.detail == "reference sets did not load for the preview (RecursionError)" diff --git a/tests/test_sealed_cache.py b/tests/test_sealed_cache.py index 7f12191aaf..00372b6f05 100644 --- a/tests/test_sealed_cache.py +++ b/tests/test_sealed_cache.py @@ -265,7 +265,7 @@ def open_then_mutate(blob: bytes, aad: bytes) -> bytes: def test_dry_run_state_and_reference_read_back_in_the_live_json_form(tmp_path: Path) -> None: - from messagefoundry.pipeline.dryrun import _dry_run_reference_view + from messagefoundry.pipeline.dryrun import dry_run_reference_view ref = tmp_path / "payers.toml" ref.write_text('[acme]\nplan = "PPO"\neffective = 2026-01-01\n', encoding="utf-8") @@ -273,7 +273,7 @@ def test_dry_run_state_and_reference_read_back_in_the_live_json_form(tmp_path: P registry.references["payers"] = SimpleNamespace( # type: ignore[assignment] name="payers", source=SimpleNamespace(kind="file", settings={"path": str(ref)}) ) - view = _dry_run_reference_view(registry) + view = dry_run_reference_view(registry) assert view["payers"]["acme"] == {"plan": "PPO", "effective": "2026-01-01"} From b0938654c0ccde48d6b71a358d26188e049a3722 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:16:31 -0600 Subject: [PATCH 7/8] Preview reference sets decode on read without the store's sealing key The unrepaired review round (round-5d09231ab9) found that building the preview view from sealed_reference_set made two assurance rows false: docs/ASVS-L2-PHASE0-CHANGES.md says the sealed-cache key seals only the engine's own caches, in the engine process only, and check, dryrun and verify would now mint and use it. It also made the no-view path about 50 percent slower per message (AES-GCM per row). A false control claim must be fixed, so the view's sets are now _PreviewReferenceSet, a plain Mapping that keeps each value as the store's JSON text and decodes it on every read: fresh copies as before, no key, and no json.loads of values no Handler reads. The fresh-value test still fails 2/3 with a plain shared dict. Stale prose that round named is updated: route_message's inline comment names the passed view, and test_dryrun_logs_a_reference_file_it_skips_once no longer says check rebuilds the view per fixture. Banners for the Lander (supersede the earlier commit bodies): #6819: PARTIAL. _shareable_payload delegates to build_payload (no behaviour change). Open: public route_message, route_only and transform_one still decode bytes as UTF-8 for a non-HL7 type, so raw binary bytes raise or arrive without mfb64 carriage; dry_run itself carries or decodes first (_dry_run_raw). #6820: PARTIAL. check builds the reference view once per run, values decoded per read; CodeSetError half already met (vault #3340). Open: the dryrun CLI and trace_dry_run still rebuild per message, and no file-size cap (the live sync has none either; not adjudicated here). #6821: BUILT for S08-34; S08-35 already met (strict_validation_due). #5105: CLOSE, met by engine PR 2867; no change here. #5107: CLOSE, all three steps met (PR 2867, PR 2811); no change here. BACKLOG #6820. --- changelog.d/6820.changed.md | 10 +++---- messagefoundry/checks.py | 2 +- messagefoundry/pipeline/dryrun.py | 48 ++++++++++++++++++++++--------- tests/test_reference_sets.py | 4 +-- 4 files changed, 43 insertions(+), 21 deletions(-) diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md index 9a4d081aa6..90ce41555b 100644 --- a/changelog.d/6820.changed.md +++ b/changelog.d/6820.changed.md @@ -2,8 +2,8 @@ fixture on every inbound, and each preview re-read and re-parsed every file-backed reference set. It now builds the reference view once per run, with the new public `dry_run_reference_view`, and passes it to every preview through a new `reference_view` - keyword on `dry_run` and `route_message`. Each set in the view is the live engine's sealed - reference cache, so every read decodes its own copy of a value, and a Handler that edits one - in a fixture does not change what a later fixture reads. A caller that passes no view keeps - the old behaviour. The `dryrun` command and the traced dry run still read the files for every - message. (`BACKLOG #6820`) + keyword on `dry_run` and `route_message`. Every read of a value decodes its own copy, as a read + of the live engine's reference cache does, so a Handler that edits one in a fixture does not + change what a later fixture reads. A caller that passes no view keeps the old behaviour. The + `dryrun` command and the traced dry run still read the files for every message. + (`BACKLOG #6820`) diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index 4fd7d7f35b..1672d79f78 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -2033,7 +2033,7 @@ def _check_dryrun( ) # Built once for the whole run, so each file-backed reference set is read once rather than once # per fixture per inbound (BACKLOG #6820). Every fixture reads the same snapshot, and each read - # of a value decodes its own copy, as the live engine's sealed cache does. A loader fault the + # of a value decodes its own copy, as a read of the live engine's cache does. A loader fault the # builder does not turn into a skipped set fails this leg, naming its type alone, rather than # ending the report: per fixture it was an ERROR, through dry_run's own guard. try: diff --git a/messagefoundry/pipeline/dryrun.py b/messagefoundry/pipeline/dryrun.py index 6adf8ada76..a74b83f4fb 100644 --- a/messagefoundry/pipeline/dryrun.py +++ b/messagefoundry/pipeline/dryrun.py @@ -17,7 +17,7 @@ import logging import os import time -from collections.abc import Collection, Mapping +from collections.abc import Collection, Iterator, Mapping from dataclasses import dataclass, field from pathlib import Path from typing import Any, NamedTuple, Protocol, cast @@ -69,7 +69,6 @@ from messagefoundry.pipeline.sandbox import SandboxMode, SandboxSession, run_sandboxed from messagefoundry.store import MessageStatus from messagefoundry.store.metadata import encode_reference_value -from messagefoundry.store.sealed_cache import sealed_reference_set __all__ = [ "DeliveryPreview", @@ -614,15 +613,38 @@ def transform_one( _skipped_reference_sets_logged: set[tuple[str, str]] = set() +class _PreviewReferenceSet(Mapping[str, Any]): + """One reference set of a preview view: each value kept as the JSON text the store encodes it + to, and decoded on every read, so every read returns its own copy, as a read of the live + engine's reference cache does. A Handler that edits a value it read changes neither the set + nor a later read of it, in this preview or another one given the same view (BACKLOG #6820).""" + + __slots__ = ("_encoded",) + + def __init__(self, encoded: dict[str, str]) -> None: + self._encoded = encoded + + def __getitem__(self, key: str) -> Any: + return json.loads(self._encoded[key]) + + def __contains__(self, key: object) -> bool: + return key in self._encoded + + def __iter__(self) -> Iterator[str]: + return iter(self._encoded) + + def __len__(self) -> int: + return len(self._encoded) + + def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: """Best-effort preview of reference snapshots for a dry-run (ADR 0006): load each FILE-backed declaration with a literal path. DB-backed or ``env()``-path sets can't be materialized without a store/environment, so they're omitted (a read of one then raises, as a preview error). - Each set is the live engine's own sealed reference cache, filled through the JSON encoding the - store applies, so a preview reads what the engine returns (BACKLOG #1174): a TOML date is an ISO - string in both, and every read decodes a fresh copy, so a Handler that edits a value it read - changes neither the view nor a later read of it (BACKLOG #6820). A + Each value goes through the JSON encoding the store applies, so a preview reads what the live + engine's reference cache returns (BACKLOG #1174): a TOML date is an ISO string in both. Each + read decodes its own copy, as the engine's does (:class:`_PreviewReferenceSet`). A set the store would refuse to encode is omitted, as the live sync would refuse to commit it. So is a set whose file did not load (vault BACKLOG #3340); both log a warning naming it, the second once per set per process. @@ -638,9 +660,8 @@ def dry_run_reference_view(registry: Registry) -> dict[str, Mapping[str, Any]]: if not isinstance(path, str): # an env() ref — unresolved in a pure dry-run continue try: - view[spec.name] = sealed_reference_set( - spec.name, - ((k, encode_reference_value(v)) for k, v in load_code_set(path).items()), + view[spec.name] = _PreviewReferenceSet( + {k: encode_reference_value(v) for k, v in load_code_set(path).items()} ) except CodeSetError: # A missing, malformed or unreadable file. Say so, or a later read of the set reports it @@ -766,8 +787,8 @@ def route_message( values between previews, which this one does not. ``None``, the default, builds them from the graph on this call, reading every file-backed set again. A caller previewing many messages against one graph builds it once and passes it, so each file is read once (BACKLOG #6820). The previews - then share one snapshot of each set, and each read of a value decodes its own copy, as the - live engine's sealed cache does. + then share one snapshot of each set, and each read of a value decodes its own copy, as a + read of the live engine's reference cache does. """ # Publish the graph's code sets so a call-time code_set(...) inside a Router/Handler resolves # during a dry-run / Test Bench / `messagefoundry check` preview (the loader only had them active @@ -778,8 +799,9 @@ def route_message( # earlier handler in the same simulated message declared (a self-consistent preview), mirroring how # the live cache would reflect committed writes. It is local to this call (no global side effect). sim_state: dict[tuple[str, str], StateValue] = {} - # Reference sets (ADR 0006): there is no store/sync in a dry-run, so build a best-effort preview - # view from the graph's FILE-backed declarations (literal paths) so a reference(...) read resolves + # Reference sets (ADR 0006): there is no store/sync in a dry-run, so use the caller's view, or + # build a best-effort preview view from the graph's FILE-backed declarations (literal paths), so + # a reference(...) read resolves # during `check`/Test Bench. DB-backed or env()-path sets can't be reached in a pure dry-run and are # simply absent (a read of one then raises, surfaced as that message's preview error). sim_reference = dry_run_reference_view(registry) if reference_view is None else reference_view diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index ad9a5d4fce..ff26999726 100644 --- a/tests/test_reference_sets.py +++ b/tests/test_reference_sets.py @@ -719,8 +719,8 @@ def test_dryrun_logs_a_reference_file_it_skips_once( was left out with no log line, so a later read reported the set missing with no word on why. The line names the set only, never the loader's text: a duplicate-key error quotes the key, which may be PHI for a patient-keyed set. It names no cause either, since a guess from the path misnames - one. And it is logged once per set per process: `check` rebuilds the view for every fixture on - every inbound, and a line per rebuild buries the log.""" + one. And it is logged once per set per process: a caller that passes no view, as this test + does, rebuilds it for every message, and a line per rebuild buries the log.""" from messagefoundry.pipeline import dryrun monkeypatch.setattr(dryrun, "_skipped_reference_sets_logged", set()) From 16ddee0363e38dbf44522155d563810c06fb8ec7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:34:18 -0600 Subject: [PATCH 8/8] Changelog: say what a preview without a passed view still does The final review round (round-4d4f2dd7f2) found the #6820 fragment's "a caller that passes no view keeps the old behaviour" false: every read now decodes its own copy on that path too, so one Handler's edit to a reference value no longer reaches a later Handler of the same message. The fragment now says so, and no longer says check previews every fixture on every inbound. Text only. BACKLOG #6820. --- changelog.d/6820.changed.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md index 90ce41555b..92883b4898 100644 --- a/changelog.d/6820.changed.md +++ b/changelog.d/6820.changed.md @@ -1,9 +1,9 @@ -- **`messagefoundry check` reads each reference file once per run.** `check` previews every - fixture on every inbound, and each preview re-read and re-parsed every file-backed reference - set. It now builds the reference view once per run, with the new public +- **`messagefoundry check` reads each reference file once per run.** `check` previewed each + fixture against each inbound it runs on, and each preview re-read and re-parsed every + file-backed reference set. It now builds the reference view once per run, with the new public `dry_run_reference_view`, and passes it to every preview through a new `reference_view` keyword on `dry_run` and `route_message`. Every read of a value decodes its own copy, as a read - of the live engine's reference cache does, so a Handler that edits one in a fixture does not - change what a later fixture reads. A caller that passes no view keeps the old behaviour. The - `dryrun` command and the traced dry run still read the files for every message. + of the live engine's reference cache does, so a Handler that edits a value it read changes no + later read, in the same preview or a later fixture's. A caller that passes no view still reads + the files on every call: the `dryrun` command and the traced dry run do so for every message. (`BACKLOG #6820`)