From 5d743f53a6e72c6cb6717f9dafbcaed2e66f2d5f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:01:30 -0600 Subject: [PATCH 01/14] dryrun trace: keep --show-phi values valid JSON for NaN, Infinity and huge ints Under show_phi=True, _safe_value passed a NaN/Infinity float through, so the CLI's json.dumps wrote the bare tokens NaN/Infinity, which RFC 8259 rejects, and an int past the 4300-digit int-to-str limit made json.dumps raise ValueError. A non-finite float is now repr'd ("nan", "inf", "-inf") and an int longer than the 120-character value cap becomes "", found by comparison so the conversion that raises never runs. BACKLOG #6822 (Argon RC-S08-37). Verdict: real defect; the new test failed before the fix. Proposed PR title: dryrun trace: --show-phi values stay valid JSON for NaN, Infinity and huge ints (BACKLOG #6822) Proposed banner: CLOSED -- fixed: _safe_value renders non-finite floats and over-cap ints as strings under --show-phi; failing test plus fix. --- changelog.d/6822.fixed.md | 5 +++ messagefoundry/pipeline/dryrun_trace.py | 14 ++++++-- tests/test_dryrun_trace.py | 45 +++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 changelog.d/6822.fixed.md diff --git a/changelog.d/6822.fixed.md b/changelog.d/6822.fixed.md new file mode 100644 index 0000000000..4d955a6849 --- /dev/null +++ b/changelog.d/6822.fixed.md @@ -0,0 +1,5 @@ +`messagefoundry dryrun --trace --show-phi` now writes valid JSON when a traced local holds a NaN or +Infinity float, which it renders as the string `"nan"`, `"inf"` or `"-inf"`, or an int longer than +120 characters, which it renders as `""`. Before, the trace carried the bare tokens +`NaN`/`Infinity`, which JSON does not allow, and an int past the interpreter's 4300-digit conversion +limit made the command fail with a `ValueError`. diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 43303faf38..02b21a5557 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -62,6 +62,7 @@ from __future__ import annotations import inspect +import math import sys from collections.abc import Iterator from contextlib import contextmanager @@ -92,6 +93,8 @@ # in full even under --show-phi. _MAX_EVENTS = 5000 _MAX_VALUE_LEN = 120 +# The bound below which an int's decimal form, sign included, fits in _MAX_VALUE_LEN characters. +_MAX_INT_MAGNITUDE = 10 ** (_MAX_VALUE_LEN - 1) # --- value serialization (PHI-gated) ----------------------------------------- @@ -102,11 +105,18 @@ def _safe_value(value: object, show_phi: bool) -> Any: Without ``show_phi`` every value collapses to ``"REDACTED"`` (values are message-derived, hence PHI). With it, scalars pass through and any other object is ``repr``'d; both are length-capped so a full - message body can never be dumped.""" + message body can never be dumped. A NaN/Infinity float is ``repr``'d and an int longer than the cap + becomes a placeholder, because ``json.dumps`` would otherwise write a token RFC 8259 rejects or, past + the interpreter's int-to-str digit limit, raise (BACKLOG #6822).""" if not show_phi: return "REDACTED" - if value is None or isinstance(value, (bool, int, float)): + if value is None or isinstance(value, bool): return value + if isinstance(value, float): + return value if math.isfinite(value) else repr(value) + if isinstance(value, int): + # Compared, never str()'d: converting a huge int is itself what raises. + return value if abs(value) < _MAX_INT_MAGNITUDE else "" if isinstance(value, str): text = value else: diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 65257e1c99..9390fa5902 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -568,6 +568,51 @@ def test_cli_trace_show_phi(tmp_path: Path, capsys) -> None: assert any(w["path"] == "MSH-3" and w["value"] == "FOUNDRY" for w in writes) +# --- BACKLOG #6822: --show-phi values must still serialize as RFC 8259 JSON -------------------- + + +def handle_non_json_numbers(msg: Message) -> Send: + nan = float("nan") + pos_inf = float("inf") + neg_inf = float("-inf") + huge = 10**5000 # past CPython's default 4300-digit int-to-str limit + _unused = (nan, pos_inf, neg_inf, huge) + return Send("out", msg) + + +def handle_ordinary_numbers(msg: Message) -> Send: + count = 42 + ratio = 0.5 + big = 1 - 10**119 # 120 characters with the sign: the longest int still kept as a JSON number + too_long = -(10**119) # 121 characters: one past the cap + flag = True + _unused = (count, ratio, big, too_long, flag) + return Send("out", msg) + + +def test_show_phi_values_serialize_as_strict_json() -> None: + # Under --show-phi a NaN/Infinity float passed through unchanged, so the CLI's json.dumps wrote the + # bare tokens NaN/Infinity (not JSON), and a >4300-digit int made json.dumps raise ValueError. + reg = _registry(route_to_h, {"h": handle_non_json_numbers}) + traced = trace_dry_run(reg, ADT_A01, show_phi=True) + text = json.dumps(traced, allow_nan=False) # raises on NaN/Infinity or an unprintable int + assigned = _all_assigned(_handler_invocation(json.loads(text))) + assert assigned["nan"] == "nan" + assert assigned["pos_inf"] == "inf" + assert assigned["neg_inf"] == "-inf" + assert assigned["huge"] == "" + + +def test_show_phi_keeps_ordinary_numbers_as_numbers() -> None: + reg = _registry(route_to_h, {"h": handle_ordinary_numbers}) + assigned = _all_assigned(_handler_invocation(trace_dry_run(reg, ADT_A01, show_phi=True))) + assert assigned["count"] == 42 + assert assigned["ratio"] == 0.5 + assert assigned["big"] == 1 - 10**119 + assert assigned["too_long"] == "" + assert assigned["flag"] is True + + # --- ADR 0084: an `accepts=` decline is surfaced in the trace ---------------------------------- From ef20e66e6f1a25bcdf242ef85c8e119e9d3b14f5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:15:26 -0600 Subject: [PATCH 02/14] dryrun trace: review round 1 repairs for the --show-phi number fix Check numbers by type() and call no subclass hook (no abs, repr or comparison on a user subclass), tag non-finite floats as "" etc., keep an over-cap int's 120-character prefix like a long string and use the placeholder only past the int-to-str digit limit, fix the positive-boundary off-by-one, and give the changelog fragment the bullet format the checker requires. Tests add the hostile-subclass case, the untraced-disposition comparison, the positive boundary and the real CLI serializer. BACKLOG #6822 Proposed PR title: dryrun trace: --show-phi values stay valid JSON for NaN, Infinity and huge ints (BACKLOG #6822) Proposed banner: CLOSED -- fixed: _safe_value renders non-finite floats and over-cap ints as strings under --show-phi; failing test plus fix. --- changelog.d/6822.fixed.md | 11 +-- messagefoundry/pipeline/dryrun_trace.py | 33 +++++---- tests/test_dryrun_trace.py | 92 +++++++++++++++++++++---- 3 files changed, 105 insertions(+), 31 deletions(-) diff --git a/changelog.d/6822.fixed.md b/changelog.d/6822.fixed.md index 4d955a6849..b554fbb289 100644 --- a/changelog.d/6822.fixed.md +++ b/changelog.d/6822.fixed.md @@ -1,5 +1,6 @@ -`messagefoundry dryrun --trace --show-phi` now writes valid JSON when a traced local holds a NaN or -Infinity float, which it renders as the string `"nan"`, `"inf"` or `"-inf"`, or an int longer than -120 characters, which it renders as `""`. Before, the trace carried the bare tokens -`NaN`/`Infinity`, which JSON does not allow, and an int past the interpreter's 4300-digit conversion -limit made the command fail with a `ValueError`. +- **`dryrun --trace --show-phi` now always writes valid JSON.** A traced value that was a NaN or + Infinity float came out as the bare token `NaN` or `Infinity`, which JSON does not allow, and an + int past the interpreter's 4300-digit conversion limit made the command fail with a `ValueError`. + Such a float is now shown as `""`, `""` or `""`, an int past + that limit as `""`, and any other int longer than 120 characters is cut to 120 + like a long string. (`BACKLOG #6822`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 02b21a5557..849bb8d9ac 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -93,8 +93,6 @@ # in full even under --show-phi. _MAX_EVENTS = 5000 _MAX_VALUE_LEN = 120 -# The bound below which an int's decimal form, sign included, fits in _MAX_VALUE_LEN characters. -_MAX_INT_MAGNITUDE = 10 ** (_MAX_VALUE_LEN - 1) # --- value serialization (PHI-gated) ----------------------------------------- @@ -105,19 +103,30 @@ def _safe_value(value: object, show_phi: bool) -> Any: Without ``show_phi`` every value collapses to ``"REDACTED"`` (values are message-derived, hence PHI). With it, scalars pass through and any other object is ``repr``'d; both are length-capped so a full - message body can never be dumped. A NaN/Infinity float is ``repr``'d and an int longer than the cap - becomes a placeholder, because ``json.dumps`` would otherwise write a token RFC 8259 rejects or, past - the interpreter's int-to-str digit limit, raise (BACKLOG #6822).""" + message body can never be dumped. A NaN/Infinity float becomes a tagged string and an over-cap int is + truncated like a string, because ``json.dumps`` would otherwise write a token RFC 8259 rejects or, + past the interpreter's int-to-str digit limit, raise (BACKLOG #6822). The numeric checks go by + ``type()`` and call no hook a subclass defines, so the observer never runs user code there.""" if not show_phi: return "REDACTED" - if value is None or isinstance(value, bool): + if value is None or type(value) is bool: return value - if isinstance(value, float): - return value if math.isfinite(value) else repr(value) - if isinstance(value, int): - # Compared, never str()'d: converting a huge int is itself what raises. - return value if abs(value) < _MAX_INT_MAGNITUDE else "" - if isinstance(value, str): + cls = type(value) + if issubclass(cls, float) and isinstance(value, float): # isinstance only narrows for mypy + # math.isnan/isinf/copysign read the C double directly; a comparison would call __gt__. + if math.isnan(value): + return "" + if math.isinf(value): + return "" if math.copysign(1.0, value) > 0 else "" + return value + if issubclass(cls, int): + try: + text = int.__repr__(value) + except ValueError: # past sys.get_int_max_str_digits(): json.dumps would raise the same + return "" + if len(text) <= _MAX_VALUE_LEN: + return value + elif isinstance(value, str): text = value else: try: diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 9390fa5902..0222725327 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -583,36 +583,100 @@ def handle_non_json_numbers(msg: Message) -> Send: def handle_ordinary_numbers(msg: Message) -> Send: count = 42 ratio = 0.5 - big = 1 - 10**119 # 120 characters with the sign: the longest int still kept as a JSON number - too_long = -(10**119) # 121 characters: one past the cap + pos_cap = 10**119 # 120 characters: the longest int still kept as a JSON number + neg_cap = 1 - 10**119 # 120 characters with the sign + over_cap = -(10**119) # 121 characters: truncated like a string flag = True - _unused = (count, ratio, big, too_long, flag) + _unused = (count, ratio, pos_cap, neg_cap, over_cap, flag) return Send("out", msg) +class _HostileInt(int): + def __abs__(self) -> int: + raise RuntimeError("user __abs__ ran") + + def __repr__(self) -> str: + raise RuntimeError("user __repr__ ran") + + +class _HostileFloat(float): + def __repr__(self) -> str: + raise RuntimeError("user __repr__ ran") + + def __gt__(self, other: object) -> bool: + raise RuntimeError("user __gt__ ran") + + +def handle_hostile_numbers(msg: Message) -> Send: + h_int = _HostileInt(10**200) + h_nan = _HostileFloat("nan") + h_inf = _HostileFloat("inf") + _unused = (h_int, h_nan, h_inf) + return Send("out", msg) + + +def _strict_assigned(handler) -> dict: + reg = _registry(route_to_h, {"h": handler}) + traced = trace_dry_run(reg, ADT_A01, show_phi=True) + # The traced run stays a pure observer: same disposition as the untraced one (ADR 0072 gate 1). + assert traced["disposition"] == dry_run(reg, ADT_A01).disposition.value + text = json.dumps(traced, allow_nan=False) # raises on NaN/Infinity or an unprintable int + return _all_assigned(_handler_invocation(json.loads(text))) + + def test_show_phi_values_serialize_as_strict_json() -> None: # Under --show-phi a NaN/Infinity float passed through unchanged, so the CLI's json.dumps wrote the # bare tokens NaN/Infinity (not JSON), and a >4300-digit int made json.dumps raise ValueError. - reg = _registry(route_to_h, {"h": handle_non_json_numbers}) - traced = trace_dry_run(reg, ADT_A01, show_phi=True) - text = json.dumps(traced, allow_nan=False) # raises on NaN/Infinity or an unprintable int - assigned = _all_assigned(_handler_invocation(json.loads(text))) - assert assigned["nan"] == "nan" - assert assigned["pos_inf"] == "inf" - assert assigned["neg_inf"] == "-inf" + assigned = _strict_assigned(handle_non_json_numbers) + assert assigned["nan"] == "" + assert assigned["pos_inf"] == "" + assert assigned["neg_inf"] == "" assert assigned["huge"] == "" def test_show_phi_keeps_ordinary_numbers_as_numbers() -> None: - reg = _registry(route_to_h, {"h": handle_ordinary_numbers}) - assigned = _all_assigned(_handler_invocation(trace_dry_run(reg, ADT_A01, show_phi=True))) + assigned = _strict_assigned(handle_ordinary_numbers) assert assigned["count"] == 42 assert assigned["ratio"] == 0.5 - assert assigned["big"] == 1 - 10**119 - assert assigned["too_long"] == "" + assert assigned["pos_cap"] == 10**119 + assert assigned["neg_cap"] == 1 - 10**119 + assert assigned["over_cap"] == str(-(10**119))[:120] + "…(truncated)" assert assigned["flag"] is True +def test_show_phi_numbers_call_no_subclass_hook() -> None: + # The tracer must not run user code a numeric subclass defines, or a traced run could ERROR where + # the untraced one delivers. + assigned = _strict_assigned(handle_hostile_numbers) + assert assigned["h_int"] == str(10**200)[:120] + "…(truncated)" + assert assigned["h_nan"] == "" + assert assigned["h_inf"] == "" + + +def test_cli_trace_show_phi_writes_strict_json(tmp_path: Path, capsys) -> None: + # The real serializer: `dryrun --trace --show-phi` stdout must parse with NaN/Infinity refused. + module = _CONFIG_MODULE.replace( + ' mrn = msg["PID-3.1"]\n', + ' mrn = msg["PID-3.1"]\n nan = float("nan")\n huge = 10**5000\n', + ) + assert module != _CONFIG_MODULE + cfg = tmp_path / "config" + cfg.mkdir() + (cfg / "IB_TEST.py").write_text(module, encoding="utf-8") + msg = tmp_path / "adt.hl7" + msg.write_text(ADT_A01, encoding="utf-8") + rc = main(["dryrun", "--config", str(cfg), "--messages", str(msg), "--trace", "--show-phi"]) + assert rc == 0 + + def _refuse(token: str) -> object: + raise ValueError(f"non-JSON token {token}") + + out = json.loads(capsys.readouterr().out, parse_constant=_refuse) + assigned = _all_assigned(_handler_invocation(out[0])) + assert assigned["nan"] == "" + assert assigned["huge"] == "" + + # --- ADR 0084: an `accepts=` decline is surfaced in the trace ---------------------------------- From c870010624c2cda7eee9f97da2eb19f1a76e4185 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:44:17 -0600 Subject: [PATCH 03/14] dryrun_trace: never drain a Handler's single-pass iterable of Sends _sends_from walked any non-Iterator iterable. An object whose __iter__ returns a stored generator is single-pass but not an Iterator, so the trace observer exhausted it before dryrun._partition ran: the traced run read FILTERED with zero deliveries where the untraced run delivered (reproduced by the new test before the fix). The Handler half now walks the same re-iterable allowlist as the Router half and declares any other iterable return with lazy_result. BACKLOG #6823 Proposed banner: FIXED - traced dry run walks only re-iterable Handler containers; a single-pass iterable of Sends is declared lazy_result and no longer drained (test + fix). --- changelog.d/6823.fixed.md | 6 +++ messagefoundry/pipeline/dryrun_trace.py | 37 ++++++++++++++----- tests/test_dryrun_trace.py | 49 +++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 9 deletions(-) create mode 100644 changelog.d/6823.fixed.md diff --git a/changelog.d/6823.fixed.md b/changelog.d/6823.fixed.md new file mode 100644 index 0000000000..14ec275ac9 --- /dev/null +++ b/changelog.d/6823.fixed.md @@ -0,0 +1,6 @@ +- **A traced dry run no longer drains a Handler's single-pass iterable of `Send`s.** A Handler + returning an object whose `__iter__` hands back a stored generator (iterable, but not an + iterator) was walked by the trace observer before the dry run partitioned it, so the traced run + reported `FILTERED` with zero deliveries where the untraced run delivered. The observer now walks + only `list`/`tuple`/`set`/`frozenset`, as the Router half already did, and marks any other + iterable Handler return `lazy_result` instead of reading it. (`BACKLOG #6823`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 849bb8d9ac..c024db14eb 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -64,7 +64,7 @@ import inspect import math import sys -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar from time import perf_counter @@ -80,7 +80,6 @@ RouterFn, Send, accepts_verdict, - handler_result_items, ) from messagefoundry.parsing.message import Message from messagefoundry.pipeline.dryrun import dry_run @@ -168,17 +167,35 @@ def _sends_from(result: object) -> list[str]: :func:`_routed_from`'s long-standing gap for a generator Router, but on the Handler half **this change opened it**: before BACKLOG #341 a generator Handler delivered nothing at all, so reporting no sends was exact rather than a degradation. The caller marks the invocation ``lazy_result`` so - the gap is declared to the consumer instead of read as an inert handler (ADR 0072 §6 gate 1).""" + the gap is declared to the consumer instead of read as an inert handler (ADR 0072 §6 gate 1). + + **"Not an Iterator" is not "safe to walk"** (BACKLOG #6823), the same defect the Router half hit + under BACKLOG #1694: an object whose ``__iter__`` hands back a stored generator is single-pass yet + no ``Iterator``, and walking it here left ``_partition`` an empty iterable, so a delivering run + traced as FILTERED. Only the re-iterable containers in :data:`_ROUTED_CONTAINERS` are walked; any + other iterable is reported as no sends and declared by :func:`_handler_return_is_untraceable`.""" if result is None: return [] - if isinstance(result, Iterator): + if isinstance(result, _ROUTED_CONTAINERS): + items: Iterable[object] = result + elif _handler_return_is_untraceable(result): return [] - items = handler_result_items(result) - if items is None: - items = [result] + else: + items = [result] # a single value, as `handler_result_items` treats a non-iterable return [it.to for it in items if isinstance(it, Send)] +def _handler_return_is_untraceable(result: object) -> bool: + """True when :func:`_sends_from` declines to walk this Handler return, so the record is incomplete. + + Drives ``lazy_result`` for the Handler half. It names exactly the shapes ``_partition`` + materializes as a container (any ``Iterable`` but ``str``/``bytes``/``bytearray``) that are not + known to be re-iterable: a generator, and a custom single-pass iterable.""" + return isinstance(result, Iterable) and not isinstance( + result, (str, bytes, bytearray, *_ROUTED_CONTAINERS) + ) + + #: Router-return containers this observer will walk: re-iterable, and walking one consumes nothing. #: #: An ALLOWLIST rather than ``isinstance(result, Iterable)``, and the difference is a real defect the @@ -331,11 +348,13 @@ def record_return(self, result: object) -> None: if self.kind == "router": # Widen the declaration for the Router half: `_routed_from` walks an allowlist, so a # single-pass custom iterable or a `__getitem__`-only sequence is equally untraced and - # must say so. The Handler half keeps the Iterator test -- `_sends_from` still routes - # through `handler_result_items`, which has its own rule. + # must say so. self.lazy_result = self.lazy_result or _router_return_is_untraceable(result) self.routed_to = _routed_from(result) elif self.kind == "handler": + # The Handler half walks the same allowlist, so its declaration widens the same way + # (BACKLOG #6823): a single-pass custom iterable is untraced, not "sent nothing". + self.lazy_result = self.lazy_result or _handler_return_is_untraceable(result) self.sends = _sends_from(result) # An "accepts" predicate (ADR 0084) returns a bool — it has neither routed_to nor sends, and its # verdict is reported at message level (`accepts_declined`). Named explicitly so it isn't quietly diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 0222725327..d3c5d7d355 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -21,6 +21,8 @@ from collections.abc import Iterator from pathlib import Path +import pytest + from messagefoundry.__main__ import main from messagefoundry.config.db_lookup import db_lookup from messagefoundry.config.fhir_lookup import fhir_lookup @@ -342,6 +344,53 @@ def test_gate_1b_a_generator_invocation_declares_lazy_result() -> None: assert control_inv["sends"] == [{"outbound": "out"}] and control_inv["events"] +class _SinglePassSends: + """A Handler's single-pass Iterable of ``Send``s: ``__iter__`` returns one stored generator. + + Not an ``Iterator``, so the ``Iterator`` guard alone let ``_sends_from`` walk it, drain it, and + hand ``_partition`` an empty iterable (BACKLOG #6823).""" + + def __init__(self, *items: Send) -> None: + self._gen = (i for i in items) + + def __iter__(self) -> Iterator[Send]: + return self._gen + + +def handle_single_pass(msg: Message) -> _SinglePassSends: + return _SinglePassSends(Send("out", msg), Send("out2", msg)) + + +def test_gate_1a_a_single_pass_iterable_handler_traces_byte_identically() -> None: + """ADR 0072 gate 1a for a Handler returning a single-pass Iterable that is not an Iterator. + + Walking it in the observer exhausted it, so the traced run reported FILTERED with zero + deliveries while the untraced run delivered two (BACKLOG #6823). The untraced side is asserted + to deliver first, so the test cannot pass by both runs delivering nothing. The under-report on + the invocation is declared with ``lazy_result``, as for a generator Handler.""" + plain = dry_run(_two_out_registry(handle_single_pass), ADT_A01) + traced = trace_dry_run(_two_out_registry(handle_single_pass), ADT_A01) + + assert [d.to for d in plain.deliveries] == ["out", "out2"] + assert [s["outbound"] for s in traced["sends"]] == [d.to for d in plain.deliveries] + assert traced["disposition"] == plain.disposition.value + inv = _handler_invocation(traced) + assert inv["sends"] == [] + assert inv["lazy_result"] is True + + +@pytest.mark.parametrize("make", [list, tuple, set, frozenset]) +def test_handler_invocation_still_traces_re_iterable_containers(make: type) -> None: + """Control for the allowlist: re-iterable containers are still walked and not marked lazy.""" + + def handle(msg: Message) -> object: + return make([Send("out", msg), Send("out2", msg)]) + + inv = _handler_invocation(trace_dry_run(_two_out_registry(handle), ADT_A01)) + assert sorted(s["outbound"] for s in inv["sends"]) == ["out", "out2"] + assert "lazy_result" not in inv + + def test_gate_byte_identical_unrouted_and_filtered() -> None: unrouted = trace_dry_run(_registry(lambda m: [], {}), ADT_A01) assert unrouted["disposition"] == MessageStatus.UNROUTED.value From a38471d8424f27f909f608eb7567ba49cb6b4eb3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 00:57:58 -0600 Subject: [PATCH 04/14] dryrun_trace: test the Handler allowlist on the exact type Review round 1: a list subclass with a single-pass __iter__, or one that is its own Iterator, passed isinstance(result, list) and was still drained. Walk only the exact builtin types, derive the Handler's lazy_result from the one predicate, and fix the docstrings that still described the removed Iterator guard. BACKLOG #6823 --- messagefoundry/pipeline/dryrun_trace.py | 44 ++++++++++++--------- tests/test_dryrun_trace.py | 51 ++++++++++++++++++++++++- 2 files changed, 75 insertions(+), 20 deletions(-) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index c024db14eb..c2256e9868 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -69,7 +69,7 @@ from contextvars import ContextVar from time import perf_counter from types import CodeType, FrameType -from typing import Any +from typing import Any, cast from messagefoundry.config.db_lookup import DbLookupError from messagefoundry.config.fhir_lookup import FhirLookupError @@ -157,10 +157,9 @@ def _safe_snapshot(frame: FrameType) -> dict[str, Any]: def _sends_from(result: object) -> list[str]: """Outbound names in a Handler's raw return (``Send``/``SetState``/an iterable/``None``) — mirrors the ``Send`` half of :func:`messagefoundry.pipeline.dryrun._partition`, name-only (no payload = no - PHI). It shares that function's materialization rule so the trace does not drift from what actually - delivers now that any non-``str`` iterable fans out (BACKLOG #341). + PHI). It reports a subset of what that function delivers, never a substitute (ADR 0072 gate 1b). - **One deliberate divergence: a one-shot iterator is never consumed.** A generator Handler is + **It never walks a return it cannot prove re-iterable.** A generator Handler is reported as no sends rather than drained here, because this hook is a *pure observer* — exhausting the generator would leave ``_partition`` nothing to partition, so the traced run would deliver 0 where the untraced run delivers N. Under-reporting is the only safe option; it is symmetric with @@ -169,15 +168,15 @@ def _sends_from(result: object) -> list[str]: no sends was exact rather than a degradation. The caller marks the invocation ``lazy_result`` so the gap is declared to the consumer instead of read as an inert handler (ADR 0072 §6 gate 1). - **"Not an Iterator" is not "safe to walk"** (BACKLOG #6823), the same defect the Router half hit - under BACKLOG #1694: an object whose ``__iter__`` hands back a stored generator is single-pass yet - no ``Iterator``, and walking it here left ``_partition`` an empty iterable, so a delivering run - traced as FILTERED. Only the re-iterable containers in :data:`_ROUTED_CONTAINERS` are walked; any - other iterable is reported as no sends and declared by :func:`_handler_return_is_untraceable`.""" + "Not an ``Iterator``" is not "safe to walk" either (BACKLOG #6823): see + :data:`_ROUTED_CONTAINERS`. Only those exact builtin types are walked, since a subclass may + override ``__iter__``; any other iterable is reported as no sends and declared by + :func:`_handler_return_is_untraceable`. A re-iterable shape outside that set, such as a + ``deque``, therefore under-reports too.""" if result is None: return [] - if isinstance(result, _ROUTED_CONTAINERS): - items: Iterable[object] = result + if type(result) in _ROUTED_CONTAINERS: + items: Iterable[object] = cast("Iterable[object]", result) elif _handler_return_is_untraceable(result): return [] else: @@ -185,14 +184,21 @@ def _sends_from(result: object) -> list[str]: return [it.to for it in items if isinstance(it, Send)] +#: What ``handler_result_items`` treats as a single value although it is ``Iterable``. Kept in step +#: with that function's carve-out, which ``_partition`` applies. +_HANDLER_SINGLE_VALUES = (str, bytes, bytearray) + + def _handler_return_is_untraceable(result: object) -> bool: """True when :func:`_sends_from` declines to walk this Handler return, so the record is incomplete. - Drives ``lazy_result`` for the Handler half. It names exactly the shapes ``_partition`` - materializes as a container (any ``Iterable`` but ``str``/``bytes``/``bytearray``) that are not - known to be re-iterable: a generator, and a custom single-pass iterable.""" - return isinstance(result, Iterable) and not isinstance( - result, (str, bytes, bytearray, *_ROUTED_CONTAINERS) + Drives ``lazy_result`` for the Handler half: an ``Iterable`` that ``_partition`` materializes as + a container and whose exact type is not in :data:`_ROUTED_CONTAINERS`. At least a generator, a + custom single-pass iterable and a builtin-container subclass are such returns.""" + return ( + isinstance(result, Iterable) + and not isinstance(result, _HANDLER_SINGLE_VALUES) + and type(result) not in _ROUTED_CONTAINERS ) @@ -353,8 +359,10 @@ def record_return(self, result: object) -> None: self.routed_to = _routed_from(result) elif self.kind == "handler": # The Handler half walks the same allowlist, so its declaration widens the same way - # (BACKLOG #6823): a single-pass custom iterable is untraced, not "sent nothing". - self.lazy_result = self.lazy_result or _handler_return_is_untraceable(result) + # (BACKLOG #6823): a single-pass custom iterable is untraced, not "sent nothing". The + # predicate also covers a generator, and replaces the Iterator test so the flag and + # `_sends_from` cannot disagree on an Iterator that subclasses a builtin container. + self.lazy_result = _handler_return_is_untraceable(result) self.sends = _sends_from(result) # An "accepts" predicate (ADR 0084) returns a bool — it has neither routed_to nor sends, and its # verdict is reported at message level (`accepts_declined`). Named explicitly so it isn't quietly diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index d3c5d7d355..2053dd93a1 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -308,8 +308,9 @@ def test_gate_1a_a_generator_handler_traces_byte_identically_at_message_level() non-``str`` iterable, and materialising a generator CONSUMES it. Mirroring that rule literally would leave the real ``_partition`` an exhausted iterator, so the *traced* run would deliver 0 where the untraced run delivers 2: a tracer that changes the disposition, which is the one thing - ADR 0072 forbids. The two-line ``isinstance(result, Iterator)`` guard in ``_sends_from`` is what - prevents it, and before this test nothing covered it — deleting the guard left the whole tracer + ADR 0072 forbids. ``_sends_from``'s refusal to walk a return it cannot prove re-iterable (an + ``isinstance(result, Iterator)`` guard until BACKLOG #6823) is what prevents it, and before this + test nothing covered it — deleting the guard left the whole tracer suite green while turning a traced generator Handler into an accept-and-drop. The untraced side is asserted non-empty first, so this cannot pass by both runs delivering nothing @@ -379,6 +380,52 @@ def test_gate_1a_a_single_pass_iterable_handler_traces_byte_identically() -> Non assert inv["lazy_result"] is True +class _GenList(list[Send]): + """A ``list`` subclass whose ``__iter__`` is single-pass: ``isinstance(x, list)`` is True.""" + + def __init__(self, *items: Send) -> None: + super().__init__(items) + self._gen = (i for i in items) + + def __iter__(self) -> Iterator[Send]: + return self._gen + + +class _IterList(list[Send]): + """A ``list`` subclass that is also its own one-shot ``Iterator``.""" + + def __init__(self, *items: Send) -> None: + super().__init__(items) + self._pos = 0 + + def __iter__(self) -> _IterList: + return self + + def __next__(self) -> Send: + if self._pos >= len(self): + raise StopIteration + self._pos += 1 + return list.__getitem__(self, self._pos - 1) + + +@pytest.mark.parametrize("cls", [_GenList, _IterList]) +def test_gate_1a_a_single_pass_container_subclass_handler_is_not_drained(cls: type) -> None: + """The allowlist is tested on the EXACT type: a builtin-container subclass may be single-pass.""" + + def handle(msg: Message) -> object: + return cls(Send("out", msg), Send("out2", msg)) + + plain = dry_run(_two_out_registry(handle), ADT_A01) + traced = trace_dry_run(_two_out_registry(handle), ADT_A01) + + assert [d.to for d in plain.deliveries] == ["out", "out2"] + assert [s["outbound"] for s in traced["sends"]] == [d.to for d in plain.deliveries] + assert traced["disposition"] == plain.disposition.value + inv = _handler_invocation(traced) + assert inv["sends"] == [] + assert inv["lazy_result"] is True + + @pytest.mark.parametrize("make", [list, tuple, set, frozenset]) def test_handler_invocation_still_traces_re_iterable_containers(make: type) -> None: """Control for the allowlist: re-iterable containers are still walked and not marked lazy.""" From e6ff111f6a1d7b653f09d4432539e7ba7b6adeca Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:08:29 -0600 Subject: [PATCH 05/14] dryrun_trace: one lazy_result rule per half, accurate changelog Review round 2: drop the dead Iterator check on the Handler path and correct the changelog and comment that said the Handler walks the allowlist "as the Router half already did" (the Router half still uses isinstance, so a container subclass there is reported, not fixed here). BACKLOG #6823 Proposed banner: FIXED - traced dry run walks a Handler return only when its exact type is list/tuple/set/frozenset; a single-pass iterable of Sends (or a single-pass container subclass) is declared lazy_result and no longer drained (test + fix). Open findings in the PR body. --- changelog.d/6823.fixed.md | 13 +++++++------ messagefoundry/pipeline/dryrun_trace.py | 21 +++++++++------------ 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/changelog.d/6823.fixed.md b/changelog.d/6823.fixed.md index 14ec275ac9..872971d73e 100644 --- a/changelog.d/6823.fixed.md +++ b/changelog.d/6823.fixed.md @@ -1,6 +1,7 @@ -- **A traced dry run no longer drains a Handler's single-pass iterable of `Send`s.** A Handler - returning an object whose `__iter__` hands back a stored generator (iterable, but not an - iterator) was walked by the trace observer before the dry run partitioned it, so the traced run - reported `FILTERED` with zero deliveries where the untraced run delivered. The observer now walks - only `list`/`tuple`/`set`/`frozenset`, as the Router half already did, and marks any other - iterable Handler return `lazy_result` instead of reading it. (`BACKLOG #6823`) +- **A traced dry run no longer drains a Handler's single-pass iterable of `Send`s by walking it.** + A Handler returning an object whose `__iter__` hands back a stored generator (iterable, but not + an iterator) was walked by the trace observer before the dry run partitioned it, so the traced + run reported `FILTERED` with zero deliveries where the untraced run delivered. The observer now + walks a Handler return only when its exact type is `list`/`tuple`/`set`/`frozenset`, and marks + any other iterable Handler return `lazy_result` instead of reading it, so such an invocation + reports no per-invocation sends. (`BACKLOG #6823`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index c2256e9868..a3d3fc79cd 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -344,24 +344,21 @@ def record_write(self, path: str, value: object) -> None: # terminal classification -------------------------------------------------- def record_return(self, result: object) -> None: - if self.kind in ("router", "handler"): - # A generator function returns WITHOUT running its body, so this record is structurally - # incomplete (no line events, no measurable sends/routed_to) — declare that rather than - # let a consumer read an empty record as "this handler did nothing". Set for BOTH halves: - # the Router gap is long-standing, the Handler gap was opened by BACKLOG #341 widening - # `_partition` so a generator Handler now delivers. - self.lazy_result = isinstance(result, Iterator) + # A generator function returns WITHOUT running its body, so this record is structurally + # incomplete (no line events, no measurable sends/routed_to) — declare that rather than let a + # consumer read an empty record as "this handler did nothing". Set for BOTH halves: the Router + # gap is long-standing, the Handler gap was opened by BACKLOG #341 widening `_partition` so a + # generator Handler now delivers. if self.kind == "router": # Widen the declaration for the Router half: `_routed_from` walks an allowlist, so a # single-pass custom iterable or a `__getitem__`-only sequence is equally untraced and # must say so. - self.lazy_result = self.lazy_result or _router_return_is_untraceable(result) + self.lazy_result = isinstance(result, Iterator) or _router_return_is_untraceable(result) self.routed_to = _routed_from(result) elif self.kind == "handler": - # The Handler half walks the same allowlist, so its declaration widens the same way - # (BACKLOG #6823): a single-pass custom iterable is untraced, not "sent nothing". The - # predicate also covers a generator, and replaces the Iterator test so the flag and - # `_sends_from` cannot disagree on an Iterator that subclasses a builtin container. + # The Handler half walks the exact types in the same allowlist (BACKLOG #6823), so a + # single-pass custom iterable or container subclass is untraced, not "sent nothing". The + # predicate also covers a generator, so the flag and `_sends_from` share one rule. self.lazy_result = _handler_return_is_untraceable(result) self.sends = _sends_from(result) # An "accepts" predicate (ADR 0084) returns a bool — it has neither routed_to nor sends, and its From 266da4048097353972c9c46cf29aa6d6f88d3cd0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 01:28:12 -0600 Subject: [PATCH 06/14] dryrun_trace: identity type test; docs match the shipped lazy_result Manager follow-up on review round 3. The exact-container test now uses identity, so no user metaclass __eq__ runs in the observer. CONNECTIONS.md and USER-GUIDE.md define the Handler's lazy_result as shipped, ADR 0072 gains a dated amendment naming gate 1b and the removed Iterator guard, and the changelog states the str/bytes exclusion. BACKLOG #6823 Proposed banner: FIXED - traced dry run walks a Handler return only when its exact type is list/tuple/set/frozenset; a single-pass iterable of Sends (or a single-pass container subclass) is declared lazy_result and no longer drained (test + fix; docs and ADR 0072 amended). Open findings in the PR body. --- changelog.d/6823.fixed.md | 7 ++++--- docs/CONNECTIONS.md | 14 +++++++++----- docs/USER-GUIDE.md | 2 +- docs/adr/0072-traced-dryrun-mode.md | 16 ++++++++++++++++ messagefoundry/pipeline/dryrun_trace.py | 13 +++++++++++-- 5 files changed, 41 insertions(+), 11 deletions(-) diff --git a/changelog.d/6823.fixed.md b/changelog.d/6823.fixed.md index 872971d73e..2672195ce1 100644 --- a/changelog.d/6823.fixed.md +++ b/changelog.d/6823.fixed.md @@ -2,6 +2,7 @@ A Handler returning an object whose `__iter__` hands back a stored generator (iterable, but not an iterator) was walked by the trace observer before the dry run partitioned it, so the traced run reported `FILTERED` with zero deliveries where the untraced run delivered. The observer now - walks a Handler return only when its exact type is `list`/`tuple`/`set`/`frozenset`, and marks - any other iterable Handler return `lazy_result` instead of reading it, so such an invocation - reports no per-invocation sends. (`BACKLOG #6823`) + walks a Handler return only when its exact type is `list`/`tuple`/`set`/`frozenset`. Any other + iterable Handler return, except `str`/`bytes`/`bytearray` (which are single values), is marked + `lazy_result` instead of read, so such an invocation reports no per-invocation sends. + (`BACKLOG #6823`) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 87cdc34b78..e96d014399 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -290,11 +290,15 @@ duplicate name (across **any** of these files) and an inbound that binds a route > the identical-output-on-re-run property the staged pipeline leans on (CLAUDE.md §2). Which `Send`s > are delivered is unaffected. **Use an ordered container whenever order matters.** > -> A **generator** Handler delivers exactly like a list, but its body runs *after* the execution tracer -> behind `dryrun --trace` (and the Test Bench that reads it) has detached. That invocation's trace -> record therefore carries no executed lines and no sends, marked `"lazy_result": true` so the omission -> is declared rather than read as a handler that did nothing; the run's message-level `sends` are still -> exact. Return a list or tuple if you want the handler's body traced line-by-line. +> The execution tracer behind `dryrun --trace` (and the Test Bench that reads it) reads a Handler's +> per-invocation sends only when the Handler returns an exact `list`, `tuple`, `set` or `frozenset`. +> Any other iterable return (other than `str`/`bytes`/`bytearray`), such as a generator, a `deque`, a +> custom iterable or a subclass of one of those four, may be single-pass, so the tracer does not walk +> it: that invocation's record reports no sends and is marked `"lazy_result": true`, so the omission +> is declared rather than read as a handler that did nothing (BACKLOG #6823). The run's message-level +> `sends` are still exact. A **generator** Handler's body also runs *after* the tracer has detached, +> so its record carries no executed lines either. Return a list or tuple if you want the handler's +> per-invocation sends and body traced. > **Transforms & HL7 escaping.** Writing a **component/subcomponent** (`msg["PID-5.1"] = value`) > stores `value` as a literal: HL7 delimiters in it (`^ ~ & |`) are **escaped** so they stay data diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index e8bbe0d82a..35a844fb13 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -439,7 +439,7 @@ def archive(msg): The `Send` target (`"FILE-OUT_Test_ADT"`) names an `outbound(...)` Connection declared in the same config. To fan out, return a container of `Send`s — e.g. [samples/results_relay/results_relay.py](../samples/results_relay/results_relay.py) ends with `return [Send(OB_EHR, msg), Send(FILE_ARCHIVE, msg)]`. A **list** is the idiom used throughout these docs, but a tuple, a set, or a generator that `yield`s its `Send`s all deliver the same `Send`s; an **empty** container (`return []` / `return ()`) is the filter, exactly like `return None`. Those are the only shapes a Handler may return (a `SetState` / `SetMeta` write counts as a `Send` here). Return the message itself, `msg.encode()`, or a `dict` and the engine raises, naming your handler and the type, and dead-letters the message as `ERROR` — never a silent `FILTERED` you would have to go looking for. -> **Two caveats on the less common shapes.** Fan-out is delivered in iteration order, and a **`set`** has no defined iteration order — it varies per process, so sibling `Send`s to the same outbound queue in an arbitrary order that a crash re-run can change. Use a list or tuple when order matters. And a **generator** Handler's body runs after the `dryrun --trace` execution tracer has detached, so its trace record shows no executed lines and no sends and is marked `"lazy_result": true` (the run's message-level `sends` are still exact) — return a list or tuple if you want it traced line-by-line. Both are documented in full in [CONNECTIONS.md](CONNECTIONS.md). +> **Two caveats on the less common shapes.** Fan-out is delivered in iteration order, and a **`set`** has no defined iteration order — it varies per process, so sibling `Send`s to the same outbound queue in an arbitrary order that a crash re-run can change. Use a list or tuple when order matters. And `dryrun --trace` reads a Handler's per-invocation sends only from an exact `list`, `tuple`, `set` or `frozenset`: any other iterable return (other than `str`/`bytes`/`bytearray`) — a generator, a `deque`, a custom iterable, a subclass of those four — gets a trace record with no sends, marked `"lazy_result": true` (the run's message-level `sends` are still exact). A **generator** Handler's body also runs after the tracer has detached, so its record shows no executed lines either. Return a list or tuple if you want it traced fully. Both are documented in full in [CONNECTIONS.md](CONNECTIONS.md). ### 3. The `Message` operations you'll use diff --git a/docs/adr/0072-traced-dryrun-mode.md b/docs/adr/0072-traced-dryrun-mode.md index 9669674ff3..0afc39bce0 100644 --- a/docs/adr/0072-traced-dryrun-mode.md +++ b/docs/adr/0072-traced-dryrun-mode.md @@ -98,6 +98,22 @@ The sanctioned non-pure reads (ADR 0010/0043) are **unavailable in dry-run and r - **AST instrumentation / bytecode rewriting.** Could attribute values to sub-expressions more precisely, but it rewrites author code, is fragile across Python versions, and risks diverging behavior from the real run (violating the byte-identical guarantee). Rejected for v1; a bounded AST-assisted *value-timing* refinement is a possible v2. - **Enrich the existing `--json` with per-handler attribution only** (add a `handler` tag to `DeliveryPreview`). Cheap, and it would let #92 **v1** show accurate multi-handler summaries — but it yields **no per-statement data**, so it cannot drive #92 v2 or #84 profiling/coverage. Noted as the **owner option** in MULTISESSION-PLAN-7 §H for v1 only; insufficient as the v2 contract. +## Amendment 2026-11-24 (BACKLOG #6823) — `lazy_result` on the Handler half + +The §3 `lazy_result` text and the gate 1b carve-out above are kept as accepted; this note records +what shipped since. Gate 1b names "the `_sends_from` iterator guard". That guard tested +`isinstance(result, Iterator)`, and it was not enough: an object whose `__iter__` returns a stored +generator is single-pass but not an `Iterator`, so the tracer walked it, `_partition` then found it +empty, and a traced run read `FILTERED` with zero deliveries where the untraced run delivered — +a gate 1a break. The guard is removed. The tracer now walks a Handler return only when its exact +type is `list`, `tuple`, `set` or `frozenset` (checked by identity). For any other iterable Handler +return except `str`/`bytes`/`bytearray`, the invocation reports `sends: []` and carries +`"lazy_result": true`. On the Handler half, `lazy_result` therefore means: *the return was such an +iterable, so the trace reports no per-invocation sends*. It no longer implies the body was not +traced: only a generator Handler also has no line events. Gate 1a is unchanged and still absolute. +→ `tests/test_dryrun_trace.py::test_gate_1a_a_single_pass_iterable_handler_traces_byte_identically`, +`tests/test_dryrun_trace.py::test_gate_1a_a_single_pass_container_subclass_handler_is_not_drained`. + --- *This ADR is Proposed / direction-setting. It fixes the trace contract, the capture semantics, the live-lookup rule, and the PHI posture; it is ratified (Accepted) before L5 writes code, and nothing here changes the shipped `dryrun` default.* diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index a3d3fc79cd..dfd6a46aee 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -175,7 +175,7 @@ def _sends_from(result: object) -> list[str]: ``deque``, therefore under-reports too.""" if result is None: return [] - if type(result) in _ROUTED_CONTAINERS: + if _is_exact_container(result): items: Iterable[object] = cast("Iterable[object]", result) elif _handler_return_is_untraceable(result): return [] @@ -189,6 +189,15 @@ def _sends_from(result: object) -> list[str]: _HANDLER_SINGLE_VALUES = (str, bytes, bytearray) +def _is_exact_container(result: object) -> bool: + """True when ``result``'s exact type is one of :data:`_ROUTED_CONTAINERS`. + + Identity, not ``type(result) in ...``: membership compares with ``==``, which would run a user + metaclass ``__eq__`` inside this observer.""" + t = type(result) + return t is list or t is tuple or t is set or t is frozenset + + def _handler_return_is_untraceable(result: object) -> bool: """True when :func:`_sends_from` declines to walk this Handler return, so the record is incomplete. @@ -198,7 +207,7 @@ def _handler_return_is_untraceable(result: object) -> bool: return ( isinstance(result, Iterable) and not isinstance(result, _HANDLER_SINGLE_VALUES) - and type(result) not in _ROUTED_CONTAINERS + and not _is_exact_container(result) ) From d99ae39348daf848833566c44f7984e6f751fbae Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 02:37:30 -0600 Subject: [PATCH 07/14] docs: single-value Sends still traced; note the 0072 amendment Text only. CONNECTIONS.md and USER-GUIDE.md now say plainly that a bare return Send(...) still gets its per-invocation sends. The ADR 0072 Status line and README index row note the 2026-11-24 amendment, which now says it supersedes section 3 and gate 1b on the Handler half. The dryrun_trace module docstring and _Recorder comment describe the wider Handler lazy_result. BACKLOG #6823 --- docs/CONNECTIONS.md | 6 +++--- docs/USER-GUIDE.md | 2 +- docs/adr/0072-traced-dryrun-mode.md | 6 +++--- docs/adr/README.md | 2 +- messagefoundry/pipeline/dryrun_trace.py | 10 +++++++--- 5 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index e96d014399..19d8de846a 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -290,9 +290,9 @@ duplicate name (across **any** of these files) and an inbound that binds a route > the identical-output-on-re-run property the staged pipeline leans on (CLAUDE.md §2). Which `Send`s > are delivered is unaffected. **Use an ordered container whenever order matters.** > -> The execution tracer behind `dryrun --trace` (and the Test Bench that reads it) reads a Handler's -> per-invocation sends only when the Handler returns an exact `list`, `tuple`, `set` or `frozenset`. -> Any other iterable return (other than `str`/`bytes`/`bytearray`), such as a generator, a `deque`, a +> The execution tracer behind `dryrun --trace` (and the Test Bench that reads it) reports a +> Handler's per-invocation sends for a single returned value, such as a bare `return Send(...)`, and +> for an exact `list`, `tuple`, `set` or `frozenset`. Any other iterable return (other than `str`/`bytes`/`bytearray`), such as a generator, a `deque`, a > custom iterable or a subclass of one of those four, may be single-pass, so the tracer does not walk > it: that invocation's record reports no sends and is marked `"lazy_result": true`, so the omission > is declared rather than read as a handler that did nothing (BACKLOG #6823). The run's message-level diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index 35a844fb13..6e3ad416d8 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -439,7 +439,7 @@ def archive(msg): The `Send` target (`"FILE-OUT_Test_ADT"`) names an `outbound(...)` Connection declared in the same config. To fan out, return a container of `Send`s — e.g. [samples/results_relay/results_relay.py](../samples/results_relay/results_relay.py) ends with `return [Send(OB_EHR, msg), Send(FILE_ARCHIVE, msg)]`. A **list** is the idiom used throughout these docs, but a tuple, a set, or a generator that `yield`s its `Send`s all deliver the same `Send`s; an **empty** container (`return []` / `return ()`) is the filter, exactly like `return None`. Those are the only shapes a Handler may return (a `SetState` / `SetMeta` write counts as a `Send` here). Return the message itself, `msg.encode()`, or a `dict` and the engine raises, naming your handler and the type, and dead-letters the message as `ERROR` — never a silent `FILTERED` you would have to go looking for. -> **Two caveats on the less common shapes.** Fan-out is delivered in iteration order, and a **`set`** has no defined iteration order — it varies per process, so sibling `Send`s to the same outbound queue in an arbitrary order that a crash re-run can change. Use a list or tuple when order matters. And `dryrun --trace` reads a Handler's per-invocation sends only from an exact `list`, `tuple`, `set` or `frozenset`: any other iterable return (other than `str`/`bytes`/`bytearray`) — a generator, a `deque`, a custom iterable, a subclass of those four — gets a trace record with no sends, marked `"lazy_result": true` (the run's message-level `sends` are still exact). A **generator** Handler's body also runs after the tracer has detached, so its record shows no executed lines either. Return a list or tuple if you want it traced fully. Both are documented in full in [CONNECTIONS.md](CONNECTIONS.md). +> **Two caveats on the less common shapes.** Fan-out is delivered in iteration order, and a **`set`** has no defined iteration order — it varies per process, so sibling `Send`s to the same outbound queue in an arbitrary order that a crash re-run can change. Use a list or tuple when order matters. And `dryrun --trace` reports a Handler's per-invocation sends for a single returned value (a bare `return Send(...)`) and for an exact `list`, `tuple`, `set` or `frozenset`; any other iterable return (other than `str`/`bytes`/`bytearray`) — a generator, a `deque`, a custom iterable, a subclass of those four — gets a trace record with no sends, marked `"lazy_result": true` (the run's message-level `sends` are still exact). A **generator** Handler's body also runs after the tracer has detached, so its record shows no executed lines either. Return a list or tuple if you want it traced fully. Both are documented in full in [CONNECTIONS.md](CONNECTIONS.md). ### 3. The `Message` operations you'll use diff --git a/docs/adr/0072-traced-dryrun-mode.md b/docs/adr/0072-traced-dryrun-mode.md index 0afc39bce0..914ef4390f 100644 --- a/docs/adr/0072-traced-dryrun-mode.md +++ b/docs/adr/0072-traced-dryrun-mode.md @@ -1,6 +1,6 @@ # ADR 0072 — Traced dry-run mode: `dryrun --trace json` for the interactive live-debug loop -**Status:** Accepted (2026-07-06). Ratified by the owner — the engine lane (MULTISESSION-PLAN-7 **L5**) may build. The traced mode is **additive + opt-in**; nothing here changes the shipped `dryrun` default. The §6 test gates are the acceptance criteria (byte-identical run · live-lookup identical · coverage-intact · redacted-by-default). **Amended 2026-08-04 (BACKLOG #341)** — gate 1 stated a single byte-identical equality; the repo reads it at two levels (message-level and per-invocation), and widening `_partition` to fan out any non-`str` iterable made a **generator Handler** deliver where it previously delivered nothing, which the per-invocation mirror cannot observe. Gate 1 in §6 is split by level and given an explicit generator carve-out, and §3 gains the `lazy_result` field that declares it. The message-level guarantee — the one the ADR exists to make — is **unchanged and still absolute**. +**Status:** Accepted (2026-07-06). Ratified by the owner — the engine lane (MULTISESSION-PLAN-7 **L5**) may build. The traced mode is **additive + opt-in**; nothing here changes the shipped `dryrun` default. The §6 test gates are the acceptance criteria (byte-identical run · live-lookup identical · coverage-intact · redacted-by-default). **Amended 2026-11-24 (BACKLOG #6823)** — on the Handler half, `lazy_result` now marks any iterable return whose exact type is not `list`/`tuple`/`set`/`frozenset` (except `str`/`bytes`/`bytearray`), which reports no per-invocation sends; see the amendment at the end, which supersedes §3 and gate 1b there. **Amended 2026-08-04 (BACKLOG #341)** — gate 1 stated a single byte-identical equality; the repo reads it at two levels (message-level and per-invocation), and widening `_partition` to fan out any non-`str` iterable made a **generator Handler** deliver where it previously delivered nothing, which the per-invocation mirror cannot observe. Gate 1 in §6 is split by level and given an explicit generator carve-out, and §3 gains the `lazy_result` field that declares it. The message-level guarantee — the one the ADR exists to make — is **unchanged and still absolute**. **Deciders:** owner + IDE/DX working group **Related:** BACKLOG **#92** (interactive live-debug loop — the primary consumer, v2), BACKLOG **#84** (Test Bench profiling/coverage — the second consumer), BACKLOG **#48** (Insert Element palette — sibling DX lane), ADR 0004 (payload-agnostic ingress — `RawMessage` vs `Message` in a handler), ADR 0010/0043 (`db_lookup`/`fhir_lookup` — the sanctioned non-pure reads that raise in dry-run), CLAUDE.md §9 (PHI handling — `dryrun` output can contain full bodies). Plan: `docs/releases/MULTISESSION-PLAN-7.md` (L5 builds this; L6/L7 consume it). **Code references** are `origin/main @ 0f0ba08`; line numbers are approximate — locate exactly at implementation time. @@ -100,8 +100,8 @@ The sanctioned non-pure reads (ADR 0010/0043) are **unavailable in dry-run and r ## Amendment 2026-11-24 (BACKLOG #6823) — `lazy_result` on the Handler half -The §3 `lazy_result` text and the gate 1b carve-out above are kept as accepted; this note records -what shipped since. Gate 1b names "the `_sends_from` iterator guard". That guard tested +The §3 `lazy_result` text and the gate 1b carve-out above are kept as accepted text, and this +amendment supersedes them for the Handler half where they differ. Gate 1b names "the `_sends_from` iterator guard". That guard tested `isinstance(result, Iterator)`, and it was not enough: an object whose `__iter__` returns a stored generator is single-pass but not an `Iterator`, so the tracer walked it, `_partition` then found it empty, and a traced run read `FILTERED` with zero deliveries where the untraced run delivered — diff --git a/docs/adr/README.md b/docs/adr/README.md index 095683fed3..66cc987976 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -106,7 +106,7 @@ what is withheld and what you can request. | [0069](0069-durable-write-throughput-lever.md) | Durable-write is not the throughput wall — engine feed concurrency is — the store absorbs ~27k commits/s (measured commit-storm) while the pipeline feeds only ~750/s (~36× gap); rejects every durable-write-tier lever (app-side group-commit, faster log storage, bigger pool — each ~0) and reaffirms ADR 0055's `DELAYED_DURABILITY`/`commit_delay` rulings; directs effort to engine-side feed concurrency (pooled claiming + higher stage concurrency + engine per-message CPU); commit-depth reduction is secondary and largely invariant-blocked | **Accepted** -- ratified 2026-07-12 by [ADR 0099](0099-phase-4-group-commit-amortize-the-per-event-transaction-cost.md) | | [0070](0070-t17-infra-fault-bound.md) | Bounding a persistent pooled T17 infra fault. The `StageDispatcher`'s machinery-fault branch released the head and returned a fixed-backoff RETRY, while `release_claimed` *undid* the claim's poison-guard increment (`attempts = MAX(attempts-1, 0)`) and left `next_attempt_at` past-due — so a persistent infra fault re-claimed at the ~0.25 s sweep cadence forever (an escalation-less ~4×/s spin; the G6 ceiling never fires; the head silently head-of-line-blocks its lane). **Fix A:** re-pend the head with exponential-capped backoff, releasing `items[i:]` (never `items[1:]`, which strands the head INFLIGHT and breaks FIFO). **Fix B:** `[pipeline].infra_fault_policy`, default `stop` — count consecutive zero-progress infra faults and STOP the lane with an alert (`retry_forever` opt-in). A T17 head is **never** auto-dead-lettered: the message is not at fault, and the signal cannot distinguish a long outage from a deterministic bug — a human makes that call | Accepted (2026-07-04; implemented) | | [0071](0071-cut-executor-round-trips-b5.md) | Cutting per-message executor round-trips: the async-marshaling feed wall (build-plan B5) — the concrete lever ADR 0069 deferred. The 2026-07-04 py-spy profile names the ~107 msg/s pooled ceiling as **per-completion executor→loop marshaling + the Windows Proactor self-pipe wakeup**, and (adversarially adjudicated + micro-benched 2026-07-04) it is a **blocking-driver (SQL Server / aioodbc per-statement) wall** — Postgres (asyncpg loop-native, ~2 crossings/msg) and SQLite (loop-affine handoff lock) keep the async path **by construction**. Decision: on SQL Server, **thread-hop fusion** — run each off-loop CPU stage + its handoff on one dedicated-executor hop via a dedicated *synchronous* pyodbc source, so a multi-statement handoff marshals back once (micro-bench: 12→2 crossings/msg, commits/msg identical ⇒ no transaction fusion, so 0069's fence is not hit). Cheaper/coalesced wakeup secondary (deferred); free-threading (ADR 0053) tertiary. **Throughput GO/NO-GO is the SQL-Server leg** (SQLite proved mechanism-only, throughput sign-unstable); null ⇒ escalate to ADR 0053 | Accepted (built + merged, default-OFF `fuse_thread_hops`; promote gate NO-GO) | -| [0072](0072-traced-dryrun-mode.md) | Traced dry-run mode — `dryrun --trace json`: a `sys.settrace` pass around the Router/Handler call emits a line-addressable `(line, event, value)` sequence + disposition + Sends, the data source for the **#92** interactive live-debug loop (v2 inline values) and **#84** profiling/coverage. Additive + **preview-only** (a traced run is byte-identical to a non-traced one — no dispatch/logic change); values are **PHI-redacted by default** + streamed-never-persisted (reuse the `--show-phi` gate); `db_lookup`/`fhir_lookup` stay `ERROR` (annotated `live_lookup_skipped`, handler does **not** resume); prior tracer restored in `finally` (coverage.py-safe), frame-scoped, thread-local. Stdlib-only, no runtime dep | Accepted (2026-07-06) — building (L5); **amended 2026-08-04** (BACKLOG #341 — the byte-identical gate is now stated by level: message-level absolute, per-invocation best-effort with a declared `lazy_result` carve-out for a generator Router/Handler) | +| [0072](0072-traced-dryrun-mode.md) | Traced dry-run mode — `dryrun --trace json`: a `sys.settrace` pass around the Router/Handler call emits a line-addressable `(line, event, value)` sequence + disposition + Sends, the data source for the **#92** interactive live-debug loop (v2 inline values) and **#84** profiling/coverage. Additive + **preview-only** (a traced run is byte-identical to a non-traced one — no dispatch/logic change); values are **PHI-redacted by default** + streamed-never-persisted (reuse the `--show-phi` gate); `db_lookup`/`fhir_lookup` stay `ERROR` (annotated `live_lookup_skipped`, handler does **not** resume); prior tracer restored in `finally` (coverage.py-safe), frame-scoped, thread-local. Stdlib-only, no runtime dep | Accepted (2026-07-06) — building (L5); **amended 2026-08-04** (BACKLOG #341 — the byte-identical gate is now stated by level: message-level absolute, per-invocation best-effort with a declared `lazy_result` carve-out for a generator Router/Handler); **amended 2026-11-24** (BACKLOG #6823 — a Handler's `lazy_result` now also covers any iterable return that is not an exact `list`/`tuple`/`set`/`frozenset`, so a single-pass iterable is never drained) | | [0073](0073-ownership-scoped-recovery-single-consumer-lanes.md) | Ownership-scoped recovery + single delivery consumer per outbound lane — the N-active-shards-on-one-unified-store reliability runtime (builds ADR 0063's deferred primitive): `reset_stale_inflight(owned=OwnedLanes)` scopes startup/DR crash recovery to a shard's config-graph lanes (channel_id for ingress/routed/response, destination_name for outbound; empty set matches nothing; residual-`IN`/`ANY` predicate keeps the WS-B ready-index seek); deterministic rendezvous (sha256 HRW) outbound-lane ownership over the pinned shard universe, gated at the wake boundary + pooled lane provider + per-lane spawn (predicate, not set — a reload-dropped lane keeps exactly its owner); `--shard`+`[cluster]` refused fail-closed; shard-set-changing reloads refused (fleet restart required); owner-only outbound controls/purge (409 names the owner; `/connections` rows carry `owner_shard`); sharded-only non-owned-lane buildup/stall watchdog (hung-owner paging). N-active stays gated on the clean 4-engine no-loss bench before SYSTEM-REQUIREMENTS calls it supported | Accepted (2026-07-06) — built | | [0074](0074-adopter-capacity-estimator.md) | Adopter-run capacity estimator (BACKLOG #96) — productize the **built** `harness/load/` rate-walk + zero-loss reconcile as a supported `messagefoundry capacity` command an adopter points at *their* box/store/config to answer "does this carry my ~36 msg/s hospital with headroom?"; reports the **per-interface** no-loss ceiling + engine-wide aggregate + a **backend-aware limiting-factor** label + provision-at-≤50%-of-ceiling guidance. Hard requirements: **isolated throwaway store** (refuse to run against a non-isolated/production store — count-and-log intact), **synthetic PHI-free** payloads only (ADR 0030), backend-aware labels (SQLite knob rankings do **not** transfer to server backends — the B12 lesson), explicit harness-ceiling caveats (~450/s ACK per driver, ~135–144/s delivered per sink, poller-zero ⇒ sub-ceiling knee). v1 = rate-walk + limiting-factor labels; deeper per-stage diagnostics deferred. A productization of throughput-campaign evidence (PR #768), not a new measurement effort | Accepted (2026-07-07) — ratified. ⛔ **BUILD GATED (2026-07-14)**: a validity re-check vs STEP-4 Arm 0 found **14 confirmed blockers** in the *measurement* method (the named "only success gate" over-reports by **3–5.5×**; the poller-zero failure mode *satisfies* it; the estimand is intake not delivery; the aggregate-is-the-sum rule is measured-false; the ceiling is instant-partner). **Premise + hard requirements + the fail-closed guard layer still hold and remain buildable.** See the ADR's 2026-07-14 Amendment . ✅ **RE-RATIFIED 2026-09-14 (owner)** — the three corrections are adopted (sustain = no-loss AND non-filling; the estimand is DELIVERY; the aggregate is `min(measured concurrent, Σ per-interface)`), so the gate's owner-re-ratification condition is **SATISFIED for the measurement layer's RULES**. The measurement **build** stays **demand-gated** (BACKLOG #96); the guard layer may start. See the ADR's 2026-09-14 Re-ratification | | [0075](0075-per-hop-sql-statement-batching.md) | Per-hop SQL statement batching (`[pipeline].batch_handoff_statements`, default-ON (emergency off-switch), fail-closed, SQL-Server-only) — the last [ADR 0069](0069-durable-write-throughput-lever.md)-named feed lever ("batching SQL statements per executor hop"): fold a multi-statement handoff **body** (guard-DELETE + inserts + finalize applock + `messages.status` UPDATE + event, from the SAME shared `(sql,params)` builders that keep the async/sync twins in lockstep) into 1–2 `pyodbc.execute()` batches, cutting **network round-trips + aioodbc executor crossings — NOT transactions** (`commits/msg` stays 2.000; the ADR 0069 cross-lane/commit fence is not hit). Attacks the serial-RT co-bottleneck the [ADR 0071](0071-cut-executor-round-trips-b5.md) B5 fusion NO-GO could not (the ~11 ms inter-box store RTT × ~4–5 RT/msg) and works on the **default async path**. Microbench (adversarially re-reviewed, counts VERIFIED honest): per-hop drop 27–50%, but the **≥40% figure is CONDITIONAL on the applock-rc-fold** — under the strict interpretation 27–33% clears nothing, so the microbench JUSTIFIES a live-rig e2e A/B, it does not substitute for it. Content-vs-infra error attribution + a golden-SQL/living RT-count CI gate are load-bearing. **Promoted default-ON 2026-07-08** (Bench B distance-insurance A/B: harmless-near + helps-far, green SS correctness precondition) — flag retained only as an emergency off-switch | Accepted (2026-07-07) — promoted default-ON 2026-07-08 | diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index dfd6a46aee..0622cf6e5a 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -49,7 +49,10 @@ The invocation therefore carries ``"lazy_result": true``: message-level ``sends``/``handlers`` stay byte-identical to the untraced run, and the consumer can say *"this body was not traced"* instead of rendering an apparently inert handler beside ``trace_ok: true`` (ADR 0072 §6 gate 1; the honest- - degradation rule of ADR 0089 §4). + degradation rule of ADR 0089 §4). **Handler half, wider (ADR 0072 amendment 2026-11-24, BACKLOG + #6823):** a Handler's ``lazy_result`` marks any iterable return whose exact type is not + ``list``/``tuple``/``set``/``frozenset`` (``str``/``bytes``/``bytearray`` aside). It means only that + the per-invocation ``sends`` were not read; such a body may still carry line events. * *Python 3.14.* The tracer only touches ``sys.settrace`` — it never installs a ``sys.monitoring`` tool — so it coexists with coverage tooling on either mechanism. @@ -286,8 +289,9 @@ def __init__( self.sends: list[str] = [] self.routed_to: list[str] = [] self.truncated = False - # The invocation returned a one-shot iterator (a generator Router/Handler): its body has not - # run yet, so this record has no line events and its sends/routed_to are not measurable here. + # The return was not walked, so this record's sends/routed_to are not measurable here. For a + # generator the body has not run yet either, so there are no line events; a Handler's other + # unwalked iterables (BACKLOG #6823) may still have them. See `record_return`. self.lazy_result = False # trace state self.frame: FrameType | None = None From 366582a2083959dc0c4e624248fb1c3a30f2ee7b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:14:15 -0600 Subject: [PATCH 08/14] dryrun_trace: drop Message writes past the event and write caps After an invocation reached _MAX_EVENTS, _finalize stopped popping _writes_by_line while record_write kept appending every Message write, so a long mutating loop grew the recorder without bound. record_write now drops a write once the event cap is reached, and past a new per-invocation _MAX_WRITES cap that also bounds a helper's writes landing on one traced line. Either marks the invocation truncated; _finalize clears writes that can no longer be emitted. BACKLOG #6824 --- changelog.d/6824.fixed.md | 6 +++ messagefoundry/pipeline/dryrun_trace.py | 13 +++++ tests/test_dryrun_trace.py | 67 +++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 changelog.d/6824.fixed.md diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md new file mode 100644 index 0000000000..4e38271bf0 --- /dev/null +++ b/changelog.d/6824.fixed.md @@ -0,0 +1,6 @@ +- **A traced dry-run no longer keeps Message writes it will never emit.** Once an invocation hit + the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding every later + `msg[...]` write in memory, so a long mutating loop grew without bound. Writes are now dropped + past that cap, and also past a separate per-invocation cap of 5,000 writes, which bounds the + writes a Handler's helper makes on a single traced line. Either cap marks the invocation + `truncated`. (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 0622cf6e5a..4459917d87 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -94,6 +94,10 @@ # marked ``truncated``). A long string local / write value is likewise capped so a body can't be dumped # in full even under --show-phi. _MAX_EVENTS = 5000 +# Message writes are capped per invocation on their own, because a helper the Handler calls is not +# line-traced: all its writes land on one Handler line, so the event cap alone never bounds them. +# Past either cap a write is dropped and the record marked ``truncated`` (BACKLOG #6824). +_MAX_WRITES = 5000 _MAX_VALUE_LEN = 120 @@ -300,6 +304,7 @@ def __init__( self._last_ts: float | None = None self._snap_before: dict[str, Any] = {} self._writes_by_line: dict[int, list[dict[str, Any]]] = {} + self._write_count = 0 # writes kept, pending or emitted, against _MAX_WRITES # tracer callbacks --------------------------------------------------------- @@ -335,6 +340,8 @@ def on_return(self, frame: FrameType) -> None: def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: if len(self.events) >= _MAX_EVENTS: self.truncated = True + # No later line is emitted, so writes still pending here never will be either. + self._writes_by_line.clear() return now = _safe_snapshot(frame) assigned = _diff(now, self._snap_before, self.show_phi) @@ -349,6 +356,12 @@ def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: # message-write capture (called from the patched Message.set) -------------- def record_write(self, path: str, value: object) -> None: + # Past the event cap no line is finalized, so a write kept now would never be emitted, only + # held: a long mutating loop would grow this recorder without bound (BACKLOG #6824). + if len(self.events) >= _MAX_EVENTS or self._write_count >= _MAX_WRITES: + self.truncated = True + return + self._write_count += 1 line = self.frame.f_lineno if self.frame is not None else (self.def_line or 0) self._writes_by_line.setdefault(line, []).append( {"path": path, "value": _safe_value(value, self.show_phi)} diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 2053dd93a1..08510d5ccc 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -836,3 +836,70 @@ def test_trace_accepts_declined_is_empty_without_predicates() -> None: traced = trace_dry_run(_registry(route_to_h, {"h": handle_transform}), ADT_A01) assert traced["accepts_declined"] == [] assert not [inv for inv in traced["invocations"] if inv["kind"] == "accepts"] + + +# --- bounded capture + the shared Message patch (BACKLOG #6824, #6825) -------------------------- + + +def _capture_tracers(monkeypatch: pytest.MonkeyPatch) -> list: + """Keep each `_Tracer` that `trace_dry_run` builds, so a test can read its recorders.""" + from messagefoundry.pipeline import dryrun_trace as dt + + made: list = [] + + class _Kept(dt._Tracer): + def __init__(self, show_phi: bool) -> None: + super().__init__(show_phi) + made.append(self) + + monkeypatch.setattr(dt, "_Tracer", _Kept) + return made + + +def _retained_writes(rec) -> int: + pending = sum(len(v) for v in rec._writes_by_line.values()) + return pending + sum(len(ev.get("writes", [])) for ev in rec.events) + + +def test_writes_after_the_event_cap_are_not_retained(monkeypatch: pytest.MonkeyPatch) -> None: + # Past _MAX_EVENTS no line is finalized, so a write recorded then is never emitted. It must not + # be kept either, or a long mutating loop grows the recorder without bound (BACKLOG #6824). + from messagefoundry.pipeline.dryrun_trace import _MAX_EVENTS + + def handle_loops(msg: Message) -> Send: + for _ in range(_MAX_EVENTS * 2): + msg["MSH-3"] = "X" + return Send("out", msg) + + made = _capture_tracers(monkeypatch) + traced = trace_dry_run(_registry(route_to_h, {"h": handle_loops}), ADT_A01) + assert traced["sends"] == [{"outbound": "out"}] + inv = _handler_invocation(traced) + assert inv.get("truncated") is True + rec = next(r for r in made[0].invocations if r.kind == "handler") + assert rec._writes_by_line == {} + assert _retained_writes(rec) <= _MAX_EVENTS + assert _all_writes(inv), "writes before the cap are still emitted" + + +def test_writes_from_a_helper_loop_are_bounded(monkeypatch: pytest.MonkeyPatch) -> None: + # A helper the Handler calls is not line-traced, so all its writes land on one Handler line. + # The per-invocation cap must bound those too, and say the record is truncated (BACKLOG #6824). + from messagefoundry.pipeline.dryrun_trace import _MAX_WRITES + + def fill(msg: Message) -> None: + for _ in range(_MAX_WRITES * 2): + msg["MSH-3"] = "X" + + def handle_calls_fill(msg: Message) -> Send: + fill(msg) + return Send("out", msg) + + made = _capture_tracers(monkeypatch) + traced = trace_dry_run(_registry(route_to_h, {"h": handle_calls_fill}), ADT_A01) + assert traced["sends"] == [{"outbound": "out"}] + inv = _handler_invocation(traced) + assert inv.get("truncated") is True + rec = next(r for r in made[0].invocations if r.kind == "handler") + assert _retained_writes(rec) <= _MAX_WRITES + assert len(_all_writes(inv)) == _MAX_WRITES From 9b748b929c0466cb5b0b18edbcb701858034f4cf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:19:14 -0600 Subject: [PATCH 09/14] dryrun_trace: count holders of the shared Message._write patch _patched_message_writes overwrote and restored the class-global Message._write with no count or lock, so when two threads traced at once the first to finish restored the original under the other, which then recorded no writes. A lock-guarded holder count now installs the patch on the first entry and restores it on the last exit. BACKLOG #6825 --- changelog.d/6825.fixed.md | 5 ++++ messagefoundry/pipeline/dryrun_trace.py | 24 ++++++++++++++--- tests/test_dryrun_trace.py | 36 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 changelog.d/6825.fixed.md diff --git a/changelog.d/6825.fixed.md b/changelog.d/6825.fixed.md new file mode 100644 index 0000000000..a18046f845 --- /dev/null +++ b/changelog.d/6825.fixed.md @@ -0,0 +1,5 @@ +- **Concurrent traced dry-runs no longer lose each other's Message writes.** Two threads running + `trace_dry_run` at once shared one class-level patch of `Message._write`, and the first to + finish restored the original under the other, whose `msg[...]` writes then went unrecorded with + no sign in its trace. The patch is now counted under a lock: installed on the first entry, + restored on the last exit. (`BACKLOG #6825`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 4459917d87..494a637c4b 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -67,6 +67,7 @@ import inspect import math import sys +import threading from collections.abc import Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -544,16 +545,31 @@ def _recording_write( _ORIG_MESSAGE_WRITE(self, path, value, occurrence, repetition, as_data=as_data) +# ``Message._write`` is class-global, so concurrent traces (one per thread) share one patch. A +# count under a lock installs it on the first entry and restores it on the last exit; without it +# the first trace to finish restored the original under the others, which then silently recorded +# no writes (BACKLOG #6825). +_patch_lock = threading.Lock() +_patch_holders = 0 + + @contextmanager def _patched_message_writes() -> Iterator[None]: """Record ``msg.set(...)`` / ``msg[...] = ...`` / ``msg.set_data(...)`` writes for the active - recorder, then restore the original method. A no-op passthrough whenever no recorder is active, so - it never perturbs the mutation itself.""" - Message._write = _recording_write # type: ignore[method-assign] + recorder, then restore the original method once no trace still needs it. A no-op passthrough + whenever no recorder is active, so it never perturbs the mutation itself.""" + global _patch_holders + with _patch_lock: + if _patch_holders == 0: + Message._write = _recording_write # type: ignore[method-assign] + _patch_holders += 1 try: yield finally: - Message._write = _ORIG_MESSAGE_WRITE # type: ignore[method-assign] + with _patch_lock: + _patch_holders -= 1 + if _patch_holders == 0: + Message._write = _ORIG_MESSAGE_WRITE # type: ignore[method-assign] def trace_dry_run( diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 08510d5ccc..142ee43a6d 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -903,3 +903,39 @@ def handle_calls_fill(msg: Message) -> Send: rec = next(r for r in made[0].invocations if r.kind == "handler") assert _retained_writes(rec) <= _MAX_WRITES assert len(_all_writes(inv)) == _MAX_WRITES + + +def test_message_write_patch_survives_a_concurrent_trace_exiting() -> None: + # Two threads tracing at once share the class-level Message._write. The one that finishes first + # must not restore the original under the other, which would silently stop recording its writes + # (BACKLOG #6825). + import threading + + from messagefoundry.pipeline import dryrun_trace as dt + + original = Message._write + a_entered = threading.Event() + b_exited = threading.Event() + seen: dict[str, object] = {} + + def run_a() -> None: + with dt._patched_message_writes(): + a_entered.set() + b_exited.wait(10) + seen["a_during"] = Message._write + + def run_b() -> None: + a_entered.wait(10) + with dt._patched_message_writes(): + pass + b_exited.set() + + ta = threading.Thread(target=run_a) + tb = threading.Thread(target=run_b) + ta.start() + tb.start() + ta.join(20) + tb.join(20) + assert b_exited.is_set() + assert seen["a_during"] is dt._recording_write + assert Message._write is original From d4b0fce1f76e7e9497f8ed3349637107cc39517f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:52:17 -0600 Subject: [PATCH 10/14] dryrun_trace: review round 1 repairs to the write caps and patch count - The write cap marks writes_truncated, not truncated, which the IDE reads as short line coverage. - A write is recorded only after Message._write accepts it, so refused writes spend no budget. - No write is kept without a latched frame; the dead clear() is gone. - The patch holder count is taken inside the try, released only if held. - Tests: refused write, end-to-end concurrent traces, holder count. BACKLOG #6824, #6825 Proposed vault banners: #6824: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: past _MAX_EVENTS, record_write kept every write in _writes_by_line. Writes are dropped past the event cap (truncated) and a new 5,000-write cap (writes_truncated). #6825: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: a second trace exiting restored Message._write under the first. A lock-guarded holder count now restores on the last exit. --- changelog.d/6824.fixed.md | 9 +-- messagefoundry/pipeline/dryrun_trace.py | 48 ++++++++++------ tests/test_dryrun_trace.py | 74 +++++++++++++++++++++++-- 3 files changed, 107 insertions(+), 24 deletions(-) diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md index 4e38271bf0..427ae05b4b 100644 --- a/changelog.d/6824.fixed.md +++ b/changelog.d/6824.fixed.md @@ -1,6 +1,7 @@ - **A traced dry-run no longer keeps Message writes it will never emit.** Once an invocation hit the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding every later - `msg[...]` write in memory, so a long mutating loop grew without bound. Writes are now dropped - past that cap, and also past a separate per-invocation cap of 5,000 writes, which bounds the - writes a Handler's helper makes on a single traced line. Either cap marks the invocation - `truncated`. (`BACKLOG #6824`) + `msg[...]` write in memory, so a long mutating loop grew without bound. A write past that cap is + now dropped, under the invocation's existing `truncated` flag. A separate per-invocation cap of + 5,000 writes bounds the writes a Handler's helper makes on a single traced line; a write past it + is dropped and the invocation carries a new `writes_truncated` flag. A write that + `Message` refuses is no longer recorded. (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 494a637c4b..eab8e0b6d6 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -97,7 +97,9 @@ _MAX_EVENTS = 5000 # Message writes are capped per invocation on their own, because a helper the Handler calls is not # line-traced: all its writes land on one Handler line, so the event cap alone never bounds them. -# Past either cap a write is dropped and the record marked ``truncated`` (BACKLOG #6824). +# A write past the event cap is dropped under ``truncated``, since its line is never emitted; one past +# this cap is dropped and the record marked ``writes_truncated`` instead, because its lines may all be +# present and ``truncated`` tells a consumer line coverage is short (BACKLOG #6824). _MAX_WRITES = 5000 _MAX_VALUE_LEN = 120 @@ -294,6 +296,7 @@ def __init__( self.sends: list[str] = [] self.routed_to: list[str] = [] self.truncated = False + self.writes_truncated = False # The return was not walked, so this record's sends/routed_to are not measurable here. For a # generator the body has not run yet either, so there are no line events; a Handler's other # unwalked iterables (BACKLOG #6823) may still have them. See `record_return`. @@ -341,8 +344,6 @@ def on_return(self, frame: FrameType) -> None: def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: if len(self.events) >= _MAX_EVENTS: self.truncated = True - # No later line is emitted, so writes still pending here never will be either. - self._writes_by_line.clear() return now = _safe_snapshot(frame) assigned = _diff(now, self._snap_before, self.show_phi) @@ -357,13 +358,19 @@ def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: # message-write capture (called from the patched Message.set) -------------- def record_write(self, path: str, value: object) -> None: - # Past the event cap no line is finalized, so a write kept now would never be emitted, only - # held: a long mutating loop would grow this recorder without bound (BACKLOG #6824). - if len(self.events) >= _MAX_EVENTS or self._write_count >= _MAX_WRITES: + # A write is kept only where a later `_finalize` will emit it. Past the event cap no line is + # finalized, and with no latched frame none ever is, so a write kept then would only be held: + # a long mutating loop would grow this recorder without bound (BACKLOG #6824). + if self.frame is None: + return + if len(self.events) >= _MAX_EVENTS: self.truncated = True return + if self._write_count >= _MAX_WRITES: + self.writes_truncated = True + return self._write_count += 1 - line = self.frame.f_lineno if self.frame is not None else (self.def_line or 0) + line = self.frame.f_lineno self._writes_by_line.setdefault(line, []).append( {"path": path, "value": _safe_value(value, self.show_phi)} ) @@ -432,6 +439,8 @@ def to_dict(self, disposition: str) -> dict[str, Any]: } if self.truncated: out["truncated"] = True + if self.writes_truncated: + out["writes_truncated"] = True if self.lazy_result: out["lazy_result"] = True return out @@ -539,10 +548,12 @@ def _recording_write( *, as_data: bool, ) -> None: + _ORIG_MESSAGE_WRITE(self, path, value, occurrence, repetition, as_data=as_data) + # Recorded only once the write took, so a refused write neither shows in the trace nor spends + # the per-invocation write budget (BACKLOG #6824). rec = _active_recorder.get() if rec is not None: rec.record_write(path, value) - _ORIG_MESSAGE_WRITE(self, path, value, occurrence, repetition, as_data=as_data) # ``Message._write`` is class-global, so concurrent traces (one per thread) share one patch. A @@ -559,17 +570,22 @@ def _patched_message_writes() -> Iterator[None]: recorder, then restore the original method once no trace still needs it. A no-op passthrough whenever no recorder is active, so it never perturbs the mutation itself.""" global _patch_holders - with _patch_lock: - if _patch_holders == 0: - Message._write = _recording_write # type: ignore[method-assign] - _patch_holders += 1 + held = False try: - yield - finally: + # Inside the try, so an interrupt after the count rose still releases it; a leaked count + # would leave the patch installed for the life of the process. with _patch_lock: - _patch_holders -= 1 if _patch_holders == 0: - Message._write = _ORIG_MESSAGE_WRITE # type: ignore[method-assign] + Message._write = _recording_write # type: ignore[method-assign] + _patch_holders += 1 + held = True + yield + finally: + if held: + with _patch_lock: + _patch_holders -= 1 + if _patch_holders == 0: + Message._write = _ORIG_MESSAGE_WRITE # type: ignore[method-assign] def trace_dry_run( diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 142ee43a6d..568202a2aa 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -16,6 +16,7 @@ from __future__ import annotations +import contextlib import json import sys from collections.abc import Iterator @@ -884,7 +885,9 @@ def handle_loops(msg: Message) -> Send: def test_writes_from_a_helper_loop_are_bounded(monkeypatch: pytest.MonkeyPatch) -> None: # A helper the Handler calls is not line-traced, so all its writes land on one Handler line. - # The per-invocation cap must bound those too, and say the record is truncated (BACKLOG #6824). + # The per-invocation write cap must bound those too, and say so as `writes_truncated`: every + # line is still present, so `truncated` (which a consumer reads as short line coverage) stays + # off (BACKLOG #6824). from messagefoundry.pipeline.dryrun_trace import _MAX_WRITES def fill(msg: Message) -> None: @@ -899,12 +902,35 @@ def handle_calls_fill(msg: Message) -> Send: traced = trace_dry_run(_registry(route_to_h, {"h": handle_calls_fill}), ADT_A01) assert traced["sends"] == [{"outbound": "out"}] inv = _handler_invocation(traced) - assert inv.get("truncated") is True + assert inv.get("writes_truncated") is True + assert "truncated" not in inv rec = next(r for r in made[0].invocations if r.kind == "handler") assert _retained_writes(rec) <= _MAX_WRITES assert len(_all_writes(inv)) == _MAX_WRITES +def test_a_refused_write_is_not_recorded_and_spends_no_write_budget() -> None: + # Only a write that took is recorded, so refused writes cannot push a real one past the cap. + from messagefoundry.pipeline.dryrun_trace import _MAX_WRITES + + def try_absent(msg: Message) -> None: + for _ in range(_MAX_WRITES): + with contextlib.suppress(KeyError, ValueError): + msg["ZZZ-1"] = "X" + + def handle_refused_then_real(msg: Message) -> Send: + try_absent(msg) + msg["MSH-3"] = "REAL" + return Send("out", msg) + + traced = trace_dry_run( + _registry(route_to_h, {"h": handle_refused_then_real}), ADT_A01, show_phi=True + ) + inv = _handler_invocation(traced) + assert [w["path"] for w in _all_writes(inv)] == ["MSH-3"] + assert "writes_truncated" not in inv + + def test_message_write_patch_survives_a_concurrent_trace_exiting() -> None: # Two threads tracing at once share the class-level Message._write. The one that finishes first # must not restore the original under the other, which would silently stop recording its writes @@ -913,7 +939,7 @@ def test_message_write_patch_survives_a_concurrent_trace_exiting() -> None: from messagefoundry.pipeline import dryrun_trace as dt - original = Message._write + assert dt._patch_holders == 0 a_entered = threading.Event() b_exited = threading.Event() seen: dict[str, object] = {} @@ -938,4 +964,44 @@ def run_b() -> None: tb.join(20) assert b_exited.is_set() assert seen["a_during"] is dt._recording_write - assert Message._write is original + assert Message._write is dt._ORIG_MESSAGE_WRITE + assert dt._patch_holders == 0 + + +def test_concurrent_traced_dry_runs_each_record_their_writes() -> None: + # End to end: a trace that finishes while another is mid-Handler must not cost the other its + # later writes (BACKLOG #6825). + import threading + + from messagefoundry.pipeline import dryrun_trace as dt + + a_paused = threading.Event() + b_done = threading.Event() + results: dict[str, dict] = {} + + def handle_pauses(msg: Message) -> Send: + a_paused.set() + b_done.wait(10) + msg["MSH-3"] = "AFTER" + return Send("out", msg) + + def run_a() -> None: + reg = _registry(route_to_h, {"h": handle_pauses}) + results["a"] = trace_dry_run(reg, ADT_A01, show_phi=True) + + def run_b() -> None: + a_paused.wait(10) + results["b"] = trace_dry_run(_registry(route_to_h, {"h": handle_transform}), ADT_A01) + b_done.set() + + ta = threading.Thread(target=run_a) + tb = threading.Thread(target=run_b) + ta.start() + tb.start() + ta.join(20) + tb.join(20) + assert b_done.is_set() + assert any(w["path"] == "MSH-3" for w in _all_writes(_handler_invocation(results["b"]))) + a_writes = _all_writes(_handler_invocation(results["a"])) + assert any(w["path"] == "MSH-3" and w["value"] == "AFTER" for w in a_writes) + assert Message._write is dt._ORIG_MESSAGE_WRITE From c89afd6cd30af6f9eab95e5b0529e5e3a5d74011 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:21:36 -0600 Subject: [PATCH 11/14] dryrun_trace: review round 2 repairs - Record a write before Message._write again, so a write that raises still shows on the failing line; round 1's reorder had hidden it. - Keep no write once the traced frame has returned (no open line). - Document the event and write caps in the module docstring; fix the changelog's write-cap wording. - Thread tests re-raise worker errors and fail on a hung worker. BACKLOG #6824, #6825 Proposed vault banners: #6824: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: past _MAX_EVENTS, record_write kept every write in _writes_by_line. Writes are dropped past the event cap (truncated), with no open line, and past a new 5,000-write cap (writes_truncated). #6825: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: a second trace exiting restored Message._write under the first. A lock-guarded holder count now restores on the last exit. --- changelog.d/6824.fixed.md | 8 +-- messagefoundry/pipeline/dryrun_trace.py | 15 ++-- tests/test_dryrun_trace.py | 95 ++++++++++++++++--------- 3 files changed, 74 insertions(+), 44 deletions(-) diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md index 427ae05b4b..eb4cae478e 100644 --- a/changelog.d/6824.fixed.md +++ b/changelog.d/6824.fixed.md @@ -1,7 +1,7 @@ - **A traced dry-run no longer keeps Message writes it will never emit.** Once an invocation hit the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding every later `msg[...]` write in memory, so a long mutating loop grew without bound. A write past that cap is - now dropped, under the invocation's existing `truncated` flag. A separate per-invocation cap of - 5,000 writes bounds the writes a Handler's helper makes on a single traced line; a write past it - is dropped and the invocation carries a new `writes_truncated` flag. A write that - `Message` refuses is no longer recorded. (`BACKLOG #6824`) + now dropped, under the invocation's existing `truncated` flag. A separate cap of 5,000 writes + per invocation, counting every write, also bounds the writes a Handler's helper makes on a + single traced line; a write past it is dropped and the invocation carries a new + `writes_truncated` flag. (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index eab8e0b6d6..503f58e003 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -53,6 +53,9 @@ #6823):** a Handler's ``lazy_result`` marks any iterable return whose exact type is not ``list``/``tuple``/``set``/``frozenset`` (``str``/``bytes``/``bytearray`` aside). It means only that the per-invocation ``sends`` were not read; such a body may still carry line events. +* *Bounded capture.* An invocation keeps at most :data:`_MAX_EVENTS` line events and + :data:`_MAX_WRITES` ``msg`` writes. Past the first it carries ``"truncated": true``; past the + second, ``"writes_truncated": true``, and later writes on every line are dropped (BACKLOG #6824). * *Python 3.14.* The tracer only touches ``sys.settrace`` — it never installs a ``sys.monitoring`` tool — so it coexists with coverage tooling on either mechanism. @@ -359,9 +362,10 @@ def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: def record_write(self, path: str, value: object) -> None: # A write is kept only where a later `_finalize` will emit it. Past the event cap no line is - # finalized, and with no latched frame none ever is, so a write kept then would only be held: - # a long mutating loop would grow this recorder without bound (BACKLOG #6824). - if self.frame is None: + # finalized, and with no latched frame or no open line (the frame has returned) none is, so a + # write kept then would only be held: a long mutating loop would grow this recorder without + # bound (BACKLOG #6824). + if self.frame is None or self._last_line is None: return if len(self.events) >= _MAX_EVENTS: self.truncated = True @@ -548,12 +552,11 @@ def _recording_write( *, as_data: bool, ) -> None: - _ORIG_MESSAGE_WRITE(self, path, value, occurrence, repetition, as_data=as_data) - # Recorded only once the write took, so a refused write neither shows in the trace nor spends - # the per-invocation write budget (BACKLOG #6824). + # Recorded before the write, so a write that raises still shows on the line that failed. rec = _active_recorder.get() if rec is not None: rec.record_write(path, value) + _ORIG_MESSAGE_WRITE(self, path, value, occurrence, repetition, as_data=as_data) # ``Message._write`` is class-global, so concurrent traces (one per thread) share one patch. A diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 568202a2aa..90054ab6a3 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -16,7 +16,6 @@ from __future__ import annotations -import contextlib import json import sys from collections.abc import Iterator @@ -909,26 +908,65 @@ def handle_calls_fill(msg: Message) -> Send: assert len(_all_writes(inv)) == _MAX_WRITES -def test_a_refused_write_is_not_recorded_and_spends_no_write_budget() -> None: - # Only a write that took is recorded, so refused writes cannot push a real one past the cap. - from messagefoundry.pipeline.dryrun_trace import _MAX_WRITES +def test_a_write_that_raises_still_shows_on_its_line() -> None: + # The live-debug loop shows the value that broke the Handler; recording happens before the + # write so a refused write is not hidden from the failing line. + def handle_bad_write(msg: Message) -> Send: + msg["PID-5"] = "A|B" + return Send("out", msg) + + traced = trace_dry_run(_registry(route_to_h, {"h": handle_bad_write}), ADT_A01, show_phi=True) + assert traced["disposition"] == MessageStatus.ERROR.value + writes = _all_writes(_handler_invocation(traced)) + assert {"path": "PID-5", "value": "A|B"} in writes + - def try_absent(msg: Message) -> None: - for _ in range(_MAX_WRITES): - with contextlib.suppress(KeyError, ValueError): - msg["ZZZ-1"] = "X" +def test_a_write_after_the_traced_frame_returned_is_not_held( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A wrapper's write after the unwrapped Handler returns has no line left to emit it on, so it + # must not be kept (BACKLOG #6824). + import functools - def handle_refused_then_real(msg: Message) -> Send: - try_absent(msg) - msg["MSH-3"] = "REAL" + def inner(msg: Message) -> Send: return Send("out", msg) - traced = trace_dry_run( - _registry(route_to_h, {"h": handle_refused_then_real}), ADT_A01, show_phi=True - ) - inv = _handler_invocation(traced) - assert [w["path"] for w in _all_writes(inv)] == ["MSH-3"] - assert "writes_truncated" not in inv + @functools.wraps(inner) + def wrapper(msg: Message) -> Send: + out = inner(msg) + msg["MSH-4"] = "LATE" + return out + + made = _capture_tracers(monkeypatch) + trace_dry_run(_registry(route_to_h, {"h": wrapper}), ADT_A01) + rec = next(r for r in made[0].invocations if r.kind == "handler") + assert rec.frame is not None + assert rec._writes_by_line == {} + + +def _run_threads(*targets) -> None: + """Run each target on its own thread; re-raise the first error, and fail on a hung thread.""" + import threading + + errors: list[BaseException] = [] + + def guarded(fn): + def run() -> None: + try: + fn() + except BaseException as exc: # noqa: BLE001 - re-raised on the test thread below + errors.append(exc) + + return run + + threads = [threading.Thread(target=guarded(t), daemon=True) for t in targets] + for t in threads: + t.start() + for t in threads: + t.join(20) + assert not any(t.is_alive() for t in threads), "a worker thread hung" + if errors: + raise errors[0] def test_message_write_patch_survives_a_concurrent_trace_exiting() -> None: @@ -947,22 +985,16 @@ def test_message_write_patch_survives_a_concurrent_trace_exiting() -> None: def run_a() -> None: with dt._patched_message_writes(): a_entered.set() - b_exited.wait(10) + assert b_exited.wait(10) seen["a_during"] = Message._write def run_b() -> None: - a_entered.wait(10) + assert a_entered.wait(10) with dt._patched_message_writes(): pass b_exited.set() - ta = threading.Thread(target=run_a) - tb = threading.Thread(target=run_b) - ta.start() - tb.start() - ta.join(20) - tb.join(20) - assert b_exited.is_set() + _run_threads(run_a, run_b) assert seen["a_during"] is dt._recording_write assert Message._write is dt._ORIG_MESSAGE_WRITE assert dt._patch_holders == 0 @@ -990,18 +1022,13 @@ def run_a() -> None: results["a"] = trace_dry_run(reg, ADT_A01, show_phi=True) def run_b() -> None: - a_paused.wait(10) + assert a_paused.wait(10) results["b"] = trace_dry_run(_registry(route_to_h, {"h": handle_transform}), ADT_A01) b_done.set() - ta = threading.Thread(target=run_a) - tb = threading.Thread(target=run_b) - ta.start() - tb.start() - ta.join(20) - tb.join(20) - assert b_done.is_set() + _run_threads(run_a, run_b) assert any(w["path"] == "MSH-3" for w in _all_writes(_handler_invocation(results["b"]))) a_writes = _all_writes(_handler_invocation(results["a"])) assert any(w["path"] == "MSH-3" and w["value"] == "AFTER" for w in a_writes) assert Message._write is dt._ORIG_MESSAGE_WRITE + assert dt._patch_holders == 0 From 810c7a0fb5d5a513267ac7228b77e39309a65594 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:44:12 -0600 Subject: [PATCH 12/14] dryrun_trace: revert the no-open-line write guard; text matches code The round-2 guard on _last_line dropped writes made after a handled in-frame exception, with no flag. It is reverted with its test. The holder-count comment now says the leak window is narrowed, not closed, and the changelog says the write cap counts kept writes. BACKLOG #6824, #6825 Proposed vault banners: #6824: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: past _MAX_EVENTS, record_write kept every write in _writes_by_line. Writes are dropped past the event cap (truncated) and past a new 5,000-kept-write cap (writes_truncated). #6825: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: a second trace exiting restored Message._write under the first. A lock-guarded holder count now restores on the last exit. --- changelog.d/6824.fixed.md | 8 ++++---- messagefoundry/pipeline/dryrun_trace.py | 14 +++++++------- tests/test_dryrun_trace.py | 23 ----------------------- 3 files changed, 11 insertions(+), 34 deletions(-) diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md index eb4cae478e..287a3c8a92 100644 --- a/changelog.d/6824.fixed.md +++ b/changelog.d/6824.fixed.md @@ -1,7 +1,7 @@ - **A traced dry-run no longer keeps Message writes it will never emit.** Once an invocation hit the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding every later `msg[...]` write in memory, so a long mutating loop grew without bound. A write past that cap is - now dropped, under the invocation's existing `truncated` flag. A separate cap of 5,000 writes - per invocation, counting every write, also bounds the writes a Handler's helper makes on a - single traced line; a write past it is dropped and the invocation carries a new - `writes_truncated` flag. (`BACKLOG #6824`) + now dropped, under the invocation's existing `truncated` flag. A separate cap of 5,000 kept + writes per invocation also bounds the writes a Handler's helper makes on a single traced line; + a write past it is dropped and the invocation carries a new `writes_truncated` flag. + (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 503f58e003..c6520e3966 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -361,11 +361,10 @@ def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: # message-write capture (called from the patched Message.set) -------------- def record_write(self, path: str, value: object) -> None: - # A write is kept only where a later `_finalize` will emit it. Past the event cap no line is - # finalized, and with no latched frame or no open line (the frame has returned) none is, so a - # write kept then would only be held: a long mutating loop would grow this recorder without - # bound (BACKLOG #6824). - if self.frame is None or self._last_line is None: + # Past the event cap no line is finalized, and with no latched frame none ever is, so a write + # kept then would only be held: a long mutating loop would grow this recorder without bound + # (BACKLOG #6824). Other kept writes are bounded by _MAX_WRITES. + if self.frame is None: return if len(self.events) >= _MAX_EVENTS: self.truncated = True @@ -575,8 +574,9 @@ def _patched_message_writes() -> Iterator[None]: global _patch_holders held = False try: - # Inside the try, so an interrupt after the count rose still releases it; a leaked count - # would leave the patch installed for the life of the process. + # Inside the try, which narrows the window in which an interrupt leaks the count; it does + # not close it (between the increment and `held = True`, or in the release). A leaked count + # leaves the patch installed for the life of the process. with _patch_lock: if _patch_holders == 0: Message._write = _recording_write # type: ignore[method-assign] diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 90054ab6a3..32fd68a037 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -921,29 +921,6 @@ def handle_bad_write(msg: Message) -> Send: assert {"path": "PID-5", "value": "A|B"} in writes -def test_a_write_after_the_traced_frame_returned_is_not_held( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # A wrapper's write after the unwrapped Handler returns has no line left to emit it on, so it - # must not be kept (BACKLOG #6824). - import functools - - def inner(msg: Message) -> Send: - return Send("out", msg) - - @functools.wraps(inner) - def wrapper(msg: Message) -> Send: - out = inner(msg) - msg["MSH-4"] = "LATE" - return out - - made = _capture_tracers(monkeypatch) - trace_dry_run(_registry(route_to_h, {"h": wrapper}), ADT_A01) - rec = next(r for r in made[0].invocations if r.kind == "handler") - assert rec.frame is not None - assert rec._writes_by_line == {} - - def _run_threads(*targets) -> None: """Run each target on its own thread; re-raise the first error, and fail on a hung thread.""" import threading From 746098f4e1ce32584e29d00c58c7d926a7a9f439 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:07:42 -0600 Subject: [PATCH 13/14] dryrun_trace: keep pre-latch writes; the write cap also sets truncated A write with no latched frame is keyed to the def line again, as on main, so a wrapper's write before a one-line target is emitted; it now counts against _MAX_WRITES. The write cap also sets truncated, the only key the IDE reads (traceView.ts, testBenchWebview.ts), so a capped trace never looks complete. Comment reason corrected; new wrapper test. BACKLOG #6824 Proposed vault banners: #6824: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: past _MAX_EVENTS, record_write kept every write in _writes_by_line. Writes are dropped past the event cap and past a new 5,000-kept-write cap; either sets truncated, the second also writes_truncated. #6825: FIXED (batch 673, branch b673/trace-group-2). Adjudicated a real defect by failing test: a second trace exiting restored Message._write under the first. A lock-guarded holder count now restores on the last exit. --- changelog.d/6824.fixed.md | 4 ++-- messagefoundry/pipeline/dryrun_trace.py | 22 +++++++++++----------- tests/test_dryrun_trace.py | 23 +++++++++++++++++++---- 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md index 287a3c8a92..bde8e94833 100644 --- a/changelog.d/6824.fixed.md +++ b/changelog.d/6824.fixed.md @@ -3,5 +3,5 @@ `msg[...]` write in memory, so a long mutating loop grew without bound. A write past that cap is now dropped, under the invocation's existing `truncated` flag. A separate cap of 5,000 kept writes per invocation also bounds the writes a Handler's helper makes on a single traced line; - a write past it is dropped and the invocation carries a new `writes_truncated` flag. - (`BACKLOG #6824`) + a write past it is dropped, and the invocation carries `truncated` and a new `writes_truncated` + flag. (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index c6520e3966..279fa6e40b 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -54,8 +54,8 @@ ``list``/``tuple``/``set``/``frozenset`` (``str``/``bytes``/``bytearray`` aside). It means only that the per-invocation ``sends`` were not read; such a body may still carry line events. * *Bounded capture.* An invocation keeps at most :data:`_MAX_EVENTS` line events and - :data:`_MAX_WRITES` ``msg`` writes. Past the first it carries ``"truncated": true``; past the - second, ``"writes_truncated": true``, and later writes on every line are dropped (BACKLOG #6824). + :data:`_MAX_WRITES` ``msg`` writes. Past either it carries ``"truncated": true``; past the second + also ``"writes_truncated": true``, and later writes on every line are dropped (BACKLOG #6824). * *Python 3.14.* The tracer only touches ``sys.settrace`` — it never installs a ``sys.monitoring`` tool — so it coexists with coverage tooling on either mechanism. @@ -100,9 +100,7 @@ _MAX_EVENTS = 5000 # Message writes are capped per invocation on their own, because a helper the Handler calls is not # line-traced: all its writes land on one Handler line, so the event cap alone never bounds them. -# A write past the event cap is dropped under ``truncated``, since its line is never emitted; one past -# this cap is dropped and the record marked ``writes_truncated`` instead, because its lines may all be -# present and ``truncated`` tells a consumer line coverage is short (BACKLOG #6824). +# Semantics: :meth:`_Recorder.record_write` (BACKLOG #6824). _MAX_WRITES = 5000 _MAX_VALUE_LEN = 120 @@ -361,19 +359,21 @@ def _finalize(self, frame: FrameType, line: int, elapsed: float) -> None: # message-write capture (called from the patched Message.set) -------------- def record_write(self, path: str, value: object) -> None: - # Past the event cap no line is finalized, and with no latched frame none ever is, so a write - # kept then would only be held: a long mutating loop would grow this recorder without bound - # (BACKLOG #6824). Other kept writes are bounded by _MAX_WRITES. - if self.frame is None: - return + # Past the event cap no line is finalized, so a write kept then would only be held: a long + # mutating loop would grow this recorder without bound (BACKLOG #6824). A write with no + # latched frame is keyed to the def line, where a later finalize may still emit it (a + # wrapper writing before a one-line target runs), so it is kept, against _MAX_WRITES. if len(self.events) >= _MAX_EVENTS: self.truncated = True return if self._write_count >= _MAX_WRITES: + # Also `truncated`: the IDE reads only that key, and a capped write list must not look + # complete there. self.writes_truncated = True + self.truncated = True return self._write_count += 1 - line = self.frame.f_lineno + line = self.frame.f_lineno if self.frame is not None else (self.def_line or 0) self._writes_by_line.setdefault(line, []).append( {"path": path, "value": _safe_value(value, self.show_phi)} ) diff --git a/tests/test_dryrun_trace.py b/tests/test_dryrun_trace.py index 32fd68a037..b7852b786d 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -884,9 +884,8 @@ def handle_loops(msg: Message) -> Send: def test_writes_from_a_helper_loop_are_bounded(monkeypatch: pytest.MonkeyPatch) -> None: # A helper the Handler calls is not line-traced, so all its writes land on one Handler line. - # The per-invocation write cap must bound those too, and say so as `writes_truncated`: every - # line is still present, so `truncated` (which a consumer reads as short line coverage) stays - # off (BACKLOG #6824). + # The per-invocation write cap must bound those too, and say so as `writes_truncated` and as + # `truncated`, the key the IDE reads, so a capped trace never looks complete (BACKLOG #6824). from messagefoundry.pipeline.dryrun_trace import _MAX_WRITES def fill(msg: Message) -> None: @@ -902,12 +901,28 @@ def handle_calls_fill(msg: Message) -> Send: assert traced["sends"] == [{"outbound": "out"}] inv = _handler_invocation(traced) assert inv.get("writes_truncated") is True - assert "truncated" not in inv + assert inv.get("truncated") is True rec = next(r for r in made[0].invocations if r.kind == "handler") assert _retained_writes(rec) <= _MAX_WRITES assert len(_all_writes(inv)) == _MAX_WRITES +def test_a_wrapper_write_before_a_one_line_target_is_emitted() -> None: + # Before the target frame latches, a write is keyed to the def line; a one-line target's def + # line is its body line, so that line's finalize emits it. The write is kept, not dropped. + import functools + + def inner(msg: Message) -> Send: return Send("out", msg) # fmt: skip # noqa: E704 + + @functools.wraps(inner) + def wrapper(msg: Message) -> Send: + msg["MSH-3"] = "EARLY" + return inner(msg) + + traced = trace_dry_run(_registry(route_to_h, {"h": wrapper}), ADT_A01, show_phi=True) + assert {"path": "MSH-3", "value": "EARLY"} in _all_writes(_handler_invocation(traced)) + + def test_a_write_that_raises_still_shows_on_its_line() -> None: # The live-debug loop shows the value that broke the Handler; recording happens before the # write so a refused write is not hidden from the failing line. From 596566c2ec02d0df475c349866a7ae3ca8ada94d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:24:21 -0600 Subject: [PATCH 14/14] dryrun_trace: comment and changelog say what the IDE and trace do Text only. The write-cap comment says the test bench shows its event-cap message and the inline views read neither flag. The changelog headline is narrowed to writes past the event cap and names, at least, the kept writes that are never emitted. BACKLOG #6824 --- changelog.d/6824.fixed.md | 17 ++++++++++------- messagefoundry/pipeline/dryrun_trace.py | 6 ++++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md index bde8e94833..0c0674418e 100644 --- a/changelog.d/6824.fixed.md +++ b/changelog.d/6824.fixed.md @@ -1,7 +1,10 @@ -- **A traced dry-run no longer keeps Message writes it will never emit.** Once an invocation hit - the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding every later - `msg[...]` write in memory, so a long mutating loop grew without bound. A write past that cap is - now dropped, under the invocation's existing `truncated` flag. A separate cap of 5,000 kept - writes per invocation also bounds the writes a Handler's helper makes on a single traced line; - a write past it is dropped, and the invocation carries `truncated` and a new `writes_truncated` - flag. (`BACKLOG #6824`) +- **A traced dry-run no longer keeps the Message writes made past its event cap.** Once an + invocation hit the 5,000-event cap, `dryrun --trace` stopped emitting lines but went on holding + every later `msg[...]` write in memory, so a long mutating loop grew without bound. A write past + that cap is now dropped, under the invocation's existing `truncated` flag. A separate cap of + 5,000 kept writes per invocation also bounds the writes a Handler's helper makes on a single + traced line; a write past it is dropped, and the invocation carries `truncated` and a new + `writes_truncated` flag. Some kept writes are still never emitted, as before: at least a write a + wrapper makes before a traced function longer than one line starts, a write made when no + function could be traced, and a wrapper's write after the traced function returns. + They now count against the 5,000-write cap. (`BACKLOG #6824`) diff --git a/messagefoundry/pipeline/dryrun_trace.py b/messagefoundry/pipeline/dryrun_trace.py index 279fa6e40b..e51454301d 100644 --- a/messagefoundry/pipeline/dryrun_trace.py +++ b/messagefoundry/pipeline/dryrun_trace.py @@ -367,8 +367,10 @@ def record_write(self, path: str, value: object) -> None: self.truncated = True return if self._write_count >= _MAX_WRITES: - # Also `truncated`: the IDE reads only that key, and a capped write list must not look - # complete there. + # Also `truncated`, so the record never reads as complete. The IDE reads only that key, + # and only in its test bench, which shows its event-cap message (coverage may + # under-report) even when only writes were capped. Its inline write views read neither + # flag. self.writes_truncated = True self.truncated = True return