diff --git a/changelog.d/6820.changed.md b/changelog.d/6820.changed.md new file mode 100644 index 0000000000..92883b4898 --- /dev/null +++ b/changelog.d/6820.changed.md @@ -0,0 +1,9 @@ +- **`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 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`) 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/checks.py b/messagefoundry/checks.py index ce879e230d..1672d79f78 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, + dry_run_reference_view, + fixture_cap, + read_message_sets, + ) from messagefoundry.redaction import safe_error from messagefoundry.store import MessageStatus @@ -2026,6 +2031,20 @@ 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 reads the same snapshot, and each read + # 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: + 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) @@ -2037,7 +2056,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 4dc9095a4c..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 @@ -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 @@ -83,6 +83,7 @@ "transform_one", "disposition_for", "dry_run", + "dry_run_reference_view", "select_inbound", "AmbiguousInboundError", "NoInboundError", @@ -239,10 +240,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) @@ -604,21 +608,50 @@ 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]]: +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 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 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.""" + 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": @@ -627,16 +660,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(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 # 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) @@ -720,6 +753,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. @@ -747,6 +781,14 @@ 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; 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 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 @@ -757,11 +799,12 @@ 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) + 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] = [] @@ -957,6 +1000,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. @@ -987,6 +1031,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( @@ -1097,6 +1142,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. @@ -1124,6 +1170,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 @@ -1141,7 +1190,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) @@ -1153,17 +1209,23 @@ 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). 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 return DryRunResult( 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) - 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, @@ -1200,6 +1262,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_dryrun.py b/tests/test_dryrun.py index 6297835eee..78be13e54d 100644 --- a/tests/test_dryrun.py +++ b/tests/test_dryrun.py @@ -853,3 +853,49 @@ 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 + + +# --- 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 == [] diff --git a/tests/test_reference_sets.py b/tests/test_reference_sets.py index 96cea3b208..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()) @@ -1212,3 +1212,133 @@ 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: 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 _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 + + loads: list[str] = [] + + def counting(path: str) -> Any: + loads.append(path) + 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"] + + 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 == [] + + 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 _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(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" + f"def h(m):\n{handler_body}", + encoding="utf-8", + ) + msgs = tmp_path / "messages" + msgs.mkdir() + 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, suppress_search=True) + assert result.ok, 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"}