From 6377d81d62447d0d312bfffb88f7ae848baf5e5d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:19:26 -0600 Subject: [PATCH 1/8] DR backup: copy loops read a None read as no data yet, not end of stream BACKLOG #6687 (batch 668), added item 1 and the dr_backup half of item 8. One shared fill loop, dr_backup._read_chunks, replaces the bare `if not buf: break` copy loops in _build_archive_blocking (no-key build), _verify_in_staging (plaintext verify) and _extract_config_members. A None read (a non-blocking source with no data ready) is waited out and read again rather than ending the copy short. A blocking source does not answer None, so its reads are unchanged. Left, by the wave's overlap rule (open PR 3202 edits these functions): the copy loops in _extract_member and _restore_blocking (plaintext branch). Tests: tests/test_dr_backup_none_read.py. --- messagefoundry/pipeline/dr_backup.py | 49 +++++-- tests/test_dr_backup_none_read.py | 202 +++++++++++++++++++++++++++ 2 files changed, 238 insertions(+), 13 deletions(-) create mode 100644 tests/test_dr_backup_none_read.py diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 4ea6071b59..635777c0ed 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -57,7 +57,7 @@ from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, field, replace from pathlib import Path -from typing import Any, BinaryIO, Literal, NamedTuple, cast +from typing import Any, BinaryIO, Literal, NamedTuple, Protocol, cast from messagefoundry import file_lock from messagefoundry.config import atomic_edit @@ -450,6 +450,38 @@ def read(self, size: int = -1) -> bytes: return data +class _ChunkSource(Protocol): + """What :func:`_read_chunks` reads from: a binary ``read(n)`` that may answer ``None``.""" + + def read(self, size: int, /) -> bytes | None: ... + + +#: The read size of :func:`_read_chunks`, the 1 MiB the copy loops it replaced read. +_COPY_CHUNK_BYTES = 1024 * 1024 +#: How long :func:`_read_chunks` waits after a ``None`` read before it reads again (BACKLOG #6687). +_NO_DATA_YET_WAIT_SECONDS = 0.01 + + +def _read_chunks(src: _ChunkSource) -> Iterator[bytes]: + """Yield ``src``'s bytes, one ``read`` of up to :data:`_COPY_CHUNK_BYTES` at a time, until an + empty read, which is the end of the stream. + + A ``None`` read is not the end of the stream: a non-blocking source answers ``None`` when it has + no data ready YET. Stopping there, as a bare ``if not buf: break`` loop does, would finish a copy + short and report it as complete. So the loop waits :data:`_NO_DATA_YET_WAIT_SECONDS` and reads + again. The wait is not bounded, the same as a blocking read that never returns. A blocking source + does not answer ``None``, so for one this yields the same reads the old loops wrote (BACKLOG + #6687).""" + while True: + buf = src.read(_COPY_CHUNK_BYTES) + if buf is None: + time.sleep(_NO_DATA_YET_WAIT_SECONDS) + continue + if not buf: + return + yield buf + + def _manifest_time(manifest: dict[str, object]) -> float | None: """The archive's ``created_utc`` as epoch seconds, or ``None`` when it is absent or not the ``YYYY-MM-DDTHH:MM:SSZ`` the backup writes (BACKLOG #2614).""" @@ -1285,10 +1317,7 @@ def _build_archive_blocking( else: # No key + allow_unencrypted: write the plaintext tar verbatim. It can hold PHI: no # instance is synthetic since BACKLOG #1279 (ADR 0186). - while True: - buf = src.read(1024 * 1024) - if not buf: - break + for buf in _read_chunks(src): dst.write(buf) dst.flush() os.fsync(dst.fileno()) @@ -4413,10 +4442,7 @@ def _verify_in_staging( # teardown discards the partial tar on the way out. decrypt_stream(src, dst, match_key, max_plaintext_bytes=_MAX_RESTORE_PLAINTEXT_BYTES) else: - while True: - buf = src.read(1024 * 1024) - if not buf: - break + for buf in _read_chunks(src): dst.write(buf) manifest = _read_manifest_from_tar(tar_path) if manifest.get("config_only"): @@ -7121,10 +7147,7 @@ def _extract_config_members( # secrets (connections.toml), and securing it after the stream would leave the write # under the directory's inherited ACL on Windows for as long as the write takes. _secure_file(out) - while True: - buf = src.read(1024 * 1024) - if not buf: - break + for buf in _read_chunks(src): # Counting the streamed bytes IS the cap enforcement here (a lying header declares a # small size and streams an unbounded one), so this loop cannot become copyfileobj. streamed += len(buf) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py new file mode 100644 index 0000000000..945e389853 --- /dev/null +++ b/tests/test_dr_backup_none_read.py @@ -0,0 +1,202 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", never as end of stream. + +A non-blocking source answers ``None`` when it has nothing ready. The copy loops in +``pipeline/dr_backup.py`` each stopped on ``if not buf: break``, so a ``None`` ended the copy short and +the run went on as if it were complete. They now share :func:`dr_backup._read_chunks`. The sources +here are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" + +from __future__ import annotations + +import builtins +import hashlib +import io +import tarfile +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry.config.settings import BackupSettings, StoreSettings +from messagefoundry.pipeline import dr_backup as dr +from messagefoundry.pipeline.dr_backup import BackupRunner +from messagefoundry.store import MessageStore + +_CHUNK = 1024 * 1024 + + +class _Scripted: + """A source that answers each ``read`` from a fixed script: ``None``, bytes, then ``b""``.""" + + def __init__(self, script: list[bytes | None]) -> None: + self._script = list(script) + self.reads = 0 + + def read(self, size: int = -1, /) -> bytes | None: + self.reads += 1 + if not self._script: + raise AssertionError("read again past an end of stream already returned") + return self._script.pop(0) + + +class _Stalling: + """Wraps a real binary reader: each copy-sized read is answered ``None`` once before the real + read, the way a non-blocking source with no data ready yet answers it.""" + + def __init__(self, inner: Any) -> None: + self._inner = inner + self._owed = True + self.stalls = 0 + + def read(self, size: int = -1, /) -> bytes | None: + if size == _CHUNK and self._owed: + self._owed = False + self.stalls += 1 + return None + self._owed = True + data: bytes | None = self._inner.read(size) + return data + + def __getattr__(self, name: str) -> Any: + return getattr(self._inner, name) + + def __enter__(self) -> _Stalling: + return self + + def __exit__(self, *exc: object) -> None: + self._inner.close() + + +# --- the shared loop itself ------------------------------------------------------------------- + + +def test_a_none_read_is_waited_out_not_read_as_end_of_stream() -> None: + src = _Scripted([None, b"ab", None, None, b"cd", b""]) + assert list(dr._read_chunks(src)) == [b"ab", b"cd"] + assert src.reads == 6 + + +def test_an_empty_read_ends_the_stream_and_nothing_reads_past_it() -> None: + # _Scripted raises on a read past its script, so a loop that kept reading would fail here. + src = _Scripted([b"ab", b""]) + assert list(dr._read_chunks(src)) == [b"ab"] + + +def test_the_scripted_source_refuses_a_read_past_its_end() -> None: + # Positive control for the test above: without it, that test could pass on a source that never + # refuses. + src = _Scripted([b""]) + assert src.read(1) == b"" + with pytest.raises(AssertionError, match="past an end of stream"): + src.read(1) + + +def test_the_stalling_wrapper_answers_none_before_each_copy_sized_read() -> None: + # Positive control: the site tests below rest on this wrapper really answering None. + src = _Stalling(io.BytesIO(b"xy")) + assert src.read(_CHUNK) is None + assert src.read(_CHUNK) == b"xy" + assert src.read(_CHUNK) is None + assert src.read(_CHUNK) == b"" + assert src.stalls == 2 + + +# --- the copy sites --------------------------------------------------------------------------- + + +async def _store_with_a_row(path: Path) -> MessageStore: + store = await MessageStore.open(path) + await store.enqueue_message( + channel_id="c1", + raw="MSH|^~\\&|synthetic-body", + deliveries=[("d1", "OUT|synthetic-delivered")], + control_id="CID-1", + message_type="ADT^A01", + summary="SYNTH001 TEST^PATIENT", + now=1.0, + ) + return store + + +@pytest.mark.parametrize("site", ["build", "verify"]) +async def test_a_plaintext_backup_copies_through_a_none_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str +) -> None: + """The no-key build copies the staged tar to the archive, and verify copies the archive back to + a tar. A ``None`` at either used to end the copy at zero bytes, so verify could not PASS.""" + dest = (tmp_path / "backups").resolve() + wrapped: list[_Stalling] = [] + real_open = builtins.open + + def _open(file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> Any: + fh = real_open(file, mode, *args, **kwargs) + if mode != "rb": + return fh + path = Path(file).resolve() + hit = path.name == "archive.tar" if site == "build" else path.is_relative_to(dest) + if not hit: + return fh + stalling = _Stalling(fh) + wrapped.append(stalling) + return stalling + + monkeypatch.setattr(dr, "open", _open, raising=False) + db = tmp_path / "msg.db" + store = await _store_with_a_row(db) + try: + runner = BackupRunner( + store, + BackupSettings.model_validate( + {"enabled": True, "destination": str(dest), "allow_unencrypted": True} + ), + store_settings=StoreSettings(path=str(db), encryption_key=None), + config_dir=None, + ) + result = await runner.run_once(now=1.0) + finally: + await store.close() + assert sum(w.stalls for w in wrapped) > 0, "no copy-sized read went through the wrapper" + assert result is not None and result.encrypted is False + assert result.verify is not None and result.verify.status == "PASS" + + +def test_a_config_member_is_restored_whole_through_a_none_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + payload = b"synthetic = true\n" * 200_000 # over 3 MiB, so the copy takes several reads + tar_path = tmp_path / "archive.tar" + with tarfile.open(tar_path, "w:") as tar: + info = tarfile.TarInfo("config/settings.toml") + info.size = len(payload) + tar.addfile(info, io.BytesIO(payload)) + + wrapped: list[_Stalling] = [] + real_extractfile = tarfile.TarFile.extractfile + + def _extractfile(self: tarfile.TarFile, member: Any) -> Any: + fh = real_extractfile(self, member) + if fh is None: + return None + stalling = _Stalling(fh) + wrapped.append(stalling) + return stalling + + monkeypatch.setattr(tarfile.TarFile, "extractfile", _extractfile) + dest = tmp_path / "restored-config" + assert dr._extract_config_members(tar_path, dest) == 1 + assert sum(w.stalls for w in wrapped) > 1 + assert hashlib.sha256((dest / "settings.toml").read_bytes()).digest() == ( + hashlib.sha256(payload).digest() + ) + + +# --- _HashingReader (added item 10, met by engine PR 3033; pinned here) ------------------------- + + +def test_the_hashing_reader_passes_a_none_read_through_and_hashes_the_bytes_after_it() -> None: + raw = _Stalling(io.BytesIO(b"synthetic archive bytes")) + reader = dr._HashingReader(raw) # type: ignore[arg-type] + assert reader.read(_CHUNK) is None + assert reader.read(_CHUNK) == b"synthetic archive bytes" + assert reader.digest.hexdigest() == hashlib.sha256(b"synthetic archive bytes").hexdigest() From 96d3b9b9815fbceaf40da98ec686dbe30ccf7d4a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:39:38 -0600 Subject: [PATCH 2/8] DR backup: bound the no-data-yet wait of the shared copy loop BACKLOG #6687, review round 1 (round-70fc7350). _read_chunks waited out a None read with no limit, so a stalled non-blocking source would hold the worker thread. It now raises TimeoutError (an OSError) once None has been the only answer for _NO_DATA_YET_LIMIT_SECONDS (30 s); a byte arriving restarts that limit. Tests pin the sleep per None read, the refusal, and the restart. The test module's docstring no longer reads as if every copy loop moved to the helper: two remain, left by the overlap rule. Corrects the previous commit body: item 8 (one fill loop shared with the codec, sandbox.py and dicom.py) is not met by this branch. --- messagefoundry/pipeline/dr_backup.py | 23 +++++++++++---- tests/test_dr_backup_none_read.py | 43 ++++++++++++++++++++++++---- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 635777c0ed..e264b71a70 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -458,8 +458,10 @@ def read(self, size: int, /) -> bytes | None: ... #: The read size of :func:`_read_chunks`, the 1 MiB the copy loops it replaced read. _COPY_CHUNK_BYTES = 1024 * 1024 -#: How long :func:`_read_chunks` waits after a ``None`` read before it reads again (BACKLOG #6687). +#: How long :func:`_read_chunks` sleeps after a ``None`` read before it reads again (BACKLOG #6687). _NO_DATA_YET_WAIT_SECONDS = 0.01 +#: How long :func:`_read_chunks` keeps reading ``None`` with no byte arriving before it refuses. +_NO_DATA_YET_LIMIT_SECONDS = 30.0 def _read_chunks(src: _ChunkSource) -> Iterator[bytes]: @@ -468,15 +470,26 @@ def _read_chunks(src: _ChunkSource) -> Iterator[bytes]: A ``None`` read is not the end of the stream: a non-blocking source answers ``None`` when it has no data ready YET. Stopping there, as a bare ``if not buf: break`` loop does, would finish a copy - short and report it as complete. So the loop waits :data:`_NO_DATA_YET_WAIT_SECONDS` and reads - again. The wait is not bounded, the same as a blocking read that never returns. A blocking source - does not answer ``None``, so for one this yields the same reads the old loops wrote (BACKLOG - #6687).""" + short and report it as complete. So the loop sleeps :data:`_NO_DATA_YET_WAIT_SECONDS` and reads + again. Once ``None`` has been the only answer for :data:`_NO_DATA_YET_LIMIT_SECONDS` it raises + :class:`TimeoutError`, an ``OSError``, so a source that stalls ends the copy as a failure rather + than holding the worker thread. A blocking source does not answer ``None``, so for one this + yields the same reads the old loops wrote (BACKLOG #6687).""" + stalled_since: float | None = None while True: buf = src.read(_COPY_CHUNK_BYTES) if buf is None: + now = time.monotonic() + if stalled_since is None: + stalled_since = now + elif now - stalled_since >= _NO_DATA_YET_LIMIT_SECONDS: + raise TimeoutError( + "the source stream had no data ready for " + f"{_NO_DATA_YET_LIMIT_SECONDS:g} seconds (non-blocking source)" + ) time.sleep(_NO_DATA_YET_WAIT_SECONDS) continue + stalled_since = None if not buf: return yield buf diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index 945e389853..345bfadbcd 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -2,10 +2,11 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", never as end of stream. -A non-blocking source answers ``None`` when it has nothing ready. The copy loops in -``pipeline/dr_backup.py`` each stopped on ``if not buf: break``, so a ``None`` ended the copy short and -the run went on as if it were complete. They now share :func:`dr_backup._read_chunks`. The sources -here are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" +A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on +``if not buf: break`` ends the copy short there and the run goes on as if it were complete. Three of +the copy loops in ``pipeline/dr_backup.py`` now share :func:`dr_backup._read_chunks`, and these tests +drive each of the three; the loops in ``_extract_member`` and ``_restore_blocking`` are not changed +here. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" from __future__ import annotations @@ -13,6 +14,7 @@ import hashlib import io import tarfile +import time from pathlib import Path from typing import Any @@ -23,7 +25,7 @@ from messagefoundry.pipeline.dr_backup import BackupRunner from messagefoundry.store import MessageStore -_CHUNK = 1024 * 1024 +_CHUNK = dr._COPY_CHUNK_BYTES class _Scripted: @@ -71,10 +73,39 @@ def __exit__(self, *exc: object) -> None: # --- the shared loop itself ------------------------------------------------------------------- -def test_a_none_read_is_waited_out_not_read_as_end_of_stream() -> None: +def test_a_none_read_is_waited_out_not_read_as_end_of_stream( + monkeypatch: pytest.MonkeyPatch, +) -> None: + waits: list[float] = [] + monkeypatch.setattr(time, "sleep", waits.append) src = _Scripted([None, b"ab", None, None, b"cd", b""]) assert list(dr._read_chunks(src)) == [b"ab", b"cd"] assert src.reads == 6 + # Each None read sleeps the documented wait, rather than spinning on the source. + assert waits == [dr._NO_DATA_YET_WAIT_SECONDS] * 3 + + +def test_a_source_that_only_answers_none_is_refused_after_the_limit( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(dr, "_NO_DATA_YET_LIMIT_SECONDS", 0.05) + src = _Scripted([b"ab"] + [None] * 10_000) + chunks = dr._read_chunks(src) + assert next(chunks) == b"ab" + with pytest.raises(TimeoutError, match="no data ready"): + next(chunks) + assert src.reads < 10_001 + + +def test_a_byte_arriving_restarts_the_no_data_limit(monkeypatch: pytest.MonkeyPatch) -> None: + # Each stall here is shorter than the limit, so the copy finishes even though the stalls add up + # to more than it. + monkeypatch.setattr(dr, "_NO_DATA_YET_LIMIT_SECONDS", 0.2) + script: list[bytes | None] = [] + for _ in range(6): + script += [None] * 4 + [b"x"] + src = _Scripted([*script, b""]) + assert b"".join(dr._read_chunks(src)) == b"xxxxxx" def test_an_empty_read_ends_the_stream_and_nothing_reads_past_it() -> None: From 0dce564f11dc2b24e2de7496eaf423fbde268f22 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:06:49 -0600 Subject: [PATCH 3/8] DR backup: state what the no-data-yet limit bounds; deterministic clock in its tests BACKLOG #6687, review round 2 (round-89eaf180). The _read_chunks docstring now says the limit bounds one unbroken run of None reads, not the whole copy. _HashingReader.read is annotated bytes | None, the None pass-through engine PR 3033 built. The tests drive the wait and the limit through a fake clock patched onto dr_backup's own time name, so nothing sleeps or races a real clock, and drop a check that could not fail. The test module's docstring names at least four reads this branch leaves. Proposed PR title: DR backup: copy loops wait out a None read instead of ending the copy short (BACKLOG #6687) Proposed banner, #6687: PARTIAL. Item 1: the no-key build, plaintext verify and config-restore copy loops share _read_chunks (None waited out, refused after 30 s with no byte), tests/test_dr_backup_none_read.py. Items 2, 3, 4, 5, 6, 7, 9 and 10 met on main (evidence in the PR body). Left: item 1 at _extract_member and the _restore_blocking plaintext branch (open PR 3202 edits both functions); item 8, one fill loop shared with the codec, sandbox.py and dicom.py (design). --- messagefoundry/pipeline/dr_backup.py | 11 +++-- tests/test_dr_backup_none_read.py | 72 +++++++++++++++++++--------- 2 files changed, 55 insertions(+), 28 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index e264b71a70..6c9e4efe06 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -438,7 +438,7 @@ def __init__(self, raw: io.BufferedReader) -> None: self._raw = raw self.digest = hashlib.sha256() - def read(self, size: int = -1) -> bytes: + def read(self, size: int = -1) -> bytes | None: data = self._raw.read(size) # A read that is not bytes-like (None from a non-blocking source with nothing ready, or a # str) passes through unhashed. On the keyed branch the codec's own refusal then names it, @@ -471,10 +471,11 @@ def _read_chunks(src: _ChunkSource) -> Iterator[bytes]: A ``None`` read is not the end of the stream: a non-blocking source answers ``None`` when it has no data ready YET. Stopping there, as a bare ``if not buf: break`` loop does, would finish a copy short and report it as complete. So the loop sleeps :data:`_NO_DATA_YET_WAIT_SECONDS` and reads - again. Once ``None`` has been the only answer for :data:`_NO_DATA_YET_LIMIT_SECONDS` it raises - :class:`TimeoutError`, an ``OSError``, so a source that stalls ends the copy as a failure rather - than holding the worker thread. A blocking source does not answer ``None``, so for one this - yields the same reads the old loops wrote (BACKLOG #6687).""" + again. A run of ``None`` reads with no byte between them that lasts + :data:`_NO_DATA_YET_LIMIT_SECONDS` raises :class:`TimeoutError`, an ``OSError``. Any read that + returns bytes starts that limit again, so it bounds one stall, not the whole copy: a source that + sends a byte inside each limit is read for as long as it keeps doing so. A blocking source does + not answer ``None``, so for one this yields the same reads the old loops wrote (BACKLOG #6687).""" stalled_since: float | None = None while True: buf = src.read(_COPY_CHUNK_BYTES) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index 345bfadbcd..53ec37b550 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -3,10 +3,10 @@ """BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", never as end of stream. A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on -``if not buf: break`` ends the copy short there and the run goes on as if it were complete. Three of -the copy loops in ``pipeline/dr_backup.py`` now share :func:`dr_backup._read_chunks`, and these tests -drive each of the three; the loops in ``_extract_member`` and ``_restore_blocking`` are not changed -here. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" +``if not buf: break`` ends the copy short there. Three copy loops in ``pipeline/dr_backup.py`` now +share :func:`dr_backup._read_chunks`, and these tests drive each of the three. Reads in that module +this branch does not change include at least ``_extract_member``, the plaintext branch of +``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" from __future__ import annotations @@ -73,39 +73,65 @@ def __exit__(self, *exc: object) -> None: # --- the shared loop itself ------------------------------------------------------------------- -def test_a_none_read_is_waited_out_not_read_as_end_of_stream( - monkeypatch: pytest.MonkeyPatch, -) -> None: - waits: list[float] = [] - monkeypatch.setattr(time, "sleep", waits.append) +class _FakeClock: + """Stands in for ``dr_backup``'s own ``time`` module: ``sleep`` records the wait and moves a + fake ``monotonic`` on by it, so no test here sleeps or races a real clock. Every other + attribute is the real ``time`` module's.""" + + def __init__(self) -> None: + self.now = 0.0 + self.waits: list[float] = [] + + def monotonic(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.waits.append(seconds) + self.now += seconds + + def __getattr__(self, name: str) -> Any: + return getattr(time, name) + + +@pytest.fixture +def clock(monkeypatch: pytest.MonkeyPatch) -> _FakeClock: + fake = _FakeClock() + monkeypatch.setattr(dr, "time", fake) + return fake + + +def test_a_none_read_is_waited_out_not_read_as_end_of_stream(clock: _FakeClock) -> None: src = _Scripted([None, b"ab", None, None, b"cd", b""]) assert list(dr._read_chunks(src)) == [b"ab", b"cd"] assert src.reads == 6 # Each None read sleeps the documented wait, rather than spinning on the source. - assert waits == [dr._NO_DATA_YET_WAIT_SECONDS] * 3 + assert clock.waits == [dr._NO_DATA_YET_WAIT_SECONDS] * 3 -def test_a_source_that_only_answers_none_is_refused_after_the_limit( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(dr, "_NO_DATA_YET_LIMIT_SECONDS", 0.05) - src = _Scripted([b"ab"] + [None] * 10_000) +def test_a_source_that_only_answers_none_is_refused_at_the_limit(clock: _FakeClock) -> None: + wait, limit = dr._NO_DATA_YET_WAIT_SECONDS, dr._NO_DATA_YET_LIMIT_SECONDS + # Enough None reads to reach the limit and several more; _Scripted raises AssertionError on a + # read past its script, which pytest.raises(TimeoutError) would not catch. + stall = round(limit / wait) + 5 + src = _Scripted([b"ab"] + [None] * stall) chunks = dr._read_chunks(src) assert next(chunks) == b"ab" with pytest.raises(TimeoutError, match="no data ready"): next(chunks) - assert src.reads < 10_001 + assert limit <= clock.now < limit + 2 * wait -def test_a_byte_arriving_restarts_the_no_data_limit(monkeypatch: pytest.MonkeyPatch) -> None: - # Each stall here is shorter than the limit, so the copy finishes even though the stalls add up - # to more than it. - monkeypatch.setattr(dr, "_NO_DATA_YET_LIMIT_SECONDS", 0.2) +def test_a_byte_arriving_restarts_the_no_data_limit(clock: _FakeClock) -> None: + # Each stall is shorter than the limit, and together they are longer than it, so the copy + # finishes only if a byte arriving starts the limit again. + wait, limit = dr._NO_DATA_YET_WAIT_SECONDS, dr._NO_DATA_YET_LIMIT_SECONDS + per_stall = round(limit / wait) // 2 script: list[bytes | None] = [] - for _ in range(6): - script += [None] * 4 + [b"x"] + for _ in range(4): + script += [None] * per_stall + [b"x"] src = _Scripted([*script, b""]) - assert b"".join(dr._read_chunks(src)) == b"xxxxxx" + assert b"".join(dr._read_chunks(src)) == b"xxxx" + assert clock.now > limit def test_an_empty_read_ends_the_stream_and_nothing_reads_past_it() -> None: From 0de1c890242a3bbca925b0a7966167512f2090c4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:28:15 -0600 Subject: [PATCH 4/8] tests: wrap the None-read test module docstring to the line length BACKLOG #6687. Text only, from review round-84ccc3f4 (the unrepaired round): one docstring line ran to 195 columns. No code changes. Proposed PR title: DR backup: copy loops wait out a None read instead of ending the copy short (BACKLOG #6687) Proposed banner, #6687: PARTIAL. Item 1: the no-key build, plaintext verify and config-restore copy loops share _read_chunks (None waited out, refused after 30 s with no byte), tests/test_dr_backup_none_read.py. Items 2, 3, 4, 5, 6, 7, 9 and 10 met on main (evidence in the PR body). Left: item 1 at _extract_member and the _restore_blocking plaintext branch (open PR 3202 edits both functions); item 8, one fill loop shared with the codec, sandbox.py and dicom.py (design). --- tests/test_dr_backup_none_read.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index 53ec37b550..c90a45dc08 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -1,12 +1,13 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", never as end of stream. +"""BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", not as end of stream. A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on ``if not buf: break`` ends the copy short there. Three copy loops in ``pipeline/dr_backup.py`` now share :func:`dr_backup._read_chunks`, and these tests drive each of the three. Reads in that module this branch does not change include at least ``_extract_member``, the plaintext branch of -``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" +``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. +The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" from __future__ import annotations From 4684cee9e43ce364c0afce7451cb0b3f348dbd16 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:44:24 -0600 Subject: [PATCH 5/8] DR backup: the shared copy loop refuses a None read, as the codec does BACKLOG #6687, per the Manager's decision under the owner's instruction of 2026-11-23. _read_chunks now reads through backup_codec._read_once, so the no-key build, plaintext verify and config-restore copies refuse a None read (and a non-bytes or over-long read) with the codec's BackupCodecError, the same rule as the keyed branch. The 30 s wait, its restart logic and their tests are gone. _restore_config_members now names a BackupCodecError as a restore refusal, as it does an OSError. The comment on _MAX_RESTORE_PLAINTEXT_BYTES no longer says the plaintext verify copy is bounded by the archive's size: that limb has no byte cap of its own. Proposed PR title: DR backup: copy loops refuse a None read instead of ending the copy short (BACKLOG #6687) Proposed banner, #6687: PARTIAL. Item 1: the no-key build, plaintext verify and config-restore copy loops share _read_chunks, which refuses a None read through the codec's _read_once; tests/test_dr_backup_none_read.py. Items 2, 3, 4, 5, 6, 7, 9 and 10 met on main. Left: item 1 at _extract_member and the _restore_blocking plaintext branch (open PR 3202 edits both functions); item 8, one fill loop shared with the codec, sandbox.py and dicom.py (design). --- messagefoundry/pipeline/dr_backup.py | 56 +++++------- tests/test_dr_backup_none_read.py | 125 ++++++++++----------------- 2 files changed, 65 insertions(+), 116 deletions(-) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 6c9e4efe06..36018d7c26 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -74,6 +74,7 @@ FORMAT_VERSION, BackupCodecError, BackupKeyMismatch, + _read_once, archive_key_id, decrypt_stream, encrypt_stream, @@ -208,9 +209,10 @@ #: which the decrypt has already written to that same temp dir in full. So the member cap is reached #: only after the disk it protects is spent. This moves the bound to the first write — on the restore #: path, both limbs of it. :func:`_verify_archive_blocking`'s own plaintext limb is still uncounted, -#: though since BACKLOG #1174 it too stages beside a SQLite store. Its copy is no larger than the -#: archive file it reads, and giving it this bound means adding an escape arm to that function's -#: ordered ``except`` block, which is a wider change than the one this constant documents. +#: though since BACKLOG #1174 it too stages beside a SQLite store. That limb has no byte cap of its +#: own: what it copies is whatever the archive path yields, which a device or a growing file does +#: not bound. Giving it this bound means adding an escape arm to that function's ordered ``except`` +#: block, which is a wider change than the one this constant documents. #: #: **Why twice the member cap, and why a multiple rather than a literal.** A conforming archive is one #: ``store.db`` — admitted up to :data:`_MAX_RESTORE_MEMBER_BYTES`, above which the verify FAILs at the @@ -458,39 +460,20 @@ def read(self, size: int, /) -> bytes | None: ... #: The read size of :func:`_read_chunks`, the 1 MiB the copy loops it replaced read. _COPY_CHUNK_BYTES = 1024 * 1024 -#: How long :func:`_read_chunks` sleeps after a ``None`` read before it reads again (BACKLOG #6687). -_NO_DATA_YET_WAIT_SECONDS = 0.01 -#: How long :func:`_read_chunks` keeps reading ``None`` with no byte arriving before it refuses. -_NO_DATA_YET_LIMIT_SECONDS = 30.0 -def _read_chunks(src: _ChunkSource) -> Iterator[bytes]: +def _read_chunks(src: _ChunkSource, what: str) -> Iterator[bytes]: """Yield ``src``'s bytes, one ``read`` of up to :data:`_COPY_CHUNK_BYTES` at a time, until an empty read, which is the end of the stream. - A ``None`` read is not the end of the stream: a non-blocking source answers ``None`` when it has - no data ready YET. Stopping there, as a bare ``if not buf: break`` loop does, would finish a copy - short and report it as complete. So the loop sleeps :data:`_NO_DATA_YET_WAIT_SECONDS` and reads - again. A run of ``None`` reads with no byte between them that lasts - :data:`_NO_DATA_YET_LIMIT_SECONDS` raises :class:`TimeoutError`, an ``OSError``. Any read that - returns bytes starts that limit again, so it bounds one stall, not the whole copy: a source that - sends a byte inside each limit is read for as long as it keeps doing so. A blocking source does - not answer ``None``, so for one this yields the same reads the old loops wrote (BACKLOG #6687).""" - stalled_since: float | None = None + Each read goes through the codec's own ``_read_once``, so a no-key copy refuses what a keyed + one refuses, with the same :class:`BackupCodecError`. That includes a ``None`` read, from a + non-blocking source with no data ready: a bare ``if not buf: break`` loop reads it as the end of + the stream and finishes the copy short (BACKLOG #6687). ``what`` names the copy in the refusal. + A blocking binary file answers each read with at most ``n`` bytes and never ``None``, so for + one this yields the same reads the old loops wrote.""" while True: - buf = src.read(_COPY_CHUNK_BYTES) - if buf is None: - now = time.monotonic() - if stalled_since is None: - stalled_since = now - elif now - stalled_since >= _NO_DATA_YET_LIMIT_SECONDS: - raise TimeoutError( - "the source stream had no data ready for " - f"{_NO_DATA_YET_LIMIT_SECONDS:g} seconds (non-blocking source)" - ) - time.sleep(_NO_DATA_YET_WAIT_SECONDS) - continue - stalled_since = None + buf = _read_once(cast(BinaryIO, src), _COPY_CHUNK_BYTES, what) if not buf: return yield buf @@ -1331,7 +1314,7 @@ def _build_archive_blocking( else: # No key + allow_unencrypted: write the plaintext tar verbatim. It can hold PHI: no # instance is synthetic since BACKLOG #1279 (ADR 0186). - for buf in _read_chunks(src): + for buf in _read_chunks(src, "plaintext tar"): dst.write(buf) dst.flush() os.fsync(dst.fileno()) @@ -4456,7 +4439,7 @@ def _verify_in_staging( # teardown discards the partial tar on the way out. decrypt_stream(src, dst, match_key, max_plaintext_bytes=_MAX_RESTORE_PLAINTEXT_BYTES) else: - for buf in _read_chunks(src): + for buf in _read_chunks(src, "plaintext archive"): dst.write(buf) manifest = _read_manifest_from_tar(tar_path) if manifest.get("config_only"): @@ -6979,13 +6962,14 @@ def _restore_config_members( ) -> int: """:func:`_extract_config_members`, with an ``OSError``, ``ValueError`` or ``tarfile.TarError`` it does not word itself made a refusal (vault BACKLOG #5233). At least these are covered: a - ``PermissionError`` from a ``mkdir``, a full volume, and a member that ends early. Any other - exception type still escapes as it did. Unguarded, each left the restore as a CLI + ``PermissionError`` from a ``mkdir``, a full volume, and a member that ends early. A + :class:`BackupCodecError` from :func:`_read_chunks`, such as a ``None`` read, is made one too + (BACKLOG #6687). Any other exception type still escapes as it did. Unguarded, each left the restore as a CLI traceback, on the config-only route and the store route alike. The caller's ``finally`` still rolls back what ``written`` records.""" try: return _extract_config_members(tar_path, config_dest, written=written) - except (OSError, ValueError, tarfile.TarError) as exc: + except (OSError, ValueError, tarfile.TarError, BackupCodecError) as exc: raise BackupError( "restore", f"could not restore the config bundle into {config_dest}: {safe_exc(exc)}" ) from exc @@ -7161,7 +7145,7 @@ def _extract_config_members( # secrets (connections.toml), and securing it after the stream would leave the write # under the directory's inherited ACL on Windows for as long as the write takes. _secure_file(out) - for buf in _read_chunks(src): + for buf in _read_chunks(src, "config member"): # Counting the streamed bytes IS the cap enforcement here (a lying header declares a # small size and streams an unbounded one), so this loop cannot become copyfileobj. streamed += len(buf) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index c90a45dc08..731bc83fb1 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -1,13 +1,15 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors -"""BACKLOG #6687: a DR copy loop reads a ``None`` read as "no data yet", not as end of stream. +"""BACKLOG #6687: a DR copy loop refuses a ``None`` read rather than reading it as end of stream. A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on ``if not buf: break`` ends the copy short there. Three copy loops in ``pipeline/dr_backup.py`` now -share :func:`dr_backup._read_chunks`, and these tests drive each of the three. Reads in that module -this branch does not change include at least ``_extract_member``, the plaintext branch of -``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. -The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" +share :func:`dr_backup._read_chunks`, which reads through the codec's ``_read_once`` and so refuses +a ``None`` read with the codec's ``BackupCodecError``, as the keyed branch does. These tests drive +each of the three. Reads in that module this branch does not change include at least +``_extract_member``, the plaintext branch of ``_restore_blocking``, the ``shutil.copyfileobj`` in +``_place_restored_store`` and ``_sha256_file``. The sources are synthetic: a store with one made-up +row, and a tar of made-up config bytes.""" from __future__ import annotations @@ -15,7 +17,6 @@ import hashlib import io import tarfile -import time from pathlib import Path from typing import Any @@ -23,10 +24,12 @@ from messagefoundry.config.settings import BackupSettings, StoreSettings from messagefoundry.pipeline import dr_backup as dr -from messagefoundry.pipeline.dr_backup import BackupRunner +from messagefoundry.pipeline.dr_backup import BackupError, BackupRunner from messagefoundry.store import MessageStore +from messagefoundry.store.backup_codec import BackupCodecError -_CHUNK = dr._COPY_CHUNK_BYTES +# The 1 MiB literal is the pre-fix loops' read size, so the module still imports on that code. +_CHUNK: int = getattr(dr, "_COPY_CHUNK_BYTES", 1024 * 1024) class _Scripted: @@ -74,71 +77,19 @@ def __exit__(self, *exc: object) -> None: # --- the shared loop itself ------------------------------------------------------------------- -class _FakeClock: - """Stands in for ``dr_backup``'s own ``time`` module: ``sleep`` records the wait and moves a - fake ``monotonic`` on by it, so no test here sleeps or races a real clock. Every other - attribute is the real ``time`` module's.""" - - def __init__(self) -> None: - self.now = 0.0 - self.waits: list[float] = [] - - def monotonic(self) -> float: - return self.now - - def sleep(self, seconds: float) -> None: - self.waits.append(seconds) - self.now += seconds - - def __getattr__(self, name: str) -> Any: - return getattr(time, name) - - -@pytest.fixture -def clock(monkeypatch: pytest.MonkeyPatch) -> _FakeClock: - fake = _FakeClock() - monkeypatch.setattr(dr, "time", fake) - return fake - - -def test_a_none_read_is_waited_out_not_read_as_end_of_stream(clock: _FakeClock) -> None: - src = _Scripted([None, b"ab", None, None, b"cd", b""]) - assert list(dr._read_chunks(src)) == [b"ab", b"cd"] - assert src.reads == 6 - # Each None read sleeps the documented wait, rather than spinning on the source. - assert clock.waits == [dr._NO_DATA_YET_WAIT_SECONDS] * 3 - - -def test_a_source_that_only_answers_none_is_refused_at_the_limit(clock: _FakeClock) -> None: - wait, limit = dr._NO_DATA_YET_WAIT_SECONDS, dr._NO_DATA_YET_LIMIT_SECONDS - # Enough None reads to reach the limit and several more; _Scripted raises AssertionError on a - # read past its script, which pytest.raises(TimeoutError) would not catch. - stall = round(limit / wait) + 5 - src = _Scripted([b"ab"] + [None] * stall) - chunks = dr._read_chunks(src) +def test_a_none_read_is_refused_not_read_as_end_of_stream() -> None: + src = _Scripted([b"ab", None, b"cd", b""]) + chunks = dr._read_chunks(src, "test copy") assert next(chunks) == b"ab" - with pytest.raises(TimeoutError, match="no data ready"): + with pytest.raises(BackupCodecError, match="no data ready reading the test copy"): next(chunks) - assert limit <= clock.now < limit + 2 * wait - - -def test_a_byte_arriving_restarts_the_no_data_limit(clock: _FakeClock) -> None: - # Each stall is shorter than the limit, and together they are longer than it, so the copy - # finishes only if a byte arriving starts the limit again. - wait, limit = dr._NO_DATA_YET_WAIT_SECONDS, dr._NO_DATA_YET_LIMIT_SECONDS - per_stall = round(limit / wait) // 2 - script: list[bytes | None] = [] - for _ in range(4): - script += [None] * per_stall + [b"x"] - src = _Scripted([*script, b""]) - assert b"".join(dr._read_chunks(src)) == b"xxxx" - assert clock.now > limit + assert src.reads == 2 def test_an_empty_read_ends_the_stream_and_nothing_reads_past_it() -> None: # _Scripted raises on a read past its script, so a loop that kept reading would fail here. - src = _Scripted([b"ab", b""]) - assert list(dr._read_chunks(src)) == [b"ab"] + src = _Scripted([b"ab", b"cd", b""]) + assert list(dr._read_chunks(src, "test copy")) == [b"ab", b"cd"] def test_the_scripted_source_refuses_a_read_past_its_end() -> None: @@ -177,12 +128,15 @@ async def _store_with_a_row(path: Path) -> MessageStore: return store -@pytest.mark.parametrize("site", ["build", "verify"]) -async def test_a_plaintext_backup_copies_through_a_none_read( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str +@pytest.mark.parametrize( + ("site", "what"), [("build", "plaintext tar"), ("verify", "plaintext archive")] +) +async def test_a_plaintext_backup_refuses_a_none_read( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str, what: str ) -> None: """The no-key build copies the staged tar to the archive, and verify copies the archive back to - a tar. A ``None`` at either used to end the copy at zero bytes, so verify could not PASS.""" + a tar. A ``None`` at either used to end the copy at zero bytes, so the run failed later on an + empty tar; it now fails at the read, naming the copy.""" dest = (tmp_path / "backups").resolve() wrapped: list[_Stalling] = [] real_open = builtins.open @@ -211,18 +165,17 @@ def _open(file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> Any: store_settings=StoreSettings(path=str(db), encryption_key=None), config_dir=None, ) - result = await runner.run_once(now=1.0) + with pytest.raises(BackupError, match=f"no data ready reading the {what}"): + await runner.run_once(now=1.0) finally: await store.close() assert sum(w.stalls for w in wrapped) > 0, "no copy-sized read went through the wrapper" - assert result is not None and result.encrypted is False - assert result.verify is not None and result.verify.status == "PASS" -def test_a_config_member_is_restored_whole_through_a_none_read( +def test_a_config_restore_refuses_a_none_read( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - payload = b"synthetic = true\n" * 200_000 # over 3 MiB, so the copy takes several reads + payload = b"synthetic = true\n" * 1000 tar_path = tmp_path / "archive.tar" with tarfile.open(tar_path, "w:") as tar: info = tarfile.TarInfo("config/settings.toml") @@ -242,11 +195,23 @@ def _extractfile(self: tarfile.TarFile, member: Any) -> Any: monkeypatch.setattr(tarfile.TarFile, "extractfile", _extractfile) dest = tmp_path / "restored-config" + written: list[Path] = [] + # The restore's own wrapper turns the codec's refusal into a named BackupError. + with pytest.raises(BackupError, match="no data ready reading the config member"): + dr._restore_config_members(tar_path, dest, written=written) + assert sum(w.stalls for w in wrapped) > 0 + + +def test_a_config_member_still_restores_whole_from_a_blocking_reader(tmp_path: Path) -> None: + payload = b"synthetic = true\n" * 200_000 # over 3 MiB, so the copy takes several reads + tar_path = tmp_path / "archive.tar" + with tarfile.open(tar_path, "w:") as tar: + info = tarfile.TarInfo("config/settings.toml") + info.size = len(payload) + tar.addfile(info, io.BytesIO(payload)) + dest = tmp_path / "restored-config" assert dr._extract_config_members(tar_path, dest) == 1 - assert sum(w.stalls for w in wrapped) > 1 - assert hashlib.sha256((dest / "settings.toml").read_bytes()).digest() == ( - hashlib.sha256(payload).digest() - ) + assert (dest / "settings.toml").read_bytes() == payload # --- _HashingReader (added item 10, met by engine PR 3033; pinned here) ------------------------- From 13a4da5669b9c98785a5678ff6c1b9b48fde8e6e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:00:00 -0600 Subject: [PATCH 6/8] DR backup: say what the shared copy loop shares with the codec; changelog BACKLOG #6687. Text only, from review round-69bdc37c. The _read_chunks docstring says it shares only the codec's per-read checks: it authenticates nothing and caps no total. The plaintext-verify comment no longer gives a false reason for that limb's missing cap. Adds a changelog fragment, including the codec wording an operator sees on a no-key box. No code changes. --- changelog.d/6687-dr-copy-none-read.fixed.md | 4 ++++ messagefoundry/pipeline/dr_backup.py | 19 +++++++++++-------- tests/test_dr_backup_none_read.py | 5 +++-- 3 files changed, 18 insertions(+), 10 deletions(-) create mode 100644 changelog.d/6687-dr-copy-none-read.fixed.md diff --git a/changelog.d/6687-dr-copy-none-read.fixed.md b/changelog.d/6687-dr-copy-none-read.fixed.md new file mode 100644 index 0000000000..4fe4b8b9d3 --- /dev/null +++ b/changelog.d/6687-dr-copy-none-read.fixed.md @@ -0,0 +1,4 @@ +- A no-key DR backup's archive copy, a plaintext verify's copy and a config-bundle restore refuse a + read that returns `None` (a non-blocking source with no data ready), naming the copy, instead of + ending the copy short. On a no-key box that refusal is reported as an `encrypt` failure at + backup and as `decrypt failed` at verify, the codec's wording. (`BACKLOG #6687`) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 36018d7c26..46fd39cc86 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -211,8 +211,8 @@ #: path, both limbs of it. :func:`_verify_archive_blocking`'s own plaintext limb is still uncounted, #: though since BACKLOG #1174 it too stages beside a SQLite store. That limb has no byte cap of its #: own: what it copies is whatever the archive path yields, which a device or a growing file does -#: not bound. Giving it this bound means adding an escape arm to that function's ordered ``except`` -#: block, which is a wider change than the one this constant documents. +#: not bound. Nothing here gives it this bound yet; that is a change of its own, not one this +#: constant documents. #: #: **Why twice the member cap, and why a multiple rather than a literal.** A conforming archive is one #: ``store.db`` — admitted up to :data:`_MAX_RESTORE_MEMBER_BYTES`, above which the verify FAILs at the @@ -466,10 +466,13 @@ def _read_chunks(src: _ChunkSource, what: str) -> Iterator[bytes]: """Yield ``src``'s bytes, one ``read`` of up to :data:`_COPY_CHUNK_BYTES` at a time, until an empty read, which is the end of the stream. - Each read goes through the codec's own ``_read_once``, so a no-key copy refuses what a keyed - one refuses, with the same :class:`BackupCodecError`. That includes a ``None`` read, from a - non-blocking source with no data ready: a bare ``if not buf: break`` loop reads it as the end of - the stream and finishes the copy short (BACKLOG #6687). ``what`` names the copy in the refusal. + Each read goes through the codec's own ``_read_once``, so a single read is held to the same + checks the keyed copies apply to each read, and refused with the same + :class:`BackupCodecError`: a ``None`` read, a read that is not bytes, and a read over the size + asked for. Those per-read checks are all this shares with the keyed copies. It authenticates + nothing and caps no total. A ``None`` read comes from a non-blocking source with no data ready, + and a bare ``if not buf: break`` loop reads it as the end of the stream and finishes the copy + short (BACKLOG #6687). ``what`` names the copy in the refusal. A blocking binary file answers each read with at most ``n`` bytes and never ``None``, so for one this yields the same reads the old loops wrote.""" while True: @@ -6964,8 +6967,8 @@ def _restore_config_members( it does not word itself made a refusal (vault BACKLOG #5233). At least these are covered: a ``PermissionError`` from a ``mkdir``, a full volume, and a member that ends early. A :class:`BackupCodecError` from :func:`_read_chunks`, such as a ``None`` read, is made one too - (BACKLOG #6687). Any other exception type still escapes as it did. Unguarded, each left the restore as a CLI - traceback, on the config-only route and the store route alike. The caller's ``finally`` still + (BACKLOG #6687). Any other exception type still escapes as it did. Unguarded, each left the + restore as a CLI traceback, on the config-only route and the store route alike. The caller's ``finally`` still rolls back what ``written`` records.""" try: return _extract_config_members(tar_path, config_dest, written=written) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index 731bc83fb1..f7f9a87448 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -135,8 +135,9 @@ async def test_a_plaintext_backup_refuses_a_none_read( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str, what: str ) -> None: """The no-key build copies the staged tar to the archive, and verify copies the archive back to - a tar. A ``None`` at either used to end the copy at zero bytes, so the run failed later on an - empty tar; it now fails at the read, naming the copy.""" + a tar. A ``None`` at either used to end the copy short: here, on the first read, it ended it at + zero bytes and the run failed later on an empty tar. It now fails at the read, naming the + copy.""" dest = (tmp_path / "backups").resolve() wrapped: list[_Stalling] = [] real_open = builtins.open From 9720c56f1328d8d1dc481cea0f52812b2952b421 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:11:11 -0600 Subject: [PATCH 7/8] DR backup: a None-read refusal reports as a read failure, not a codec one BACKLOG #6687, per the Manager's decision under the owner's instruction of 2026-11-23. _read_chunks raises the codec's refusal as an OSError (EIO), with the BackupCodecError chained, so each site reports it the way it already reports a read failure there: kind write at the build (it read encrypt), a verify FAIL worded without "decrypt failed", and a restore refusal through _restore_config_members' existing OSError arm. That function is back to main's text. A refused build leaves its .part exactly as main does for any OSError in that copy. The tests now assert the failure kind, and that the refused config file is on the rollback ledger. The changelog fragment drops the codec-wording sentence. Proposed PR title: DR backup: copy loops refuse a None read instead of ending the copy short (BACKLOG #6687) --- changelog.d/6687-dr-copy-none-read.fixed.md | 4 +-- messagefoundry/pipeline/dr_backup.py | 35 ++++++++++++--------- tests/test_dr_backup_none_read.py | 30 ++++++++++++------ 3 files changed, 44 insertions(+), 25 deletions(-) diff --git a/changelog.d/6687-dr-copy-none-read.fixed.md b/changelog.d/6687-dr-copy-none-read.fixed.md index 4fe4b8b9d3..8a00009838 100644 --- a/changelog.d/6687-dr-copy-none-read.fixed.md +++ b/changelog.d/6687-dr-copy-none-read.fixed.md @@ -1,4 +1,4 @@ - A no-key DR backup's archive copy, a plaintext verify's copy and a config-bundle restore refuse a read that returns `None` (a non-blocking source with no data ready), naming the copy, instead of - ending the copy short. On a no-key box that refusal is reported as an `encrypt` failure at - backup and as `decrypt failed` at verify, the codec's wording. (`BACKLOG #6687`) + ending the copy short. Each reports the refusal as the read failure it is: a `write` failure at + backup, a verify `FAIL`, and a restore refusal. (`BACKLOG #6687`) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index 46fd39cc86..ca8f9195d0 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -467,16 +467,24 @@ def _read_chunks(src: _ChunkSource, what: str) -> Iterator[bytes]: empty read, which is the end of the stream. Each read goes through the codec's own ``_read_once``, so a single read is held to the same - checks the keyed copies apply to each read, and refused with the same - :class:`BackupCodecError`: a ``None`` read, a read that is not bytes, and a read over the size - asked for. Those per-read checks are all this shares with the keyed copies. It authenticates - nothing and caps no total. A ``None`` read comes from a non-blocking source with no data ready, - and a bare ``if not buf: break`` loop reads it as the end of the stream and finishes the copy - short (BACKLOG #6687). ``what`` names the copy in the refusal. - A blocking binary file answers each read with at most ``n`` bytes and never ``None``, so for - one this yields the same reads the old loops wrote.""" + checks the keyed copies apply to each read: a ``None`` read, a read that is not bytes, and a + read over the size asked for are refused. Those per-read checks are all this shares with the + keyed copies. It authenticates nothing and caps no total. A ``None`` read comes from a + non-blocking source with no data ready, and a bare ``if not buf: break`` loop reads it as the + end of the stream and finishes the copy short (BACKLOG #6687). ``what`` names the copy in the + refusal. A blocking binary file answers each read with at most ``n`` bytes and never ``None``, + so for one this yields the same reads the old loops wrote. + + The refusal is raised as an ``OSError`` (``EIO``), with the codec's error chained to it, since + it is a failed read of the source. The callers already treat an ``OSError`` from these copies + as a read failure: the build reports failure kind ``write``, the verify a ``FAIL`` not worded as + a decrypt, and the config restore a named refusal. A ``BackupCodecError`` would be reported as + kind ``encrypt`` or as ``decrypt failed``, and a no-key copy does neither.""" while True: - buf = _read_once(cast(BinaryIO, src), _COPY_CHUNK_BYTES, what) + try: + buf = _read_once(cast(BinaryIO, src), _COPY_CHUNK_BYTES, what) + except BackupCodecError as exc: + raise OSError(errno.EIO, str(exc)) from exc if not buf: return yield buf @@ -6965,14 +6973,13 @@ def _restore_config_members( ) -> int: """:func:`_extract_config_members`, with an ``OSError``, ``ValueError`` or ``tarfile.TarError`` it does not word itself made a refusal (vault BACKLOG #5233). At least these are covered: a - ``PermissionError`` from a ``mkdir``, a full volume, and a member that ends early. A - :class:`BackupCodecError` from :func:`_read_chunks`, such as a ``None`` read, is made one too - (BACKLOG #6687). Any other exception type still escapes as it did. Unguarded, each left the - restore as a CLI traceback, on the config-only route and the store route alike. The caller's ``finally`` still + ``PermissionError`` from a ``mkdir``, a full volume, and a member that ends early. Any other + exception type still escapes as it did. Unguarded, each left the restore as a CLI + traceback, on the config-only route and the store route alike. The caller's ``finally`` still rolls back what ``written`` records.""" try: return _extract_config_members(tar_path, config_dest, written=written) - except (OSError, ValueError, tarfile.TarError, BackupCodecError) as exc: + except (OSError, ValueError, tarfile.TarError) as exc: raise BackupError( "restore", f"could not restore the config bundle into {config_dest}: {safe_exc(exc)}" ) from exc diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index f7f9a87448..1067fa9b7a 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -5,8 +5,9 @@ A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on ``if not buf: break`` ends the copy short there. Three copy loops in ``pipeline/dr_backup.py`` now share :func:`dr_backup._read_chunks`, which reads through the codec's ``_read_once`` and so refuses -a ``None`` read with the codec's ``BackupCodecError``, as the keyed branch does. These tests drive -each of the three. Reads in that module this branch does not change include at least +a ``None`` read, as the keyed branch does. It raises the refusal as an ``OSError``, a failed read, +so each site reports it the way it reports any read failure there; these tests drive each of the +three and check that report. Reads in that module this branch does not change include at least ``_extract_member``, the plaintext branch of ``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" @@ -14,6 +15,7 @@ from __future__ import annotations import builtins +import errno import hashlib import io import tarfile @@ -81,8 +83,10 @@ def test_a_none_read_is_refused_not_read_as_end_of_stream() -> None: src = _Scripted([b"ab", None, b"cd", b""]) chunks = dr._read_chunks(src, "test copy") assert next(chunks) == b"ab" - with pytest.raises(BackupCodecError, match="no data ready reading the test copy"): + with pytest.raises(OSError, match="no data ready reading the test copy") as caught: next(chunks) + assert caught.value.errno == errno.EIO + assert isinstance(caught.value.__cause__, BackupCodecError) assert src.reads == 2 @@ -129,15 +133,17 @@ async def _store_with_a_row(path: Path) -> MessageStore: @pytest.mark.parametrize( - ("site", "what"), [("build", "plaintext tar"), ("verify", "plaintext archive")] + ("site", "what", "kind"), + [("build", "plaintext tar", "write"), ("verify", "plaintext archive", "verify")], ) async def test_a_plaintext_backup_refuses_a_none_read( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str, what: str + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site: str, what: str, kind: str ) -> None: """The no-key build copies the staged tar to the archive, and verify copies the archive back to a tar. A ``None`` at either used to end the copy short: here, on the first read, it ended it at zero bytes and the run failed later on an empty tar. It now fails at the read, naming the - copy.""" + copy, with the failure kind a read failure gets there: ``write`` at the build, and at verify a + ``FAIL`` not worded as a decrypt, since a no-key copy decrypts nothing.""" dest = (tmp_path / "backups").resolve() wrapped: list[_Stalling] = [] real_open = builtins.open @@ -166,11 +172,14 @@ def _open(file: Any, mode: str = "r", *args: Any, **kwargs: Any) -> Any: store_settings=StoreSettings(path=str(db), encryption_key=None), config_dir=None, ) - with pytest.raises(BackupError, match=f"no data ready reading the {what}"): + with pytest.raises(BackupError, match=f"no data ready reading the {what}") as caught: await runner.run_once(now=1.0) finally: await store.close() assert sum(w.stalls for w in wrapped) > 0, "no copy-sized read went through the wrapper" + assert caught.value.kind == kind + assert "OSError" in str(caught.value) + assert "decrypt" not in str(caught.value) def test_a_config_restore_refuses_a_none_read( @@ -197,10 +206,13 @@ def _extractfile(self: tarfile.TarFile, member: Any) -> Any: monkeypatch.setattr(tarfile.TarFile, "extractfile", _extractfile) dest = tmp_path / "restored-config" written: list[Path] = [] - # The restore's own wrapper turns the codec's refusal into a named BackupError. - with pytest.raises(BackupError, match="no data ready reading the config member"): + # The restore's own wrapper names the read failure as a restore refusal. + with pytest.raises(BackupError, match="no data ready reading the config member") as caught: dr._restore_config_members(tar_path, dest, written=written) assert sum(w.stalls for w in wrapped) > 0 + assert caught.value.kind == "restore" + # The file the refused copy opened is on the caller's rollback ledger. + assert (dest / "settings.toml").resolve() in [p.resolve() for p in written] def test_a_config_member_still_restores_whole_from_a_blocking_reader(tmp_path: Path) -> None: From 380b8d8f114c9bf4e93fee0c116f04cdf8d53a41 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:29:16 -0600 Subject: [PATCH 8/8] DR backup: say the None-read refusal is handled as any OSError there BACKLOG #6687. Text only, from review round-c02119ea. The _read_chunks docstring, the test prose and the changelog no longer say the sites record a read failure: each handles the refusal as it handles any OSError from that copy, which its own except arms define. "All this shares with the keyed copies" becomes "at least". No code changes. --- changelog.d/6687-dr-copy-none-read.fixed.md | 5 +++-- messagefoundry/pipeline/dr_backup.py | 24 ++++++++++----------- tests/test_dr_backup_none_read.py | 12 +++++------ 3 files changed, 20 insertions(+), 21 deletions(-) diff --git a/changelog.d/6687-dr-copy-none-read.fixed.md b/changelog.d/6687-dr-copy-none-read.fixed.md index 8a00009838..fb91e171d3 100644 --- a/changelog.d/6687-dr-copy-none-read.fixed.md +++ b/changelog.d/6687-dr-copy-none-read.fixed.md @@ -1,4 +1,5 @@ - A no-key DR backup's archive copy, a plaintext verify's copy and a config-bundle restore refuse a read that returns `None` (a non-blocking source with no data ready), naming the copy, instead of - ending the copy short. Each reports the refusal as the read failure it is: a `write` failure at - backup, a verify `FAIL`, and a restore refusal. (`BACKLOG #6687`) + ending the copy short. The refusal is an `OSError`, reported as each site reports any `OSError` + in that copy: a `write` failure at backup, a verify `FAIL`, and a restore refusal. + (`BACKLOG #6687`) diff --git a/messagefoundry/pipeline/dr_backup.py b/messagefoundry/pipeline/dr_backup.py index ca8f9195d0..ed69adee5c 100644 --- a/messagefoundry/pipeline/dr_backup.py +++ b/messagefoundry/pipeline/dr_backup.py @@ -466,20 +466,18 @@ def _read_chunks(src: _ChunkSource, what: str) -> Iterator[bytes]: """Yield ``src``'s bytes, one ``read`` of up to :data:`_COPY_CHUNK_BYTES` at a time, until an empty read, which is the end of the stream. - Each read goes through the codec's own ``_read_once``, so a single read is held to the same + Each read goes through the codec's own ``_read_once``, so a single read is held to at least the checks the keyed copies apply to each read: a ``None`` read, a read that is not bytes, and a - read over the size asked for are refused. Those per-read checks are all this shares with the - keyed copies. It authenticates nothing and caps no total. A ``None`` read comes from a - non-blocking source with no data ready, and a bare ``if not buf: break`` loop reads it as the - end of the stream and finishes the copy short (BACKLOG #6687). ``what`` names the copy in the - refusal. A blocking binary file answers each read with at most ``n`` bytes and never ``None``, - so for one this yields the same reads the old loops wrote. - - The refusal is raised as an ``OSError`` (``EIO``), with the codec's error chained to it, since - it is a failed read of the source. The callers already treat an ``OSError`` from these copies - as a read failure: the build reports failure kind ``write``, the verify a ``FAIL`` not worded as - a decrypt, and the config restore a named refusal. A ``BackupCodecError`` would be reported as - kind ``encrypt`` or as ``decrypt failed``, and a no-key copy does neither.""" + read over the size asked for are refused. It authenticates nothing and caps no total. A ``None`` + read comes from a non-blocking source with no data ready, and a bare ``if not buf: break`` loop + reads it as the end of the stream and finishes the copy short (BACKLOG #6687). ``what`` names + the copy in the refusal. A blocking binary file answers each read with at most ``n`` bytes and + never ``None``, so for one this yields the same reads the old loops wrote. + + The refusal is raised as an ``OSError`` (``EIO``) with the codec's error chained to it, so each + caller handles it as it handles any ``OSError`` from that copy, which the callers' own ``except`` + arms define. A ``BackupCodecError`` would instead be reported as an encrypt or decrypt failure, + and a no-key copy does neither.""" while True: try: buf = _read_once(cast(BinaryIO, src), _COPY_CHUNK_BYTES, what) diff --git a/tests/test_dr_backup_none_read.py b/tests/test_dr_backup_none_read.py index 1067fa9b7a..f75285aa61 100644 --- a/tests/test_dr_backup_none_read.py +++ b/tests/test_dr_backup_none_read.py @@ -5,9 +5,9 @@ A non-blocking source answers ``None`` when it has nothing ready. A copy loop that stops on ``if not buf: break`` ends the copy short there. Three copy loops in ``pipeline/dr_backup.py`` now share :func:`dr_backup._read_chunks`, which reads through the codec's ``_read_once`` and so refuses -a ``None`` read, as the keyed branch does. It raises the refusal as an ``OSError``, a failed read, -so each site reports it the way it reports any read failure there; these tests drive each of the -three and check that report. Reads in that module this branch does not change include at least +a ``None`` read, as the keyed branch does. It raises the refusal as an ``OSError``, so each site +reports it the way it reports any ``OSError`` in that copy; these tests drive each of the three and +check that report. Reads in that module this branch does not change include at least ``_extract_member``, the plaintext branch of ``_restore_blocking``, the ``shutil.copyfileobj`` in ``_place_restored_store`` and ``_sha256_file``. The sources are synthetic: a store with one made-up row, and a tar of made-up config bytes.""" @@ -142,8 +142,8 @@ async def test_a_plaintext_backup_refuses_a_none_read( """The no-key build copies the staged tar to the archive, and verify copies the archive back to a tar. A ``None`` at either used to end the copy short: here, on the first read, it ended it at zero bytes and the run failed later on an empty tar. It now fails at the read, naming the - copy, with the failure kind a read failure gets there: ``write`` at the build, and at verify a - ``FAIL`` not worded as a decrypt, since a no-key copy decrypts nothing.""" + copy, with the failure kind any ``OSError`` in that copy gets: ``write`` at the build, and at + verify a ``FAIL`` not worded as a decrypt, since a no-key copy decrypts nothing.""" dest = (tmp_path / "backups").resolve() wrapped: list[_Stalling] = [] real_open = builtins.open @@ -206,7 +206,7 @@ def _extractfile(self: tarfile.TarFile, member: Any) -> Any: monkeypatch.setattr(tarfile.TarFile, "extractfile", _extractfile) dest = tmp_path / "restored-config" written: list[Path] = [] - # The restore's own wrapper names the read failure as a restore refusal. + # The restore's own wrapper names the OSError as a restore refusal. with pytest.raises(BackupError, match="no data ready reading the config member") as caught: dr._restore_config_members(tar_path, dest, written=written) assert sum(w.stalls for w in wrapped) > 0