diff --git a/changelog.d/6824.fixed.md b/changelog.d/6824.fixed.md new file mode 100644 index 0000000000..0c0674418e --- /dev/null +++ b/changelog.d/6824.fixed.md @@ -0,0 +1,10 @@ +- **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/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 0622cf6e5a..e51454301d 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 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. @@ -67,6 +70,7 @@ import inspect import math import sys +import threading from collections.abc import Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -94,6 +98,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. +# Semantics: :meth:`_Recorder.record_write` (BACKLOG #6824). +_MAX_WRITES = 5000 _MAX_VALUE_LEN = 120 @@ -289,6 +297,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`. @@ -300,6 +309,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 --------------------------------------------------------- @@ -349,6 +359,22 @@ 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 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`, 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 + 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)} @@ -418,6 +444,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 @@ -525,22 +553,44 @@ def _recording_write( *, as_data: bool, ) -> None: + # 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 +# 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 + held = False try: + # 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] + _patch_holders += 1 + held = True yield finally: - Message._write = _ORIG_MESSAGE_WRITE # type: ignore[method-assign] + 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 2053dd93a1..b7852b786d 100644 --- a/tests/test_dryrun_trace.py +++ b/tests/test_dryrun_trace.py @@ -836,3 +836,191 @@ 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 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: + 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("writes_truncated") is True + 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. + 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 _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: + # 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 + + assert dt._patch_holders == 0 + a_entered = threading.Event() + b_exited = threading.Event() + seen: dict[str, object] = {} + + def run_a() -> None: + with dt._patched_message_writes(): + a_entered.set() + assert b_exited.wait(10) + seen["a_during"] = Message._write + + def run_b() -> None: + assert a_entered.wait(10) + with dt._patched_message_writes(): + pass + b_exited.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 + + +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: + assert a_paused.wait(10) + results["b"] = trace_dry_run(_registry(route_to_h, {"h": handle_transform}), ADT_A01) + b_done.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