From 5b59d993432debee559e4aab8701a26f33e803ad Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:17:48 -0600 Subject: [PATCH 1/9] Security notifier: a cut close records the notices it left unsent When the shutdown's bounded step cut SecurityEventNotifier.aclose while a send waited on a slow relay, the notices still queued got no audit row, and on a full queue the close was cut while putting its stop sentinel, so the drain ran on past the close into the closed store. aclose now cancels a drain the cut left running, records the cut send with reason "interrupted" (its thread may still deliver it) and each notice still queued with reason "closing", before it returns. A WARNING line counts the queued notices, lock notices left out (BACKLOG #1131). SECURITY.md's residual bullet and the alert sink's aclose docstring are corrected to match. BACKLOG #6832 Proposed vault banner: FIXED (batch 673, branch b673/notify-aclose). Adjudicated by failing tests: a cut close left queued notices unrecorded, and a cut on a full queue left the drain running. aclose now cancels the drain and records the cut send (reason interrupted) and each queued notice (reason closing) while the store is open. Residual: those writes run in the teardown's 0.1 s cut grace, so one still running then can meet the closed store. --- changelog.d/6832.fixed.md | 5 ++ docs/SECURITY.md | 14 ++-- messagefoundry/pipeline/alert_sinks.py | 5 +- messagefoundry/pipeline/security_notify.py | 46 +++++++++- tests/test_security_notice_undelivered.py | 98 ++++++++++++++++++++++ 5 files changed, 159 insertions(+), 9 deletions(-) create mode 100644 changelog.d/6832.fixed.md diff --git a/changelog.d/6832.fixed.md b/changelog.d/6832.fixed.md new file mode 100644 index 0000000000..0a78c17fa3 --- /dev/null +++ b/changelog.d/6832.fixed.md @@ -0,0 +1,5 @@ +- **A cut close of the security notifier records the notices it left unsent.** When the shutdown + cut `SecurityEventNotifier.aclose` while a send waited on a slow relay, the notices still queued + got no audit row, and on a full queue the drain ran on past the close. The close now cancels its + drain and records the cut send with `reason: interrupted` and each queued notice with + `reason: closing`, while the store is open. (`BACKLOG #6832`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 683b84c934..7b035a3d50 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7960,11 +7960,11 @@ same drops give totals one apart by lane. when the notice is handed to the relay. It reads `mailed: true` only when the relay queued the notice: one its full queue dropped, or one it refused because it had begun to close, reads `mailed: false`, so the next lock of the kind mails again (vault BACKLOG #3120). When the relay's queue is full, the relay refuses the notice because it has -begun to close, or the send fails, the engine writes one more row, with the notice's recipient as -the actor. A lock +begun to close, a cut close leaves the notice queued or cuts its send, or the send fails, the +engine writes one more row, with the notice's recipient as the actor. A lock notice writes `auth.lock_notice_undelivered`, hidden as above. Every other notice kind writes `auth.security_notice_undelivered`, which every `audit:read` reader sees. The detail names the -notice kind and the `reason`, `queue_full`, `closing` or `send_failed`. An issuer's reminder also names the +notice kind and the `reason`, `queue_full`, `closing`, `interrupted` or `send_failed`. An issuer's reminder also names the holder. The row never carries the address, the rest of the notice's detail, or the error. The source of record is `SecurityEventNotifier._record_undelivered` in `messagefoundry/pipeline/security_notify.py`. At least the offline commands `provision-admin` and @@ -7981,8 +7981,12 @@ again for the row, and only when a send failed. **Still open, at least:** - At shutdown the notifier closes while the store is still open (BACKLOG #3191), so a send that fails in its final drain is recorded. That close is one bounded step of the shutdown. When the - step is cut, a notice still queued is neither sent nor recorded, and a send already under way - may still go out or fail unrecorded. A lock notice among them keeps its `auth.lock_notice` row + step is cut, the close cancels its drain and records the send it cut with `reason: interrupted` + and each notice still queued with `reason: closing` (BACKLOG #6832). The cut send's thread runs + on to its own timeout, so that notice may still go out. Those writes run in the step's cut + grace, so one still running when the grace ends can meet the closed store and is lost like any + failed record write. A WARNING line counting the queued notices, never a lock notice, comes + before their writes. A lock notice among them keeps its `auth.lock_notice` row reading `mailed: true`, so the throttle holds back that account's next lock notice of the kind for the rest of its 24 hours. - A notice that reaches the notifier once it has begun to close is refused and recorded with diff --git a/messagefoundry/pipeline/alert_sinks.py b/messagefoundry/pipeline/alert_sinks.py index ad32ff6750..b9178a6904 100644 --- a/messagefoundry/pipeline/alert_sinks.py +++ b/messagefoundry/pipeline/alert_sinks.py @@ -2610,8 +2610,9 @@ async def aclose(self) -> None: was never started. A close cancelled while its sentinel waits on a full queue cancels the delivery task too and waits for it (BACKLOG #5907), so the startup unwind's cut does not leave the drain running after the store closed; a send that outlives the drain's grace is - still left running (:meth:`_cut_sends`). Only this sink does that: an undelivered alert is - counted by :attr:`undelivered`, while a security notice's loss must reach its audit row.""" + still left running (:meth:`_cut_sends`). The security notifier's close cancels its drain + too, and then records each notice the cut left unsent in the audit log (BACKLOG #6832), + while an undelivered alert is counted by :attr:`undelivered`.""" drain = self._task try: await super().aclose() diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 1b0ea76bf4..aed13e70cd 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -806,17 +806,59 @@ def start(self) -> None: super().start() async def aclose(self) -> None: + """Drain the queue and stop. A close cut short, as the shutdown's bounded step cuts it, + cancels the drain, and records the notice whose send it cut and every notice still queued + before it returns, so each is recorded while the store is open (BACKLOG #6832).""" self._closing = True # before the sentinel goes in, so nothing is queued behind it + drain = self._task try: await super().aclose() finally: - # Each one swallows its own failure, so this only waits. - await asyncio.gather(*self._recording, return_exceptions=True) + try: + if drain is not None: + if not drain.done(): + # Cut while the sentinel waited on a full queue: the drain still runs. A + # cut while the close waited on the drain has already cancelled it. + drain.cancel() + self._task = None + await asyncio.gather(drain, return_exceptions=True) + await self._record_abandoned() + finally: + # Each one swallows its own failure, so this only waits. + await asyncio.gather(*self._recording, return_exceptions=True) + + async def _record_abandoned(self) -> None: + """Record each notice the close left on the queue, never sent (BACKLOG #6832). One at a + time, without the queue-full path's cap: the queue's own bound caps the count.""" + left: list[SecurityEvent] = [] + while not self._queue.empty(): + event = self._queue.get_nowait() + if event is not None: + left.append(event) + if not left: + return + # A count, and never one that includes a lock notice (BACKLOG #1131). Logged before the + # writes, so a write the closing store refuses still leaves the loss in the log. + shown = sum(event.event_type not in LOG_SILENT_EVENT_TYPES for event in left) + if shown: + log.warning( + "%s closed with %d security notice(s) still queued; recording them as undelivered", + type(self).__name__, + shown, + ) + for event in left: + await self._record_undelivered(event, {"reason": "closing"}) async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: try: if await asyncio.to_thread(self._send, event): delivered() + except asyncio.CancelledError: + # The close was cut while this send waited on the relay (BACKLOG #6832). The send's + # thread runs on to its own timeout, so the notice may still go out: "interrupted" + # says its delivery is unknown, apart from a send that raised. + await self._record_undelivered(event, {"reason": "interrupted"}) + raise except Exception: # Best-effort: a failed send must never propagate. The event is usually also in the audit # log; a refused directory-reconciler audit write leaves no row (BACKLOG #3018). diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index 780ebf2697..bbacab5c99 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -11,6 +11,7 @@ import asyncio import json +import threading from collections.abc import AsyncIterator from pathlib import Path from typing import Any, cast @@ -601,3 +602,100 @@ async def opener() -> Any: "an undelivered security notice could not be recorded in the audit log (OSError)" ] assert _STILL_RUNNING not in [r.getMessage() for r in caplog.records] + + +def _blocking_send(monkeypatch: pytest.MonkeyPatch) -> tuple[threading.Event, threading.Event]: + """A send that blocks its worker thread until released, as a slow relay would.""" + started = threading.Event() + release = threading.Event() + + def slow(**_: Any) -> None: + started.set() + release.wait(5.0) + + monkeypatch.setattr(_SEND, slow) + return started, release + + +async def test_a_cut_close_records_every_notice_it_left_unsent( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832. The shutdown cuts the notifier's close while a send waits on a slow relay. The + send under way and each notice still queued gets its own row while the store is open, and the + drain does not outlive the close.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + drain = notifier._task + assert drain is not None + for name in ("amy", "ben"): + await notifier.notify( + SecurityEvent(PASSWORD_CHANGED, username=name, email=f"{name}@x.test") + ) + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-c", email="c@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + assert drain.done() + assert sorted(await _undelivered(store)) == [ + ( + LOCK_NOTICE_UNDELIVERED_ACTION, + "lock-c", + {"notice": "account_locked", "reason": "closing"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "interrupted"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "ben", + {"notice": "password_changed", "reason": "closing"}, + ), + ] + assert notifier.undelivered == 3 + finally: + release.set() + + +async def test_a_close_cut_on_a_full_queue_cancels_the_drain( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832. On a full queue the close waits to put its stop sentinel, so a cut there used + to leave the drain running past the close, into the closed store.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier._queue = asyncio.Queue(maxsize=1) + notifier.start() + drain = notifier._task + assert drain is not None + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + assert not closing.done() # waiting on the full queue + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + assert drain.done() + assert sorted(await _undelivered(store)) == [ + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "interrupted"}, + ), + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "ben", + {"notice": "password_changed", "reason": "closing"}, + ), + ] + finally: + release.set() From dea48cbb0d1fdfa0b8d99b5bebbf207e3b2be42f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:20:54 -0600 Subject: [PATCH 2/9] Lock-notice test: a cut close now leaves no stop sentinel queued The precondition of the BACKLOG #3120 restart test read the sentinel a cut close left behind. The close now empties the queue, recording each notice it took, so the precondition reads an empty queue; the property assertions are unchanged. BACKLOG #6832 --- tests/test_lock_notice_off_request_path.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_lock_notice_off_request_path.py b/tests/test_lock_notice_off_request_path.py index 721dbc7269..82fe039ee5 100644 --- a/tests/test_lock_notice_off_request_path.py +++ b/tests/test_lock_notice_off_request_path.py @@ -882,7 +882,9 @@ def held_send(**kw: Any) -> None: assert await asyncio.to_thread(started.wait, _STALL_SECONDS), "the send never started" with pytest.raises(TimeoutError): # the teardown's bound, cutting the close await asyncio.wait_for(relay.aclose(), 0.05) - assert relay._queue.qsize() == 1, "the cut close left no stop sentinel to test against" + # BACKLOG #6832: the cut close now empties the queue, its stop sentinel too, recording each + # notice it took. The property below still binds a start after it. + assert relay._queue.qsize() == 0, "the cut close left its sentinel or a notice queued" with suppress(RuntimeError): # refusing is one way to keep the property below relay.start() late = SecurityEvent(PASSWORD_CHANGED, username="b", email="b@x.test") From 0fd87b2b5aad51dae718afafc589e5213f81fff9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:55:04 -0600 Subject: [PATCH 3/9] Security notifier: review round one on the cut-close records The send is shielded and held on the notifier, so a cut close reads how it ended rather than guessing: a send already finished counts as delivered or failed, and only one still running is "interrupted". A failed send's record is a held, shielded task, so a cut during that write no longer cancels it. Queued notices are taken and counted in the log before any await, so a second cancel cannot leave them untold, and they are recorded as "abandoned", apart from a notice refused once the close began ("closing"). Failed records at close are summed into one WARNING line; no sink means no record claim. SECURITY.md, the changelog fragment, __main__'s counting-sink comments and the BACKLOG #3120 test docstring are corrected to match. BACKLOG #6832 --- changelog.d/6832.fixed.md | 6 +- docs/SECURITY.md | 14 +- messagefoundry/__main__.py | 14 +- messagefoundry/pipeline/security_notify.py | 157 ++++++++++++++------- tests/test_lock_notice_off_request_path.py | 7 +- tests/test_security_notice_undelivered.py | 89 +++++++++++- 6 files changed, 219 insertions(+), 68 deletions(-) diff --git a/changelog.d/6832.fixed.md b/changelog.d/6832.fixed.md index 0a78c17fa3..7dceaf6308 100644 --- a/changelog.d/6832.fixed.md +++ b/changelog.d/6832.fixed.md @@ -1,5 +1,7 @@ - **A cut close of the security notifier records the notices it left unsent.** When the shutdown cut `SecurityEventNotifier.aclose` while a send waited on a slow relay, the notices still queued got no audit row, and on a full queue the drain ran on past the close. The close now cancels its - drain and records the cut send with `reason: interrupted` and each queued notice with - `reason: closing`, while the store is open. (`BACKLOG #6832`) + drain and, before it returns, records the cut send with `reason: interrupted` and each queued + notice with `reason: abandoned`, and logs how many were queued. At shutdown those writes run in + the cut step's short grace, so a write still to run when it ends meets the closed store and is + lost; [SECURITY.md](../docs/SECURITY.md) keeps that as an open residual. (`BACKLOG #6832`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 7b035a3d50..c1de58a577 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7964,7 +7964,8 @@ begun to close, a cut close leaves the notice queued or cuts its send, or the se engine writes one more row, with the notice's recipient as the actor. A lock notice writes `auth.lock_notice_undelivered`, hidden as above. Every other notice kind writes `auth.security_notice_undelivered`, which every `audit:read` reader sees. The detail names the -notice kind and the `reason`, `queue_full`, `closing`, `interrupted` or `send_failed`. An issuer's reminder also names the +notice kind and the `reason`, at least `queue_full`, `closing`, `abandoned`, `interrupted` or +`send_failed`. An issuer's reminder also names the holder. The row never carries the address, the rest of the notice's detail, or the error. The source of record is `SecurityEventNotifier._record_undelivered` in `messagefoundry/pipeline/security_notify.py`. At least the offline commands `provision-admin` and @@ -7982,11 +7983,12 @@ again for the row, and only when a send failed. **Still open, at least:** - At shutdown the notifier closes while the store is still open (BACKLOG #3191), so a send that fails in its final drain is recorded. That close is one bounded step of the shutdown. When the step is cut, the close cancels its drain and records the send it cut with `reason: interrupted` - and each notice still queued with `reason: closing` (BACKLOG #6832). The cut send's thread runs - on to its own timeout, so that notice may still go out. Those writes run in the step's cut - grace, so one still running when the grace ends can meet the closed store and is lost like any - failed record write. A WARNING line counting the queued notices, never a lock notice, comes - before their writes. A lock notice among them keeps its `auth.lock_notice` row + and each notice still queued with `reason: abandoned` (BACKLOG #6832). The cut send's thread + runs on to its own timeout, so that notice may still go out. Those writes run one at a time in + the step's cut grace, so the ones still to run when the grace ends meet the closed store and + are lost; under a full queue that is most of them. A WARNING line counting the queued notices + comes before their writes, and one counting the writes that failed comes after; neither counts + a lock notice. A lock notice among them keeps its `auth.lock_notice` row reading `mailed: true`, so the throttle holds back that account's next lock notice of the kind for the rest of its 24 hours. - A notice that reaches the notifier once it has begun to close is refused and recorded with diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 8cc7d70e4e..9bba3cc76b 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -9651,11 +9651,13 @@ def run() -> None: class _CountingNoticeAudit: """A :class:`NoticeAuditSink` that forwards to ``inner`` and counts the undelivered records the notifier asked for, so ``provision-admin`` can say that delivery of a notice it reported as - dispatched is unconfirmed (BACKLOG #5634). For a dispatched notice the notifier records only a - send that raised, so a count above zero is one, whether or not the forwarded write then - succeeded. A send can raise after the relay queued the mail, so it is not proof the notice - never left. A count of zero is not a delivery receipt: at least a drain ended by an interrupt - asks for no record.""" + dispatched is unconfirmed (BACKLOG #5634). For a dispatched notice the notifier records a send + that raised, and, when its close is cut, the send it cut or the notice it left queued (BACKLOG + #6832); only an interrupt cuts this command's close, and it ends the run before the count is + read. So a count above zero says delivery is unconfirmed, whether or not the forwarded write + then succeeded. A send can raise after the relay queued the mail, so it is not proof the notice + never left. A count of zero is not a delivery receipt: a send that returned says only that the + relay took the mail.""" def __init__(self, inner: NoticeAuditSink) -> None: self._inner = inner @@ -11543,7 +11545,7 @@ async def alert() -> bool: # BACKLOG #5634: the notifier drained before run() returned, so its count is final here. None # unless a notice was dispatched. False is not a delivery receipt: it says only that the - # notifier recorded no undelivered notice, and at least a drain ended by an interrupt records none. + # notifier recorded no undelivered notice, and a send that returned says only the relay took it. holder_send_failed: bool | None = ( bool(notice_audit) and notice_audit[0].undelivered > 0 if outcome.holder_notice == HOLDER_NOTICE_DISPATCHED diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index aed13e70cd..0b3e220fcd 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -642,6 +642,13 @@ def _build_body(event: SecurityEvent) -> str: return "\n".join(lines) +def _consume_outcome(send: asyncio.Future[bool]) -> None: + """Read a send's outcome, so asyncio never reports it unread: after a cut close nobody else + reads it (BACKLOG #6832).""" + if not send.cancelled(): + send.exception() + + class SecurityEventNotifier(_BackgroundDispatcher[SecurityEvent]): """Emails the affected user about a security event, on a bounded background queue. @@ -704,7 +711,10 @@ def __init__( self._audit = audit # The queue-full records still being written, held so the loop keeps them alive and so # aclose() can wait for them. - self._recording: set[asyncio.Task[None]] = set() + self._recording: set[asyncio.Future[bool]] = set() + # The send the drain is waiting on, with what it needs to record or count it, so a cut + # close can record it (BACKLOG #6832). None between sends. + self._sending: tuple[SecurityEvent, asyncio.Future[bool], Callable[[], None]] | None = None # Set when aclose() begins, and never cleared: start() refuses (vault BACKLOG #3120). An event # queued after that sits behind the stop sentinel, or on a queue nothing reads, and is never # sent, so notify() refuses it; the contract on ``SecurityNotifier`` says why. @@ -797,8 +807,9 @@ def _record_dropped(self, event: SecurityEvent, reason: str) -> None: task.add_done_callback(self._recording.discard) def start(self) -> None: - # Never again once closed (vault BACKLOG #3120). A close the teardown cut short can leave its - # stop sentinel on the queue, so a drain loop started again would read it and stop, and + # Never again once closed (vault BACKLOG #3120). A cut close empties the queue (BACKLOG + # #6832), but one cancelled a second time can still leave its stop sentinel there, so a drain + # loop started again would read it and stop, and # notify() would answer True for events nothing sends. The engine builds a new notifier for # each lifespan rather than restart one. if self._closing: @@ -807,13 +818,17 @@ def start(self) -> None: async def aclose(self) -> None: """Drain the queue and stop. A close cut short, as the shutdown's bounded step cuts it, - cancels the drain, and records the notice whose send it cut and every notice still queued - before it returns, so each is recorded while the store is open (BACKLOG #6832).""" + cancels the drain and, before it returns, records the send it cut and each notice still + queued (BACKLOG #6832). In the shutdown those writes run in the cut step's grace, so one + still running when the teardown stops waiting can meet the closed store and is lost like + any failed record write. The count of queued notices is logged before any of them.""" self._closing = True # before the sentinel goes in, so nothing is queued behind it drain = self._task try: await super().aclose() finally: + # Taken and logged before any await, so a second cancel cannot leave them untold. + left = self._take_queued() try: if drain is not None: if not drain.done(): @@ -822,61 +837,105 @@ async def aclose(self) -> None: drain.cancel() self._task = None await asyncio.gather(drain, return_exceptions=True) - await self._record_abandoned() finally: - # Each one swallows its own failure, so this only waits. - await asyncio.gather(*self._recording, return_exceptions=True) + try: + await self._record_cut(left) + finally: + # Each one swallows its own failure, so this only waits. + await asyncio.gather(*self._recording, return_exceptions=True) - async def _record_abandoned(self) -> None: - """Record each notice the close left on the queue, never sent (BACKLOG #6832). One at a - time, without the queue-full path's cap: the queue's own bound caps the count.""" + def _take_queued(self) -> list[SecurityEvent]: + """Empty the queue, stop sentinel included, and log how many notices it held. Only a cut + close leaves any: an uncut one drained them all.""" left: list[SecurityEvent] = [] while not self._queue.empty(): - event = self._queue.get_nowait() - if event is not None: + if (event := self._queue.get_nowait()) is not None: left.append(event) - if not left: - return - # A count, and never one that includes a lock notice (BACKLOG #1131). Logged before the - # writes, so a write the closing store refuses still leaves the loss in the log. + # A count, never one that includes a lock notice (BACKLOG #1131). shown = sum(event.event_type not in LOG_SILENT_EVENT_TYPES for event in left) if shown: log.warning( - "%s closed with %d security notice(s) still queued; recording them as undelivered", + "%s closed with %d security notice(s) still queued, never sent", type(self).__name__, shown, ) - for event in left: - await self._record_undelivered(event, {"reason": "closing"}) + return left + + async def _record_cut(self, left: list[SecurityEvent]) -> None: + """Record the send a cut close stopped waiting for, and each notice it left queued.""" + records: list[tuple[SecurityEvent, str]] = [] + pending, self._sending = self._sending, None + if pending is not None: + event, send, delivered = pending + if not send.done(): + # Its thread runs on to its own timeout, so the notice may still go out: + # "interrupted" says its delivery is unknown. + records.append((event, "interrupted")) + elif (exc := send.exception()) is not None: + # It ended before the cut reached the drain, so its outcome is known. + self._log_send_failed(event, exc) + records.append((event, "send_failed")) + elif send.result(): + delivered() + # "abandoned", apart from "closing": a lock notice refused at notify() reads mailed: false + # on its auth.lock_notice row, while one queued before the close reads mailed: true. + records += [(event, "abandoned") for event in left] + if self._audit is None: + return # nowhere to record them; the queued count is already in the log + failed = 0 + for event, reason in records: + recorded = await self._record_undelivered(event, {"reason": reason}, log_failure=False) + failed += not recorded and event.event_type not in LOG_SILENT_EVENT_TYPES + if failed: + # One line, not one per row: a store closing under a full queue refuses them all. + log.warning( + "%d undelivered security notice(s) could not be recorded in the audit log at close", + failed, + ) async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: + # Shielded, so a cut close can read how the send ended (BACKLOG #6832). Its outcome is + # consumed here, since a cut leaves nobody else to read it. + send = asyncio.ensure_future(asyncio.to_thread(self._send, event)) + send.add_done_callback(_consume_outcome) + self._sending = (event, send, delivered) try: - if await asyncio.to_thread(self._send, event): - delivered() - except asyncio.CancelledError: - # The close was cut while this send waited on the relay (BACKLOG #6832). The send's - # thread runs on to its own timeout, so the notice may still go out: "interrupted" - # says its delivery is unknown, apart from a send that raised. - await self._record_undelivered(event, {"reason": "interrupted"}) - raise - except Exception: - # Best-effort: a failed send must never propagate. The event is usually also in the audit - # log; a refused directory-reconciler audit write leaves no row (BACKLOG #3018). - # A lock notice fails silently here (BACKLOG #1131, LOG_SILENT_EVENT_TYPES): a line per - # failed lock mail would show a logs:view reader when a lock landed. A relay that is down - # still shows, on every other kind of notice. - if event.event_type not in LOG_SILENT_EVENT_TYPES: - log.warning( - "security-event email failed for %s (%s)", - event.username, - event.event_type, - exc_info=True, - ) + sent = await asyncio.shield(send) + except Exception as exc: + self._sending = None + # Best-effort: a failed send must never propagate. + self._log_send_failed(event, exc) # The reason only. The exception's text can quote the relay's reply or the address, and # even its class would tell the recipient, in their own feed, that the relay is broken. - await self._record_undelivered(event, {"reason": "send_failed"}) + # Shielded and held, so a cut close waits for this write rather than cancelling it. + record = asyncio.ensure_future( + self._record_undelivered(event, {"reason": "send_failed"}) + ) + self._recording.add(record) + record.add_done_callback(self._recording.discard) + await asyncio.shield(record) + return + # A cancel leaves self._sending set, for the cut close to record. + self._sending = None + if sent: + delivered() - async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) -> None: + def _log_send_failed(self, event: SecurityEvent, exc: BaseException) -> None: + # The event is usually also in the audit log; a refused directory-reconciler audit write + # leaves no row (BACKLOG #3018). A lock notice fails silently here (BACKLOG #1131, + # LOG_SILENT_EVENT_TYPES): a line per failed lock mail would show a logs:view reader when a + # lock landed. A relay that is down still shows, on every other kind of notice. + if event.event_type not in LOG_SILENT_EVENT_TYPES: + log.warning( + "security-event email failed for %s (%s)", + event.username, + event.event_type, + exc_info=exc, + ) + + async def _record_undelivered( + self, event: SecurityEvent, why: dict[str, str], *, log_failure: bool = True + ) -> bool: """Write the audit row that says this notice never left the engine (BACKLOG #2383). Before this, a full queue or a failed send left only a WARNING line, so the trail could not @@ -885,11 +944,11 @@ async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) - ``why``, plus the holder's username on an issuer's reminder, which says whose credential it was. Never the rest of ``event.detail`` or the address: an EMAIL_CHANGED carries an address in its detail. A lock notice writes the hidden ``auth.lock_notice_undelivered`` action (BACKLOG - #1131). A failed write is swallowed, like the send it reports on. It is logged by class, and - not at all for a lock notice: that kind writes no other line, so a lone line would say a - lock landed.""" + #1131). A failed write is swallowed, like the send it reports on. It is logged by class, + unless ``log_failure`` is False, and never for a lock notice: that kind writes no other + line, so a lone line would say a lock landed. Returns whether the row was written.""" if self._audit is None: - return + return False silent = event.event_type in LOG_SILENT_EVENT_TYPES action = LOCK_NOTICE_UNDELIVERED_ACTION if silent else SECURITY_NOTICE_UNDELIVERED_ACTION detail = {"notice": notice_kind_log_label(event.event_type), **why} @@ -901,11 +960,13 @@ async def _record_undelivered(self, event: SecurityEvent, why: dict[str, str]) - action, actor=event.username, detail=json.dumps(detail, sort_keys=True) ) except Exception as exc: # noqa: BLE001 - best-effort, like the notice itself - if not silent: + if log_failure and not silent: log.warning( "an undelivered security notice could not be recorded in the audit log (%s)", type(exc).__name__, ) + return False + return True def _send(self, event: SecurityEvent) -> bool: """Mail the notice, returning whether it was sent.""" diff --git a/tests/test_lock_notice_off_request_path.py b/tests/test_lock_notice_off_request_path.py index 82fe039ee5..1431b44983 100644 --- a/tests/test_lock_notice_off_request_path.py +++ b/tests/test_lock_notice_off_request_path.py @@ -856,9 +856,10 @@ async def test_after_a_cut_close_a_notice_reported_queued_is_sent( monkeypatch: pytest.MonkeyPatch, ) -> None: """Vault BACKLOG #3120, review round two. The teardown bounds the notifier's close, and a close - cut while a send is under way leaves its stop sentinel on the queue. A drain loop started again - then read that sentinel and stopped, and ``notify`` answered ``True`` for an event nothing ever - sent. Whatever ``start`` does after a cut close, a notice reported queued must be sent. + cut while a send is under way left its stop sentinel on the queue, until BACKLOG #6832 had the + cut close empty it. A drain loop started again then read that sentinel and stopped, and + ``notify`` answered ``True`` for an event nothing ever sent. Whatever ``start`` does after a cut + close, a notice reported queued must be sent. The control is the event taken before the close: its send was under way when the close was cut, and once released it goes out and shows in ``sent``.""" diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index bbacab5c99..f9a59194f5 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -645,7 +645,7 @@ async def test_a_cut_close_records_every_notice_it_left_unsent( ( LOCK_NOTICE_UNDELIVERED_ACTION, "lock-c", - {"notice": "account_locked", "reason": "closing"}, + {"notice": "account_locked", "reason": "abandoned"}, ), ( SECURITY_NOTICE_UNDELIVERED_ACTION, @@ -655,7 +655,7 @@ async def test_a_cut_close_records_every_notice_it_left_unsent( ( SECURITY_NOTICE_UNDELIVERED_ACTION, "ben", - {"notice": "password_changed", "reason": "closing"}, + {"notice": "password_changed", "reason": "abandoned"}, ), ] assert notifier.undelivered == 3 @@ -694,8 +694,91 @@ async def test_a_close_cut_on_a_full_queue_cancels_the_drain( ( SECURITY_NOTICE_UNDELIVERED_ACTION, "ben", - {"notice": "password_changed", "reason": "closing"}, + {"notice": "password_changed", "reason": "abandoned"}, ), ] finally: release.set() + + +async def test_a_cut_during_a_failed_send_s_record_keeps_that_record( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, review round one. A cut landing while the drain writes a failed send's row + must not cancel that write, or the notice leaves no row at all.""" + + def boom(**_: Any) -> None: + raise OSError("relay down") + + monkeypatch.setattr(_SEND, boom) + gate = asyncio.Event() + entered = asyncio.Event() + + class _GatedAudit: + async def record_view( + self, message_id: str, *, actor: str | None = None, now: float | None = None + ) -> None: + raise AssertionError("the notifier never records a view") + + async def record_audit( + self, + action: str, + *, + actor: str | None = None, + channel_id: str | None = None, + detail: str | None = None, + client: str | None = None, + now: float | None = None, + ) -> None: + entered.set() + await gate.wait() + await store.record_audit(action, actor=actor, detail=detail) + + notifier = SecurityEventNotifier( + host="smtp.example.org", + port=25, + sender="mf@example.org", + audit=cast(AuditStore, _GatedAudit()), + ) + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await asyncio.wait_for(entered.wait(), 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + await asyncio.sleep(0.05) + gate.set() + with pytest.raises(asyncio.CancelledError): + await closing + assert await _undelivered(store) == [ + ( + SECURITY_NOTICE_UNDELIVERED_ACTION, + "amy", + {"notice": "password_changed", "reason": "send_failed"}, + ) + ] + + +async def test_a_cut_close_with_no_audit_sink_still_logs_the_queued_count( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6832, review round one. With no sink the queued notices still show in the log, and + the line claims no record.""" + started, release = _blocking_send(monkeypatch) + notifier = SecurityEventNotifier(host="smtp.example.org", port=25, sender="mf@example.org") + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + with pytest.raises(asyncio.CancelledError): + await closing + finally: + release.set() + assert [r.getMessage() for r in caplog.records if "still queued" in r.getMessage()] == [ + "SecurityEventNotifier closed with 1 security notice(s) still queued, never sent" + ] + assert not [r for r in caplog.records if "could not be recorded" in r.getMessage()] From 85968ecad7f6d8bfb273d18a07062223e7b64aad Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:23:36 -0600 Subject: [PATCH 4/9] Security notifier: review round two on the cut-close records aclose takes a timeout, and the API teardown hands it _INNER_SHARE of its step's bound, so the close cuts its own drain and starts recording before the step is cut. A send cancelled with the loop no longer raises out of the record pass; a cut send logs that its delivery is unknown, with or without a sink; a drain that died is logged rather than swallowed; the failed-record count is logged in a finally; _task is reset whatever state the drain is in. SECURITY.md now states the residual as it is: the writes are unbounded and run on beside engine.stop() until the store closes. Comments on start(), the recording set and _MAX_RECORDING are corrected. BACKLOG #6832 Proposed vault banner: FIXED (batch 673, branch b673/notify-aclose). Adjudicated by failing tests: a cut close left queued notices unrecorded, and a cut on a full queue left the drain running. aclose now stops waiting at part of the teardown step's bound, cancels the drain, and records the cut send (reason interrupted) and each queued notice (reason abandoned), with a WARNING count first. Residual, in SECURITY.md: the writes are unbounded, so under a full queue many can still meet the store's close. --- changelog.d/6832.fixed.md | 10 +-- docs/SECURITY.md | 19 ++--- messagefoundry/api/app.py | 6 +- messagefoundry/pipeline/security_notify.py | 82 ++++++++++++++-------- tests/test_security_notice_undelivered.py | 68 ++++++++++++++++-- 5 files changed, 134 insertions(+), 51 deletions(-) diff --git a/changelog.d/6832.fixed.md b/changelog.d/6832.fixed.md index 7dceaf6308..43e40ffd87 100644 --- a/changelog.d/6832.fixed.md +++ b/changelog.d/6832.fixed.md @@ -1,7 +1,7 @@ - **A cut close of the security notifier records the notices it left unsent.** When the shutdown cut `SecurityEventNotifier.aclose` while a send waited on a slow relay, the notices still queued - got no audit row, and on a full queue the drain ran on past the close. The close now cancels its - drain and, before it returns, records the cut send with `reason: interrupted` and each queued - notice with `reason: abandoned`, and logs how many were queued. At shutdown those writes run in - the cut step's short grace, so a write still to run when it ends meets the closed store and is - lost; [SECURITY.md](../docs/SECURITY.md) keeps that as an open residual. (`BACKLOG #6832`) + got no audit row, and on a full queue the drain ran on past the close. The close now stops + waiting for its drain at part of the shutdown step's bound, cancels it, and records the cut send + with `reason: interrupted` and each queued notice with `reason: abandoned`, and logs how many were + queued. The writes are not bounded, so under a full queue many can still be lost to the store's + close; [SECURITY.md](../docs/SECURITY.md) keeps that as an open residual. (`BACKLOG #6832`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c1de58a577..1382afb65c 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7981,14 +7981,17 @@ come before the provision row in the chain, because the notice is sent while the again for the row, and only when a send failed. **Still open, at least:** - At shutdown the notifier closes while the store is still open (BACKLOG #3191), so a send that - fails in its final drain is recorded. That close is one bounded step of the shutdown. When the - step is cut, the close cancels its drain and records the send it cut with `reason: interrupted` - and each notice still queued with `reason: abandoned` (BACKLOG #6832). The cut send's thread - runs on to its own timeout, so that notice may still go out. Those writes run one at a time in - the step's cut grace, so the ones still to run when the grace ends meet the closed store and - are lost; under a full queue that is most of them. A WARNING line counting the queued notices - comes before their writes, and one counting the writes that failed comes after; neither counts - a lock notice. A lock notice among them keeps its `auth.lock_notice` row + fails in its final drain is recorded. That close is one bounded step of the shutdown. The close + stops waiting for its drain at part of that step's bound, or when the step is cut, then cancels + the drain and records the send it cut with `reason: interrupted` and each notice still queued + with `reason: abandoned` (BACKLOG #6832). The cut send's thread runs on to its own timeout, so + that notice may still go out. Those writes run one at a time and are not bounded. The shutdown + stops waiting for them at the step's bound plus its cut grace; the rest go on beside + `engine.stop()`, competing with its writes, until the store closes, and those still to run then + fail. Under a full queue that can be most of them. A WARNING line counting the queued notices + comes before their writes, and one counting the writes that failed comes after; it does not + count the writes a cancel stopped before they ran. Neither line counts a lock notice. A lock + notice among them keeps its `auth.lock_notice` row reading `mailed: true`, so the throttle holds back that account's next lock notice of the kind for the rest of its 24 hours. - A notice that reaches the notifier once it has begun to close is refused and recorded with diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index b4bff70fae..6e3ad0c226 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -1781,7 +1781,11 @@ def _managed_teardown_steps( # #3191). steps.append( _TeardownStep( - "the security notifier's close", 0.25, lambda _b: security_notifier.aclose() + "the security notifier's close", + 0.25, + # Part of the bound, so the close cuts its own drain and starts recording the + # notices it left before the step is cut (BACKLOG #6832). + lambda b: security_notifier.aclose(b * _INNER_SHARE), ) ) # This takes the observers off. An unpinned cluster node's posture inverse is not raised here, diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 0b3e220fcd..aea5960db3 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -75,7 +75,8 @@ #: states the row. Defined here, not in ``auth/notifications.py``, where every upper-case string is a #: notice kind. SECURITY_NOTICE_UNDELIVERED_ACTION: Final = "auth.security_notice_undelivered" -#: How many queue-full records may be in flight at once. Past it a drop goes unrecorded, so the +#: How many records may be in flight at once when a queue-full drop starts one; a failed send's +#: record, held in the same set, takes a slot too. Past it a drop goes unrecorded, so the #: overload that filled the queue cannot also grow tasks and store writers without bound. _MAX_RECORDING: Final = 64 @@ -709,8 +710,8 @@ def __init__( # lifespan passes the store. Of the offline commands, provision-admin passes its store and # admin-reset-totp a sink that reopens the store for the write (BACKLOG #5634). self._audit = audit - # The queue-full records still being written, held so the loop keeps them alive and so - # aclose() can wait for them. + # The records still being written, at least the queue-full ones and a failed send's, held so + # the loop keeps them alive and so aclose() can wait for them. self._recording: set[asyncio.Future[bool]] = set() # The send the drain is waiting on, with what it needs to record or count it, so a cut # close can record it (BACKLOG #6832). None between sends. @@ -808,35 +809,43 @@ def _record_dropped(self, event: SecurityEvent, reason: str) -> None: def start(self) -> None: # Never again once closed (vault BACKLOG #3120). A cut close empties the queue (BACKLOG - # #6832), but one cancelled a second time can still leave its stop sentinel there, so a drain - # loop started again would read it and stop, and + # #6832), but a second aclose() running beside it can still leave its stop sentinel there, + # so a drain loop started again would read it and stop, and # notify() would answer True for events nothing sends. The engine builds a new notifier for # each lifespan rather than restart one. if self._closing: raise RuntimeError(f"{type(self).__name__} has been closed and cannot be started again") super().start() - async def aclose(self) -> None: - """Drain the queue and stop. A close cut short, as the shutdown's bounded step cuts it, - cancels the drain and, before it returns, records the send it cut and each notice still - queued (BACKLOG #6832). In the shutdown those writes run in the cut step's grace, so one - still running when the teardown stops waiting can meet the closed store and is lost like - any failed record write. The count of queued notices is logged before any of them.""" + async def aclose(self, timeout: float | None = None) -> None: + """Drain the queue and stop. A close cut short cancels the drain and, before it returns, + records the send it cut and each notice still queued (BACKLOG #6832). ``timeout`` cuts the + wait for the drain from inside, so the shutdown hands this close part of its step's bound + and the records start before the step itself is cut; a cancel of the caller cuts it the same + way. The writes are not bounded: past the step's bound the shutdown stops waiting for them, + and they go on, beside engine.stop(), until the store closes, which fails the rest. The + count of queued notices is logged before any of them is written.""" self._closing = True # before the sentinel goes in, so nothing is queued behind it drain = self._task try: - await super().aclose() + async with asyncio.timeout(timeout): + await super().aclose() + except TimeoutError: + log.warning( + "%s did not drain within %.2fs; cutting its queue", type(self).__name__, timeout + ) finally: # Taken and logged before any await, so a second cancel cannot leave them untold. left = self._take_queued() try: if drain is not None: - if not drain.done(): - # Cut while the sentinel waited on a full queue: the drain still runs. A - # cut while the close waited on the drain has already cancelled it. - drain.cancel() - self._task = None + # Cut while the sentinel waited on a full queue, the drain still runs; cut while + # the close waited on the drain, it is already cancelled. + drain.cancel() + self._task = None await asyncio.gather(drain, return_exceptions=True) + if not drain.cancelled() and (error := drain.exception()) is not None: + log.error("%s drain loop failed", type(self).__name__, exc_info=error) finally: try: await self._record_cut(left) @@ -845,8 +854,8 @@ async def aclose(self) -> None: await asyncio.gather(*self._recording, return_exceptions=True) def _take_queued(self) -> list[SecurityEvent]: - """Empty the queue, stop sentinel included, and log how many notices it held. Only a cut - close leaves any: an uncut one drained them all.""" + """Empty the queue, stop sentinel included, and log how many notices it held. At least a + cut close, and the close of a notifier never started, leave some.""" left: list[SecurityEvent] = [] while not self._queue.empty(): if (event := self._queue.get_nowait()) is not None: @@ -867,9 +876,15 @@ async def _record_cut(self, left: list[SecurityEvent]) -> None: pending, self._sending = self._sending, None if pending is not None: event, send, delivered = pending - if not send.done(): - # Its thread runs on to its own timeout, so the notice may still go out: + if not send.done() or send.cancelled(): + # A thread runs on to its own timeout, so the notice may still go out: # "interrupted" says its delivery is unknown. + if event.event_type not in LOG_SILENT_EVENT_TYPES: + log.warning( + "%s closed with a security notice's send still running; whether it was " + "delivered is unknown", + type(self).__name__, + ) records.append((event, "interrupted")) elif (exc := send.exception()) is not None: # It ended before the cut reached the drain, so its outcome is known. @@ -881,17 +896,22 @@ async def _record_cut(self, left: list[SecurityEvent]) -> None: # on its auth.lock_notice row, while one queued before the close reads mailed: true. records += [(event, "abandoned") for event in left] if self._audit is None: - return # nowhere to record them; the queued count is already in the log + return # nowhere to record them; the counts are already in the log failed = 0 - for event, reason in records: - recorded = await self._record_undelivered(event, {"reason": reason}, log_failure=False) - failed += not recorded and event.event_type not in LOG_SILENT_EVENT_TYPES - if failed: - # One line, not one per row: a store closing under a full queue refuses them all. - log.warning( - "%d undelivered security notice(s) could not be recorded in the audit log at close", - failed, - ) + try: + for event, reason in records: + recorded = await self._record_undelivered( + event, {"reason": reason}, log_failure=False + ) + failed += not recorded and event.event_type not in LOG_SILENT_EVENT_TYPES + finally: + if failed: + # One line, not one per row: a store closing under a full queue refuses them all. + log.warning( + "%d undelivered security notice(s) could not be recorded in the audit log at " + "close", + failed, + ) async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: # Shielded, so a cut close can read how the send ended (BACKLOG #6832). Its outcome is diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index f9a59194f5..c5d7261871 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -742,12 +742,14 @@ async def record_audit( ) notifier.start() await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) - await asyncio.wait_for(entered.wait(), 5.0) - closing = asyncio.create_task(notifier.aclose()) - await asyncio.sleep(0.05) - closing.cancel() - await asyncio.sleep(0.05) - gate.set() + try: + await asyncio.wait_for(entered.wait(), 5.0) + closing = asyncio.create_task(notifier.aclose()) + await asyncio.sleep(0.05) + closing.cancel() + await asyncio.sleep(0.05) + finally: + gate.set() with pytest.raises(asyncio.CancelledError): await closing assert await _undelivered(store) == [ @@ -782,3 +784,57 @@ async def test_a_cut_close_with_no_audit_sink_still_logs_the_queued_count( "SecurityEventNotifier closed with 1 security notice(s) still queued, never sent" ] assert not [r for r in caplog.records if "could not be recorded" in r.getMessage()] + + +async def test_a_close_timeout_cuts_the_drain_and_records_before_returning( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, review round two. The shutdown hands the close part of its bound, so the + close cuts its own drain and records, then returns without raising.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + drain = notifier._task + assert drain is not None + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + assert drain.done() + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == [ + ("amy", "interrupted"), + ("ben", "abandoned"), + ] + finally: + release.set() + + +@pytest.mark.parametrize( + ("outcome", "rows"), + [("sent", []), ("raised", ["send_failed"]), ("cancelled", ["interrupted"])], +) +async def test_a_send_settled_before_the_cut_reached_the_drain_is_read_as_it_ended( + store: MessageStore, outcome: str, rows: list[str] +) -> None: + """BACKLOG #6832, review rounds one and two. A send can end between the cut and the drain's + resumption: a sent one is no undelivered row, a raised one is send_failed, and a cancelled one + (the loop tearing down) still lets the queued notices be recorded.""" + notifier = _notifier(store) + loop = asyncio.get_running_loop() + send: asyncio.Future[bool] = loop.create_future() + if outcome == "sent": + send.set_result(True) + elif outcome == "raised": + send.set_exception(OSError("relay down")) + else: + send.cancel() + calls: list[int] = [] + amy = SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test") + notifier._sending = (amy, send, lambda: calls.append(1)) + ben = SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test") + await notifier._record_cut([ben]) + assert calls == ([1] if outcome == "sent" else []) + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == sorted( + [("amy", reason) for reason in rows] + [("ben", "abandoned")] + ) From a10e13c5e52c5ba35133ba6a01f501327149b065 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:50:19 -0600 Subject: [PATCH 5/9] Security notifier: must-fix items from the final review round The record pass of a cut close is a held, shielded task, so the teardown's cut stops only the close's wait and the rows go on being written until the store closes; SECURITY.md said so and the code did not. The close's own "did not drain" WARNING is gone: with only a lock notice in flight it would tell a logs:view reader a lock landed (BACKLOG #1131). A TimeoutError not from the close's own deadline is re-raised, and a drain failure is logged only on a cut, where nothing else raises it. SECURITY.md no longer says an interrupted provision-admin run always leaves no row. BACKLOG #6832 Proposed vault banner: FIXED (batch 673, branch b673/notify-aclose). Adjudicated by failing tests: a cut close left queued notices unrecorded, and a cut on a full queue left the drain running. aclose now stops waiting at part of the teardown step's bound, cancels the drain, and records the cut send (reason interrupted) and each queued notice (reason abandoned) in a shielded pass, with a WARNING count first. Residual, in SECURITY.md: the writes are unbounded, so under a full queue many can still meet the store's close. --- docs/SECURITY.md | 3 +- messagefoundry/pipeline/security_notify.py | 31 +++++++----- tests/test_security_notice_undelivered.py | 58 ++++++++++++++++++++++ 3 files changed, 79 insertions(+), 13 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 1382afb65c..e94e631e9b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7972,7 +7972,8 @@ source of record is `SecurityEventNotifier._record_undelivered` in `admin-reset-totp` record it the same way (BACKLOG #5634). `provision-admin` writes it into the store it holds open, so a takeover notice whose `auth.first_administrator_provisioned` row reads `holder_notice: dispatched` and whose send failed gets its own undelivered row too, except in at -least these cases: that write fails, or the run is interrupted mid-send. The command's own result +least these cases: that write fails, or an interrupt ends the run before it lands. An interrupt +mid-send can instead leave a `reason: interrupted` row (BACKLOG #6832). The command's own result says so as well: `holder_notice_send_failed` in `--json`, and a WARNING line in text. Both say the notifier requested to record the notice as undelivered, that is, its send raised, so delivery is unconfirmed; a send can raise after the relay has queued the mail. That row can diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index aea5960db3..46a3a4606a 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -19,7 +19,7 @@ import json import logging from collections.abc import Callable -from typing import Final, Protocol +from typing import Any, Final, Protocol from messagefoundry.auth.audit_visibility import LOCK_NOTICE_UNDELIVERED_ACTION from messagefoundry.auth.notifications import ( @@ -712,7 +712,7 @@ def __init__( self._audit = audit # The records still being written, at least the queue-full ones and a failed send's, held so # the loop keeps them alive and so aclose() can wait for them. - self._recording: set[asyncio.Future[bool]] = set() + self._recording: set[asyncio.Future[Any]] = set() # The send the drain is waiting on, with what it needs to record or count it, so a cut # close can record it (BACKLOG #6832). None between sends. self._sending: tuple[SecurityEvent, asyncio.Future[bool], Callable[[], None]] | None = None @@ -827,13 +827,17 @@ async def aclose(self, timeout: float | None = None) -> None: count of queued notices is logged before any of them is written.""" self._closing = True # before the sentinel goes in, so nothing is queued behind it drain = self._task + deadline = asyncio.timeout(timeout) + cut = True try: - async with asyncio.timeout(timeout): + async with deadline: await super().aclose() + cut = False except TimeoutError: - log.warning( - "%s did not drain within %.2fs; cutting its queue", type(self).__name__, timeout - ) + # No line of its own: what was cut is logged below, without the lock notices a bare + # "cut" line would hint at (BACKLOG #1131). + if not deadline.expired(): + raise finally: # Taken and logged before any await, so a second cancel cannot leave them untold. left = self._take_queued() @@ -844,14 +848,17 @@ async def aclose(self, timeout: float | None = None) -> None: drain.cancel() self._task = None await asyncio.gather(drain, return_exceptions=True) - if not drain.cancelled() and (error := drain.exception()) is not None: + # Uncut, the base close has already raised the drain's failure to the caller. + if cut and not drain.cancelled() and (error := drain.exception()) is not None: log.error("%s drain loop failed", type(self).__name__, exc_info=error) finally: - try: - await self._record_cut(left) - finally: - # Each one swallows its own failure, so this only waits. - await asyncio.gather(*self._recording, return_exceptions=True) + # Held and shielded like a failed send's record, so a cut of this close stops only + # its wait: the writes go on until the store closes. + records = asyncio.ensure_future(self._record_cut(left)) + self._recording.add(records) + records.add_done_callback(self._recording.discard) + # Each one swallows its own failure, so this only waits. + await asyncio.shield(asyncio.gather(*self._recording, return_exceptions=True)) def _take_queued(self) -> list[SecurityEvent]: """Empty the queue, stop sentinel included, and log how many notices it held. At least a diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index c5d7261871..ae3e9c48ea 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -810,6 +810,64 @@ async def test_a_close_timeout_cuts_the_drain_and_records_before_returning( release.set() +async def test_a_cut_of_the_close_while_it_records_stops_only_its_wait( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, final review round. The teardown cuts the step while the close is still + writing its rows; the cut stops the wait, and every row is still written.""" + started, release = _blocking_send(monkeypatch) + gate = asyncio.Event() + entered = asyncio.Event() + + class _GatedAudit: + async def record_view( + self, message_id: str, *, actor: str | None = None, now: float | None = None + ) -> None: + raise AssertionError("the notifier never records a view") + + async def record_audit( + self, + action: str, + *, + actor: str | None = None, + channel_id: str | None = None, + detail: str | None = None, + client: str | None = None, + now: float | None = None, + ) -> None: + entered.set() + await gate.wait() + await store.record_audit(action, actor=actor, detail=detail) + + notifier = SecurityEventNotifier( + host="smtp.example.org", + port=25, + sender="mf@example.org", + audit=cast(AuditStore, _GatedAudit()), + ) + notifier.start() + for name in ("amy", "ben", "cat"): + await notifier.notify( + SecurityEvent(PASSWORD_CHANGED, username=name, email=f"{name}@x.test") + ) + try: + assert await asyncio.to_thread(started.wait, 5.0) + closing = asyncio.create_task(notifier.aclose(0.05)) + await asyncio.wait_for(entered.wait(), 5.0) + closing.cancel() # the step's own cut, mid-record + with pytest.raises(asyncio.CancelledError): + await closing + finally: + gate.set() + release.set() + await asyncio.wait_for(asyncio.gather(*notifier._recording), 5.0) + assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == [ + ("amy", "interrupted"), + ("ben", "abandoned"), + ("cat", "abandoned"), + ] + + @pytest.mark.parametrize( ("outcome", "rows"), [("sent", []), ("raised", ["send_failed"]), ("cancelled", ["interrupted"])], From 3848f55004e6eb528b089bdae96417be65f4c710 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:11:33 -0600 Subject: [PATCH 6/9] Security notifier: drop the in-flight line that could reveal a lock The final unrepaired review found the "send still running" WARNING, skipped for a lock notice, let its absence tell a logs:view reader a lock landed, since a cut with notices queued nearly always has a send in flight (BACKLOG #1131). The line is gone; the row remains. The close's docstring and the alert sink's no longer say every record is written before the close returns, the _MAX_RECORDING comment says "at least", and a drain failure is logged only on a real cut. BACKLOG #6832 --- messagefoundry/pipeline/alert_sinks.py | 3 ++- messagefoundry/pipeline/security_notify.py | 27 +++++++++++----------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/messagefoundry/pipeline/alert_sinks.py b/messagefoundry/pipeline/alert_sinks.py index b9178a6904..87d3ba98d5 100644 --- a/messagefoundry/pipeline/alert_sinks.py +++ b/messagefoundry/pipeline/alert_sinks.py @@ -2611,7 +2611,8 @@ async def aclose(self) -> None: delivery task too and waits for it (BACKLOG #5907), so the startup unwind's cut does not leave the drain running after the store closed; a send that outlives the drain's grace is still left running (:meth:`_cut_sends`). The security notifier's close cancels its drain - too, and then records each notice the cut left unsent in the audit log (BACKLOG #6832), + too, and then starts recording, where it has an audit sink, each notice the cut left + unsent (BACKLOG #6832); a write that meets the closed store is lost, while an undelivered alert is counted by :attr:`undelivered`.""" drain = self._task try: diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 46a3a4606a..3ae17e4258 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -75,8 +75,9 @@ #: states the row. Defined here, not in ``auth/notifications.py``, where every upper-case string is a #: notice kind. SECURITY_NOTICE_UNDELIVERED_ACTION: Final = "auth.security_notice_undelivered" -#: How many records may be in flight at once when a queue-full drop starts one; a failed send's -#: record, held in the same set, takes a slot too. Past it a drop goes unrecorded, so the +#: How many records may be in flight at once when a queue-full drop starts one. Other records +#: held in the same set take slots too, at least a failed send's and a cut close's. Past it a +#: drop goes unrecorded, so the #: overload that filled the queue cannot also grow tasks and store writers without bound. _MAX_RECORDING: Final = 64 @@ -818,8 +819,9 @@ def start(self) -> None: super().start() async def aclose(self, timeout: float | None = None) -> None: - """Drain the queue and stop. A close cut short cancels the drain and, before it returns, - records the send it cut and each notice still queued (BACKLOG #6832). ``timeout`` cuts the + """Drain the queue and stop. A close cut short cancels the drain and starts recording, with a + sink, the send it cut and each notice still queued (BACKLOG #6832). It waits for those + writes unless it is cancelled again, which stops only the wait. ``timeout`` cuts the wait for the drain from inside, so the shutdown hands this close part of its step's bound and the records start before the step itself is cut; a cancel of the caller cuts it the same way. The writes are not bounded: past the step's bound the shutdown stops waiting for them, @@ -828,16 +830,19 @@ async def aclose(self, timeout: float | None = None) -> None: self._closing = True # before the sentinel goes in, so nothing is queued behind it drain = self._task deadline = asyncio.timeout(timeout) - cut = True + cut = False try: async with deadline: await super().aclose() - cut = False except TimeoutError: # No line of its own: what was cut is logged below, without the lock notices a bare # "cut" line would hint at (BACKLOG #1131). if not deadline.expired(): raise + cut = True + except asyncio.CancelledError: + cut = True + raise finally: # Taken and logged before any await, so a second cancel cannot leave them untold. left = self._take_queued() @@ -885,13 +890,9 @@ async def _record_cut(self, left: list[SecurityEvent]) -> None: event, send, delivered = pending if not send.done() or send.cancelled(): # A thread runs on to its own timeout, so the notice may still go out: - # "interrupted" says its delivery is unknown. - if event.event_type not in LOG_SILENT_EVENT_TYPES: - log.warning( - "%s closed with a security notice's send still running; whether it was " - "delivered is unknown", - type(self).__name__, - ) + # "interrupted" says its delivery is unknown. No line for it: a cut that leaves + # notices queued nearly always has a send in flight, so a line skipped for a lock + # notice would say a lock landed (BACKLOG #1131). records.append((event, "interrupted")) elif (exc := send.exception()) is not None: # It ended before the cut reached the drain, so its outcome is known. From 1b2ed30b4da4d5474cb68c21f8ce98817c408fe4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:35:07 -0600 Subject: [PATCH 7/9] SECURITY.md: the undelivered row is attempted, not guaranteed The paragraph said the engine writes the row for a cut close; the residual below it says those writes can fail. It now says the engine tries to write it, and points at the residual. BACKLOG #6832 --- docs/SECURITY.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index e94e631e9b..3345971a02 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7961,7 +7961,8 @@ when the notice is handed to the relay. It reads `mailed: true` only when the re notice: one its full queue dropped, or one it refused because it had begun to close, reads `mailed: false`, so the next lock of the kind mails again (vault BACKLOG #3120). When the relay's queue is full, the relay refuses the notice because it has begun to close, a cut close leaves the notice queued or cuts its send, or the send fails, the -engine writes one more row, with the notice's recipient as the actor. A lock +engine tries to write one more row, with the notice's recipient as the actor; when that write +can fail is under *Still open* below. A lock notice writes `auth.lock_notice_undelivered`, hidden as above. Every other notice kind writes `auth.security_notice_undelivered`, which every `audit:read` reader sees. The detail names the notice kind and the `reason`, at least `queue_full`, `closing`, `abandoned`, `interrupted` or From 53f5acf3318ddf5b8468908afeebee005eca7f1e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:50:49 -0600 Subject: [PATCH 8/9] Security notifier: Manager repair of three regressions from main (a) A second aclose() waits for the first to finish or be cut, and closes nothing itself, so it no longer awaits the drain the first set to None. (b) Each send passes a gate its thread must take before it mails; a cut close skips a send still waiting for a worker thread, so it never mails after the close, and records it as abandoned. (c) A close cut by its own timeout logs a WARNING on every such cut naming the queued count (lock notices left out), standing in for the teardown's cut line. __main__ says "at least an interrupt". BACKLOG #6832 --- messagefoundry/__main__.py | 4 +- messagefoundry/pipeline/security_notify.py | 98 ++++++++++++++++++---- tests/test_security_notice_undelivered.py | 89 +++++++++++++++++++- 3 files changed, 170 insertions(+), 21 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 9bba3cc76b..2c5d8f31d1 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -9653,8 +9653,8 @@ class _CountingNoticeAudit: notifier asked for, so ``provision-admin`` can say that delivery of a notice it reported as dispatched is unconfirmed (BACKLOG #5634). For a dispatched notice the notifier records a send that raised, and, when its close is cut, the send it cut or the notice it left queued (BACKLOG - #6832); only an interrupt cuts this command's close, and it ends the run before the count is - read. So a count above zero says delivery is unconfirmed, whether or not the forwarded write + #6832); at least an interrupt cuts this command's close, and it ends the run before the count + is read. So a count above zero says delivery is unconfirmed, whether or not the forwarded write then succeeded. A send can raise after the relay queued the mail, so it is not proof the notice never left. A count of zero is not a delivery receipt: a send that returned says only that the relay took the mail.""" diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 3ae17e4258..3ec851e87a 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -18,6 +18,7 @@ import asyncio import json import logging +import threading from collections.abc import Callable from typing import Any, Final, Protocol @@ -651,6 +652,33 @@ def _consume_outcome(send: asyncio.Future[bool]) -> None: send.exception() +class _SendGate: + """Whether a send's thread has begun, so a cut close can stop one still waiting for a worker + thread from mailing after the close (BACKLOG #6832). Thread-safe: the send's thread calls + :meth:`begin`, the loop calls :meth:`skip`, and exactly one of them wins.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._started = False + self._skipped = False + + def begin(self) -> bool: + """In the send's thread: whether to send. False once :meth:`skip` won.""" + with self._lock: + if self._skipped: + return False + self._started = True + return True + + def skip(self) -> bool: + """On the loop: whether the send never began, and now never will.""" + with self._lock: + if self._started: + return False + self._skipped = True + return True + + class SecurityEventNotifier(_BackgroundDispatcher[SecurityEvent]): """Emails the affected user about a security event, on a bounded background queue. @@ -716,7 +744,12 @@ def __init__( self._recording: set[asyncio.Future[Any]] = set() # The send the drain is waiting on, with what it needs to record or count it, so a cut # close can record it (BACKLOG #6832). None between sends. - self._sending: tuple[SecurityEvent, asyncio.Future[bool], Callable[[], None]] | None = None + self._sending: ( + tuple[SecurityEvent, asyncio.Future[bool], _SendGate, Callable[[], None]] | None + ) = None + # Set when the first aclose() has finished or been cut, so a second one waits for it rather + # than racing it (BACKLOG #6832). + self._closed = asyncio.Event() # Set when aclose() begins, and never cleared: start() refuses (vault BACKLOG #3120). An event # queued after that sits behind the stop sentinel, or on a queue nothing reads, and is never # sent, so notify() refuses it; the contract on ``SecurityNotifier`` says why. @@ -826,26 +859,34 @@ async def aclose(self, timeout: float | None = None) -> None: and the records start before the step itself is cut; a cancel of the caller cuts it the same way. The writes are not bounded: past the step's bound the shutdown stops waiting for them, and they go on, beside engine.stop(), until the store closes, which fails the rest. The - count of queued notices is logged before any of them is written.""" + count of queued notices is logged before any of them is written. A second call waits for + the first to finish or be cut, and closes nothing itself.""" + if self._closing: + await self._closed.wait() + return self._closing = True # before the sentinel goes in, so nothing is queued behind it + try: + await self._close(timeout) + finally: + self._closed.set() + + async def _close(self, timeout: float | None) -> None: drain = self._task deadline = asyncio.timeout(timeout) - cut = False + cut = timed_out = False try: async with deadline: await super().aclose() except TimeoutError: - # No line of its own: what was cut is logged below, without the lock notices a bare - # "cut" line would hint at (BACKLOG #1131). if not deadline.expired(): raise - cut = True + cut = timed_out = True except asyncio.CancelledError: cut = True raise finally: # Taken and logged before any await, so a second cancel cannot leave them untold. - left = self._take_queued() + left = self._take_queued(timeout if timed_out else None) try: if drain is not None: # Cut while the sentinel waited on a full queue, the drain still runs; cut while @@ -865,16 +906,28 @@ async def aclose(self, timeout: float | None = None) -> None: # Each one swallows its own failure, so this only waits. await asyncio.shield(asyncio.gather(*self._recording, return_exceptions=True)) - def _take_queued(self) -> list[SecurityEvent]: + def _take_queued(self, timed_out: float | None) -> list[SecurityEvent]: """Empty the queue, stop sentinel included, and log how many notices it held. At least a - cut close, and the close of a notifier never started, leave some.""" + cut close, and the close of a notifier never started, leave some. ``timed_out`` is the + timeout that cut the close, if one did.""" left: list[SecurityEvent] = [] while not self._queue.empty(): if (event := self._queue.get_nowait()) is not None: left.append(event) # A count, never one that includes a lock notice (BACKLOG #1131). shown = sum(event.event_type not in LOG_SILENT_EVENT_TYPES for event in left) - if shown: + if timed_out is not None: + # On every timeout cut, whatever kinds were in flight, so neither its presence nor its + # absence says a lock landed. It stands in for the teardown's own cut line, which a + # close cut inside its bound no longer reaches. + log.warning( + "%s did not drain within %.2fs; cut it with %d security notice(s) still queued, " + "never sent", + type(self).__name__, + timed_out, + shown, + ) + elif shown: log.warning( "%s closed with %d security notice(s) still queued, never sent", type(self).__name__, @@ -887,13 +940,15 @@ async def _record_cut(self, left: list[SecurityEvent]) -> None: records: list[tuple[SecurityEvent, str]] = [] pending, self._sending = self._sending, None if pending is not None: - event, send, delivered = pending + event, send, gate, delivered = pending if not send.done() or send.cancelled(): - # A thread runs on to its own timeout, so the notice may still go out: - # "interrupted" says its delivery is unknown. No line for it: a cut that leaves - # notices queued nearly always has a send in flight, so a line skipped for a lock - # notice would say a lock landed (BACKLOG #1131). - records.append((event, "interrupted")) + # A send still waiting for a worker thread is skipped, so it never mails after the + # close: "abandoned", like a queued one. One whose thread began runs on to its own + # timeout, so the notice may still go out: "interrupted" says its delivery is + # unknown. No line for it: a cut that leaves notices queued nearly always has a send + # in flight, so a line skipped for a lock notice would say a lock landed (BACKLOG + # #1131). + records.append((event, "abandoned" if gate.skip() else "interrupted")) elif (exc := send.exception()) is not None: # It ended before the cut reached the drain, so its outcome is known. self._log_send_failed(event, exc) @@ -924,9 +979,10 @@ async def _record_cut(self, left: list[SecurityEvent]) -> None: async def _handle(self, event: SecurityEvent, delivered: Callable[[], None]) -> None: # Shielded, so a cut close can read how the send ended (BACKLOG #6832). Its outcome is # consumed here, since a cut leaves nobody else to read it. - send = asyncio.ensure_future(asyncio.to_thread(self._send, event)) + gate = _SendGate() + send = asyncio.ensure_future(asyncio.to_thread(self._send_gated, event, gate)) send.add_done_callback(_consume_outcome) - self._sending = (event, send, delivered) + self._sending = (event, send, gate, delivered) try: sent = await asyncio.shield(send) except Exception as exc: @@ -996,6 +1052,12 @@ async def _record_undelivered( return False return True + def _send_gated(self, event: SecurityEvent, gate: _SendGate) -> bool: + """Mail the notice unless a cut close skipped it before its thread began.""" + if not gate.begin(): + return False + return self._send(event) + def _send(self, event: SecurityEvent) -> bool: """Mail the notice, returning whether it was sent.""" if not event.email: # narrowed for mypy; notify() already filtered these out diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index ae3e9c48ea..f7a0b1c5fb 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -32,6 +32,7 @@ from messagefoundry.pipeline.security_notify import ( SECURITY_NOTICE_UNDELIVERED_ACTION, SecurityEventNotifier, + _SendGate, ) from messagefoundry.store.base import AuditStore from messagefoundry.store.store import MessageStore @@ -889,10 +890,96 @@ async def test_a_send_settled_before_the_cut_reached_the_drain_is_read_as_it_end send.cancel() calls: list[int] = [] amy = SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test") - notifier._sending = (amy, send, lambda: calls.append(1)) + gate = _SendGate() + assert gate.begin() # its thread began, so a cut cannot skip it + notifier._sending = (amy, send, gate, lambda: calls.append(1)) ben = SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test") await notifier._record_cut([ben]) assert calls == ([1] if outcome == "sent" else []) assert sorted((actor, d["reason"]) for _, actor, d in await _undelivered(store)) == sorted( [("amy", reason) for reason in rows] + [("ben", "abandoned")] ) + + +async def test_a_second_close_beside_a_cut_one_returns_cleanly( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, Manager repair (a). Two closes overlap on a full queue and the first is cut. + The second waits for it and returns, rather than awaiting the drain the first set to None.""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier._queue = asyncio.Queue(maxsize=1) + notifier.start() + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + first = asyncio.create_task(notifier.aclose(0.05)) + second = asyncio.create_task(notifier.aclose()) + await asyncio.wait_for(asyncio.gather(first, second), 5.0) + finally: + release.set() + assert notifier._queue.qsize() == 0 + + +async def test_a_send_still_waiting_for_a_thread_at_the_cut_never_mails( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #6832, Manager repair (b). The executor is busy, so the send waits for a thread when + the close is cut. It must not mail once a thread frees up, and it is recorded as abandoned.""" + import concurrent.futures + + sent: list[list[str]] = [] + monkeypatch.setattr(_SEND, lambda **kw: sent.append(kw["recipients"])) + loop = asyncio.get_running_loop() + executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + real = loop.run_in_executor + + def on_busy_executor(_executor: Any, func: Any, *args: Any) -> Any: + return real(executor, func, *args) + + # Only this loop, only this test: the default executor stays the loop's own. + monkeypatch.setattr(loop, "run_in_executor", on_busy_executor) + busy = threading.Event() + occupied = real(executor, busy.wait, 5.0) + notifier = _notifier(store) + notifier.start() + try: + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="amy", email="amy@x.test")) + await asyncio.sleep(0.05) # the drain is now waiting on the queued send + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + finally: + busy.set() + await occupied + executor.shutdown(wait=True) # the queued work item has had its thread by now + assert sent == [] + assert [(actor, d["reason"]) for _, actor, d in await _undelivered(store)] == [ + ("amy", "abandoned") + ] + + +async def test_a_timeout_cut_logs_a_warning_naming_the_queued_count( + store: MessageStore, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """BACKLOG #6832, Manager repair (c). A close cut by its own timeout ends inside the step's + bound, so the teardown's cut line no longer fires; the close logs one of its own, on every + timeout cut, with a count that leaves lock notices out (BACKLOG #1131).""" + started, release = _blocking_send(monkeypatch) + notifier = _notifier(store) + notifier.start() + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-a", email="a@x.test")) + await notifier.notify(SecurityEvent(PASSWORD_CHANGED, username="ben", email="ben@x.test")) + await notifier.notify(SecurityEvent(ACCOUNT_LOCKED, username="lock-c", email="c@x.test")) + try: + assert await asyncio.to_thread(started.wait, 5.0) + await asyncio.wait_for(notifier.aclose(0.05), 5.0) + finally: + release.set() + lines = [r for r in caplog.records if "did not drain" in r.getMessage()] + assert [(r.levelname, r.getMessage()) for r in lines] == [ + ( + "WARNING", + "SecurityEventNotifier did not drain within 0.05s; cut it with 1 security notice(s) " + "still queued, never sent", + ) + ] From bc3562fea4435927dde2048e43489a4f46ab7b8e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 11:11:48 -0600 Subject: [PATCH 9/9] Security notifier: timeout-cut line at ERROR, scrubbed send-failed line The close's timeout-cut line logs at ERROR, the level of the teardown line it stands in for. The failed-send line passes the username through scrub_log_argument and the kind through notice_kind_log_label, like the closing line (the raw username predates this branch). SECURITY.md and the changelog name the abandoned reason for an unstarted send, and the start() comment no longer rests on a sentinel a close cannot leave. BACKLOG #6832 --- changelog.d/6832.fixed.md | 3 ++- docs/SECURITY.md | 6 ++++-- messagefoundry/pipeline/security_notify.py | 17 ++++++++--------- tests/test_security_notice_undelivered.py | 2 +- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/changelog.d/6832.fixed.md b/changelog.d/6832.fixed.md index 43e40ffd87..e1cdc61baf 100644 --- a/changelog.d/6832.fixed.md +++ b/changelog.d/6832.fixed.md @@ -3,5 +3,6 @@ got no audit row, and on a full queue the drain ran on past the close. The close now stops waiting for its drain at part of the shutdown step's bound, cancels it, and records the cut send with `reason: interrupted` and each queued notice with `reason: abandoned`, and logs how many were - queued. The writes are not bounded, so under a full queue many can still be lost to the store's + queued. A send still waiting for a worker thread at the cut is skipped, never mailed, and + recorded `abandoned`. The writes are not bounded, so under a full queue many can still be lost to the store's close; [SECURITY.md](../docs/SECURITY.md) keeps that as an open residual. (`BACKLOG #6832`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3345971a02..c69cce5c3b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -7986,8 +7986,10 @@ again for the row, and only when a send failed. **Still open, at least:** fails in its final drain is recorded. That close is one bounded step of the shutdown. The close stops waiting for its drain at part of that step's bound, or when the step is cut, then cancels the drain and records the send it cut with `reason: interrupted` and each notice still queued - with `reason: abandoned` (BACKLOG #6832). The cut send's thread runs on to its own timeout, so - that notice may still go out. Those writes run one at a time and are not bounded. The shutdown + with `reason: abandoned` (BACKLOG #6832). A send still waiting for a worker thread at the cut + is skipped, so it never mails, and is recorded `abandoned` too; one that ended just before the + cut is recorded as it ended. A cut send whose thread began runs on to its own timeout, so that + notice may still go out. Those writes run one at a time and are not bounded. The shutdown stops waiting for them at the step's bound plus its cut grace; the rest go on beside `engine.stop()`, competing with its writes, until the store closes, and those still to run then fail. Under a full queue that can be most of them. A WARNING line counting the queued notices diff --git a/messagefoundry/pipeline/security_notify.py b/messagefoundry/pipeline/security_notify.py index 3ec851e87a..7226e834a5 100644 --- a/messagefoundry/pipeline/security_notify.py +++ b/messagefoundry/pipeline/security_notify.py @@ -842,11 +842,10 @@ def _record_dropped(self, event: SecurityEvent, reason: str) -> None: task.add_done_callback(self._recording.discard) def start(self) -> None: - # Never again once closed (vault BACKLOG #3120). A cut close empties the queue (BACKLOG - # #6832), but a second aclose() running beside it can still leave its stop sentinel there, - # so a drain loop started again would read it and stop, and - # notify() would answer True for events nothing sends. The engine builds a new notifier for - # each lifespan rather than restart one. + # Never again once closed (vault BACKLOG #3120). The close has stopped the drain, emptied the + # queue and refuses new events (BACKLOG #6832), so a drain started again would sit on a queue + # nothing fills while notify() answers False. The engine builds a new notifier for each + # lifespan rather than restart one. if self._closing: raise RuntimeError(f"{type(self).__name__} has been closed and cannot be started again") super().start() @@ -919,8 +918,8 @@ def _take_queued(self, timed_out: float | None) -> list[SecurityEvent]: if timed_out is not None: # On every timeout cut, whatever kinds were in flight, so neither its presence nor its # absence says a lock landed. It stands in for the teardown's own cut line, which a - # close cut inside its bound no longer reaches. - log.warning( + # close cut inside its bound no longer reaches, and at that line's level. + log.error( "%s did not drain within %.2fs; cut it with %d security notice(s) still queued, " "never sent", type(self).__name__, @@ -1012,8 +1011,8 @@ def _log_send_failed(self, event: SecurityEvent, exc: BaseException) -> None: if event.event_type not in LOG_SILENT_EVENT_TYPES: log.warning( "security-event email failed for %s (%s)", - event.username, - event.event_type, + scrub_log_argument(event.username), + notice_kind_log_label(event.event_type), exc_info=exc, ) diff --git a/tests/test_security_notice_undelivered.py b/tests/test_security_notice_undelivered.py index f7a0b1c5fb..5566690cb1 100644 --- a/tests/test_security_notice_undelivered.py +++ b/tests/test_security_notice_undelivered.py @@ -978,7 +978,7 @@ async def test_a_timeout_cut_logs_a_warning_naming_the_queued_count( lines = [r for r in caplog.records if "did not drain" in r.getMessage()] assert [(r.levelname, r.getMessage()) for r in lines] == [ ( - "WARNING", + "ERROR", "SecurityEventNotifier did not drain within 0.05s; cut it with 1 security notice(s) " "still queued, never sent", )