From 63de4ad8ee7c36ffc41ea81b98f58c56176acdf9 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:11:57 +0800 Subject: [PATCH 1/3] fix(memorize): bound the bodies failed async batches keep A failed memorize_inbox row kept its request body for the whole retention window with no cap, so an outage that failed every async batch held every body accepted during it on disk (up to 4 MiB each). The queue sweep now empties the bodies of failed rows past the newest max_failed_payload_bytes (default 64 MiB); the row, its status and last_error stay. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++++++ docs/api.md | 7 +++-- docs/configuration.md | 3 +- src/everos/config/default.toml | 3 ++ src/everos/config/settings.py | 12 +++++--- .../sqlite/_repos/memorize_inbox.py | 29 ++++++++++++++++++- .../sqlite/_tables/memorize_inbox.py | 3 +- src/everos/infra/persistence/sqlite/stores.py | 3 ++ src/everos/memory/ports/stores.py | 4 +++ src/everos/service/memory/_queue.py | 6 +++- src/everos/service/memory/_queue_steps.py | 14 +++++++++ .../test_repos/test_memorize_inbox.py | 21 ++++++++++++++ .../unit/test_service/test_memorize_queue.py | 26 +++++++++++++++++ 13 files changed, 130 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4efc94569..ea407b6cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,6 +173,16 @@ unchanged apart from additions. See Upgrade below. of the ingest identity, so a store ingested with an earlier config is not reused. +### Fixed + +- **Failed `async_mode` batches no longer keep their bodies without bound.** + A `failed` queue row kept its request body for the seven-day retention, + uncapped, so an outage that failed every batch could hold every body + accepted during it on disk. Now only the newest failed bodies up to + `memorize.async_queue.max_failed_payload_bytes` (default 64 MiB) are kept; + older ones are emptied by the queue's sweep while the row and its + `last_error` stay. + ### Removed - **Foresight.** The `extract_foresight` strategy (off by default since diff --git a/docs/api.md b/docs/api.md index c7bc8f2a6..7fd0bcf0e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -890,9 +890,10 @@ means delivery is slower than arrival. (`row_retention_hours`) after it was created. `GET /tasks/{task_id}` returns `404` after that. A delivered row drops its request body at once. A `failed` row keeps its body (in `memorize_inbox.payload_json`, found by `request_id`) -until purged, and failed rows are not capped: an outage in which every batch -fails keeps every body accepted during it for the retention period. SQLite -reuses the freed pages but does not shrink `system.db`. A row that ages out +for re-sending, but only the newest failed bodies up to +`max_failed_payload_bytes` (64 MiB) in total: an outage in which every batch +fails empties the older bodies within one sweep, and their rows stay with +`last_error`. SQLite reuses the freed pages but does not shrink `system.db`. A row that ages out while still `queued` was never delivered; the purge logs a warning when that happens. diff --git a/docs/configuration.md b/docs/configuration.md index 4ee3e5ba1..fbee5cee8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -508,11 +508,12 @@ joins it only behind its session's backlog) | `max_pending_per_session` | int | `50` | Unfinished batches per session; beyond this `/add` and `/flush` answer `429`. | | `max_pending_total` | int | `200` | Unfinished batches across all sessions; beyond this the answer is `429`. | | `max_payload_bytes` | int | `4194304` | One serialised request body; beyond this the answer is `413`. | +| `max_failed_payload_bytes` | int | `67108864` | Request bodies kept on `failed` rows (for re-sending), newest first; older failed rows past this total (64 MiB) lose their body within one sweep, the row and its error stay. `0` keeps none. | | `scan_interval_seconds` | float | `5.0` | Fallback sweep interval; an enqueue wakes the worker immediately. | | `max_attempts` | int | `1` | Delivery attempts per batch before it is marked `failed` and skipped. Keep `1` unless duplicate memcells after a partial failure are acceptable: the pipeline is not atomic. | | `retry_backoff_seconds` | float | `2.0` | Pause between attempts. | | `max_replays` | int | `3` | A batch in flight when the process died is replayed on the next start; after this many replays without finishing it is marked `failed` (`error_code: replays_exhausted`). | -| `row_retention_hours` | float | `168.0` | Rows of any status are deleted this long after creation (seven days), including rows never delivered; the purge logs a warning for those. Delivered rows drop their request body at once, `failed` rows keep it. | +| `row_retention_hours` | float | `168.0` | Rows of any status are deleted this long after creation (seven days), including rows never delivered; the purge logs a warning for those. Delivered rows drop their request body at once, `failed` rows keep it within `max_failed_payload_bytes`. | ### `[memorize.input_log]` diff --git a/src/everos/config/default.toml b/src/everos/config/default.toml index 6706d539a..993eaa223 100644 --- a/src/everos/config/default.toml +++ b/src/everos/config/default.toml @@ -275,6 +275,9 @@ max_pending_per_session = 50 max_pending_total = 200 # One request body (serialised); beyond this the answer is 413. max_payload_bytes = 4194304 +# Request bodies kept on failed rows (for re-sending), newest first; older +# failed rows past this total lose their body, the row itself stays. 0 keeps none. +max_failed_payload_bytes = 67108864 # Fallback sweep interval. Enqueue wakes the worker immediately. scan_interval_seconds = 5.0 # Delivery attempts per row before it is marked failed and skipped. Keep 1 diff --git a/src/everos/config/settings.py b/src/everos/config/settings.py index 0be5b2afa..a3a81faff 100644 --- a/src/everos/config/settings.py +++ b/src/everos/config/settings.py @@ -743,10 +743,12 @@ class AsyncQueueSettings(BaseModel): over ``max_pending_per_session`` or a process over ``max_pending_total`` rejects new rows with 429, and a body over ``max_payload_bytes`` with 413. A delivered row drops its body at once, so pending and delivered rows - stay around ``max_pending_total * max_payload_bytes``; failed rows keep - their bodies for the retention period and are not capped, and SQLite does - not shrink the file after a purge. The caps are checked without a lock, - so concurrent requests overshoot a little. + stay around ``max_pending_total * max_payload_bytes``. A failed row keeps + its body for re-sending, but only the newest failed bodies up to + ``max_failed_payload_bytes`` in total; older ones are emptied (the row and + its ``last_error`` stay). SQLite does not shrink the file after a purge. + The caps are checked without a lock, so concurrent requests overshoot a + little. A row that fails ``max_attempts`` times (``retry_backoff_seconds`` apart) is marked ``failed`` and skipped so one bad batch cannot hold @@ -768,6 +770,7 @@ class AsyncQueueSettings(BaseModel): EVEROS_MEMORIZE__ASYNC_QUEUE__MAX_PENDING_PER_SESSION EVEROS_MEMORIZE__ASYNC_QUEUE__MAX_PENDING_TOTAL EVEROS_MEMORIZE__ASYNC_QUEUE__MAX_PAYLOAD_BYTES + EVEROS_MEMORIZE__ASYNC_QUEUE__MAX_FAILED_PAYLOAD_BYTES EVEROS_MEMORIZE__ASYNC_QUEUE__SCAN_INTERVAL_SECONDS EVEROS_MEMORIZE__ASYNC_QUEUE__MAX_ATTEMPTS EVEROS_MEMORIZE__ASYNC_QUEUE__RETRY_BACKOFF_SECONDS @@ -780,6 +783,7 @@ class AsyncQueueSettings(BaseModel): max_pending_per_session: int = Field(default=50, ge=1) max_pending_total: int = Field(default=200, ge=1) max_payload_bytes: int = Field(default=4 * 1024 * 1024, ge=1) + max_failed_payload_bytes: int = Field(default=64 * 1024 * 1024, ge=0) scan_interval_seconds: float = Field(default=5.0, gt=0) max_attempts: int = Field(default=1, ge=1) retry_backoff_seconds: float = Field(default=2.0, ge=0) diff --git a/src/everos/infra/persistence/sqlite/_repos/memorize_inbox.py b/src/everos/infra/persistence/sqlite/_repos/memorize_inbox.py index 34e62fe36..0478c223a 100644 --- a/src/everos/infra/persistence/sqlite/_repos/memorize_inbox.py +++ b/src/everos/infra/persistence/sqlite/_repos/memorize_inbox.py @@ -11,6 +11,7 @@ - :meth:`requeue_processing` — startup crash recovery. - :meth:`fail_abandoned` — the stuck-row sweep. - :meth:`purge_expired` — retention sweep. +- :meth:`trim_failed_payloads` — bound the bodies failed rows keep. - :meth:`list_tasks` — ``GET /tasks`` (filter by session / status, paged). """ @@ -19,7 +20,7 @@ import datetime as dt from collections.abc import Collection -from sqlalchemy import delete, func, select, update +from sqlalchemy import LargeBinary, cast, delete, func, select, update from everos.infra.persistence.sqlite._base.repository import RepoBase from everos.infra.persistence.sqlite._base.session import session_scope @@ -249,3 +250,29 @@ async def purge_expired(self, *, before: dt.datetime) -> tuple[int, int]: await s.commit() queued = int(undelivered.rowcount or 0) return queued + int(terminal.rowcount or 0), queued + + async def trim_failed_payloads(self, *, max_bytes: int) -> int: + """Empty the bodies of ``failed`` rows past the newest ``max_bytes``. + + Newest by ``id``; sizes are UTF-8 bytes. The row, its status and + ``last_error`` stay. Returns how many bodies were emptied. + """ + size = func.length(cast(MemorizeInbox.payload_json, LargeBinary)) + newest_first = MemorizeInbox.id.desc() # type: ignore[union-attr] + kept = ( + select( + MemorizeInbox.id, + func.sum(size).over(order_by=newest_first).label("running"), + ) + .where(MemorizeInbox.status == "failed", MemorizeInbox.payload_json != "") + .subquery() + ) + over_budget = select(kept.c.id).where(kept.c.running > max_bytes) + async with session_scope(self._factory) as s: + result = await s.execute( + update(MemorizeInbox) + .where(MemorizeInbox.id.in_(over_budget)) # type: ignore[union-attr] + .values(payload_json="") + ) + await s.commit() + return int(result.rowcount or 0) diff --git a/src/everos/infra/persistence/sqlite/_tables/memorize_inbox.py b/src/everos/infra/persistence/sqlite/_tables/memorize_inbox.py index ac8fcca81..f9787adf8 100644 --- a/src/everos/infra/persistence/sqlite/_tables/memorize_inbox.py +++ b/src/everos/infra/persistence/sqlite/_tables/memorize_inbox.py @@ -48,7 +48,8 @@ class MemorizeInbox(BaseTable, table=True): defer_extraction: bool = False payload_json: str """The request body as ``memorize()`` expects it, serialised verbatim. - Emptied once the row is delivered; a ``failed`` row keeps it.""" + Emptied once the row is delivered; a ``failed`` row keeps it while it is + among the newest ``max_failed_payload_bytes`` of failed bodies.""" message_count: int = 0 status: str = Field(default="queued") """``queued`` | ``processing`` | ``success`` | ``failed``.""" diff --git a/src/everos/infra/persistence/sqlite/stores.py b/src/everos/infra/persistence/sqlite/stores.py index 035f24d16..8a1e50525 100644 --- a/src/everos/infra/persistence/sqlite/stores.py +++ b/src/everos/infra/persistence/sqlite/stores.py @@ -416,6 +416,9 @@ async def get_task(self, request_id: str) -> MemorizeTask | None: async def purge_expired(self, *, before: dt.datetime) -> tuple[int, int]: return await self._repo.purge_expired(before=before) + async def trim_failed_payloads(self, *, max_bytes: int) -> int: + return await self._repo.trim_failed_payloads(max_bytes=max_bytes) + class SqliteReflectionReportStore: """Reflection audit trail over ``reflection_report``. diff --git a/src/everos/memory/ports/stores.py b/src/everos/memory/ports/stores.py index b6e33c893..79ebb5ca7 100644 --- a/src/everos/memory/ports/stores.py +++ b/src/everos/memory/ports/stores.py @@ -544,6 +544,10 @@ async def purge_expired(self, *, before: dt.datetime) -> tuple[int, int]: """Delete finished and stale tasks; return ``(deleted, never_delivered)``.""" ... + async def trim_failed_payloads(self, *, max_bytes: int) -> int: + """Empty failed tasks' bodies past the newest ``max_bytes``; return how many.""" + ... + @runtime_checkable class ReflectionReportStore(Protocol): diff --git a/src/everos/service/memory/_queue.py b/src/everos/service/memory/_queue.py index 9abd5f584..bc4054e97 100644 --- a/src/everos/service/memory/_queue.py +++ b/src/everos/service/memory/_queue.py @@ -48,6 +48,7 @@ purge_expired, queue_health, recover_processing, + trim_failed_payloads, wait_any, wait_for_wake, write_status, @@ -408,7 +409,7 @@ async def _reap_lost(self) -> None: self._status_write_lost = True async def _sweep(self) -> None: - """Expire old rows; fail ``processing`` rows nobody is working on. + """Expire old rows; bound failed bodies; fail orphaned ``processing`` rows. The scheduler knows the rows it has in flight, so any other ``processing`` row lost its status write. The outcome is unknown (the @@ -418,6 +419,9 @@ async def _sweep(self) -> None: """ before = get_utc_now() - dt.timedelta(hours=self._cfg.row_retention_hours) await purge_expired(self._inbox, before=before) + await trim_failed_payloads( + self._inbox, max_bytes=self._cfg.max_failed_payload_bytes + ) # ponytail: in-process bookkeeping; a lease column if workers ever run # in more than one process. await self._reap_lost() diff --git a/src/everos/service/memory/_queue_steps.py b/src/everos/service/memory/_queue_steps.py index 6b65118f3..3346070e4 100644 --- a/src/everos/service/memory/_queue_steps.py +++ b/src/everos/service/memory/_queue_steps.py @@ -17,6 +17,7 @@ "purge_expired", "queue_health", "recover_processing", + "trim_failed_payloads", "wait_any", "wait_for_wake", "write_status", @@ -142,6 +143,19 @@ async def purge_expired(inbox: MemorizeInboxStore, *, before: dt.datetime) -> No logger.info("memorize_queue_purged", count=deleted) +async def trim_failed_payloads(inbox: MemorizeInboxStore, *, max_bytes: int) -> None: + """Bound the bodies failed rows keep to ``max_bytes``; log, never raise.""" + try: + emptied = await inbox.trim_failed_payloads(max_bytes=max_bytes) + except Exception: + logger.exception("memorize_queue_trim_failed") + return + if emptied: + logger.warning( + "memorize_queue_failed_bodies_dropped", count=emptied, max_bytes=max_bytes + ) + + async def queue_health( inbox: MemorizeInboxStore, *, diff --git a/tests/unit/test_infra/test_sqlite/test_repos/test_memorize_inbox.py b/tests/unit/test_infra/test_sqlite/test_repos/test_memorize_inbox.py index 12dad7350..974a3d1f2 100644 --- a/tests/unit/test_infra/test_sqlite/test_repos/test_memorize_inbox.py +++ b/tests/unit/test_infra/test_sqlite/test_repos/test_memorize_inbox.py @@ -10,6 +10,8 @@ rows to ``queued`` at startup. - **Nothing lives forever**: ``purge_expired`` deletes rows older than the retention window regardless of status, except rows still ``processing``. +- **Failed bodies are bounded**: ``trim_failed_payloads`` keeps the newest + failed bodies within a byte budget and empties the older ones. - **request_id is unique**: one HTTP request maps to at most one row. """ @@ -159,6 +161,25 @@ async def test_purge_expired_deletes_old_rows_except_processing( assert remaining == {kept_processing.id, kept_fresh.id} +async def test_trim_failed_payloads_keeps_the_newest_within_the_budget( + repo: MemorizeInboxRepo, +) -> None: + body = "记" * 10 # 30 UTF-8 bytes, 10 characters + oldest = await repo.add(_row(status="failed", payload_json=body)) + middle = await repo.add(_row(status="failed", payload_json=body)) + newest = await repo.add(_row(status="failed", payload_json=body)) + queued = await repo.add(_row(status="queued", payload_json=body)) + + assert await repo.trim_failed_payloads(max_bytes=60) == 1 + + bodies = {r.id: r.payload_json for r in await repo.list_all()} + assert bodies == {oldest.id: "", middle.id: body, newest.id: body, queued.id: body} + # A second pass finds nothing over the budget; 0 keeps no failed body. + assert await repo.trim_failed_payloads(max_bytes=60) == 0 + assert await repo.trim_failed_payloads(max_bytes=0) == 2 + assert {r.id: r.status for r in await repo.list_all()}[oldest.id] == "failed" + + async def test_request_id_is_unique(repo: MemorizeInboxRepo) -> None: await repo.add(_row(request_id="dup")) with pytest.raises(IntegrityError): diff --git a/tests/unit/test_service/test_memorize_queue.py b/tests/unit/test_service/test_memorize_queue.py index 1e116cc06..5cf3e61d8 100644 --- a/tests/unit/test_service/test_memorize_queue.py +++ b/tests/unit/test_service/test_memorize_queue.py @@ -22,6 +22,7 @@ from __future__ import annotations import asyncio +import json from datetime import timedelta from pathlib import Path from typing import Any @@ -826,6 +827,31 @@ async def spy_mark(row_id: int, **values: Any) -> None: assert row is not None and row.payload_json != "" +async def test_sweep_keeps_only_the_newest_failed_bodies_within_budget( + repo: MemorizeInboxRepo, +) -> None: + """An outage that fails every batch must not hold every body for a week.""" + _wiring["deliver"] = _FakeMemorize(failing={"bad1", "bad2"}) + one_body = len(json.dumps(_payload("bad1"), ensure_ascii=False).encode()) + w = _worker(_settings(max_failed_payload_bytes=one_body)) + for n in (1, 2): + await w.enqueue( + _payload(f"bad{n}"), + request_id=f"r{n}", + is_final=False, + defer_extraction=False, + ) + await w.drain_once() + + await w._sweep() + + old = await repo.find_one(request_id="r1") + new = await repo.find_one(request_id="r2") + assert old is not None and (old.status, old.payload_json) == ("failed", "") + assert old.last_error == "RuntimeError: boom" + assert new is not None and json.loads(new.payload_json) == _payload("bad2") + + async def test_lost_status_write_is_reaped_before_the_next_row( repo: MemorizeInboxRepo, fake: _FakeMemorize, monkeypatch: pytest.MonkeyPatch ) -> None: From 086dd11d36bf62bddb5c8bac201a3c526651f569 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:51:25 +0800 Subject: [PATCH 2/3] fix(memorize): sweep the async queue while a drain stays busy The sweep (retention purge, failed-body trim) ran only before a drain, and a drain returns only once nothing is queued or in flight. Under an outage with steady traffic every failed row is replaced before the drain empties, so failed bodies grew past max_failed_payload_bytes. The drain now sweeps before each claim once scan_interval_seconds has passed since the last sweep; the loop no longer sweeps on every wake. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 +++++----- docs/configuration.md | 2 +- src/everos/config/default.toml | 3 +- src/everos/service/memory/_queue.py | 17 +++++++-- .../unit/test_service/test_memorize_queue.py | 36 +++++++++++++++++++ .../test_memorize_queue_stateful.py | 4 +++ 6 files changed, 66 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea407b6cd..8f7d864d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 replaced by `message_ids`. Buffered messages from an earlier version keep their old ids; a batch sent before the upgrade and resent after it is not recognized as a resend. +- **Failed `async_mode` batches no longer keep their bodies without bound.** + A `failed` queue row kept its request body for the seven-day retention, + uncapped, so an outage that failed every batch could hold every body + accepted during it on disk. Now only the newest failed bodies up to + `memorize.async_queue.max_failed_payload_bytes` (default 64 MiB) are kept; + older ones are emptied by the queue's sweep while the row and its + `last_error` stay. The sweep (this trim and the retention purge) now runs + every `scan_interval_seconds` while the worker is busy too, not only + between drains. ## [1.7.1] - 2026-11-20 @@ -173,16 +182,6 @@ unchanged apart from additions. See Upgrade below. of the ingest identity, so a store ingested with an earlier config is not reused. -### Fixed - -- **Failed `async_mode` batches no longer keep their bodies without bound.** - A `failed` queue row kept its request body for the seven-day retention, - uncapped, so an outage that failed every batch could hold every body - accepted during it on disk. Now only the newest failed bodies up to - `memorize.async_queue.max_failed_payload_bytes` (default 64 MiB) are kept; - older ones are emptied by the queue's sweep while the row and its - `last_error` stay. - ### Removed - **Foresight.** The `extract_foresight` strategy (off by default since diff --git a/docs/configuration.md b/docs/configuration.md index fbee5cee8..851790a62 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -509,7 +509,7 @@ joins it only behind its session's backlog) | `max_pending_total` | int | `200` | Unfinished batches across all sessions; beyond this the answer is `429`. | | `max_payload_bytes` | int | `4194304` | One serialised request body; beyond this the answer is `413`. | | `max_failed_payload_bytes` | int | `67108864` | Request bodies kept on `failed` rows (for re-sending), newest first; older failed rows past this total (64 MiB) lose their body within one sweep, the row and its error stay. `0` keeps none. | -| `scan_interval_seconds` | float | `5.0` | Fallback sweep interval; an enqueue wakes the worker immediately. | +| `scan_interval_seconds` | float | `5.0` | Sweep interval (retention purge, failed-body trim), busy or idle; an enqueue wakes the worker immediately. | | `max_attempts` | int | `1` | Delivery attempts per batch before it is marked `failed` and skipped. Keep `1` unless duplicate memcells after a partial failure are acceptable: the pipeline is not atomic. | | `retry_backoff_seconds` | float | `2.0` | Pause between attempts. | | `max_replays` | int | `3` | A batch in flight when the process died is replayed on the next start; after this many replays without finishing it is marked `failed` (`error_code: replays_exhausted`). | diff --git a/src/everos/config/default.toml b/src/everos/config/default.toml index 993eaa223..1aa112701 100644 --- a/src/everos/config/default.toml +++ b/src/everos/config/default.toml @@ -278,7 +278,8 @@ max_payload_bytes = 4194304 # Request bodies kept on failed rows (for re-sending), newest first; older # failed rows past this total lose their body, the row itself stays. 0 keeps none. max_failed_payload_bytes = 67108864 -# Fallback sweep interval. Enqueue wakes the worker immediately. +# Sweep interval (retention purge, failed-body trim), busy or idle. Enqueue +# wakes the worker immediately. scan_interval_seconds = 5.0 # Delivery attempts per row before it is marked failed and skipped. Keep 1 # unless duplicate memcells after a partial failure are acceptable: the diff --git a/src/everos/service/memory/_queue.py b/src/everos/service/memory/_queue.py index bc4054e97..f60ad3e2c 100644 --- a/src/everos/service/memory/_queue.py +++ b/src/everos/service/memory/_queue.py @@ -107,6 +107,7 @@ def __init__( # which is what lets the sweep tell a lost status write from a row # that is simply still running. self._in_flight: dict[int, tuple[MemorizeTask, asyncio.Task[None]]] = {} + self._next_sweep_at = get_utc_now() # ── producer side (called by the route) ──────────────────────────────── @@ -288,6 +289,10 @@ async def drain_once(self) -> int: started = 0 try: while True: + # Between deliveries too: a drain kept busy by new rows (an + # outage under steady traffic) must not starve housekeeping. + if get_utc_now() >= self._next_sweep_at: + await self._sweep() if self._status_write_lost: await self._reap_lost() # before the next claim, not after while ( @@ -354,8 +359,7 @@ async def _run(self) -> None: # sweep that also catches rows left behind by a missed wake. await wait_for_wake(self._wake, timeout=self._cfg.scan_interval_seconds) try: - await self._sweep() - await self.drain_once() + await self.drain_once() # sweeps first when one is due except asyncio.CancelledError: raise except Exception: @@ -411,13 +415,20 @@ async def _reap_lost(self) -> None: async def _sweep(self) -> None: """Expire old rows; bound failed bodies; fail orphaned ``processing`` rows. + Runs at start and then at most once per ``scan_interval_seconds``, + checked before each claim of :meth:`drain_once`, busy or idle. + The scheduler knows the rows it has in flight, so any other ``processing`` row lost its status write. The outcome is unknown (the lost write is usually the ``success`` one), so the row is marked ``failed`` rather than replayed. Housekeeping must never stop delivery: each step logs and moves on. """ - before = get_utc_now() - dt.timedelta(hours=self._cfg.row_retention_hours) + now = get_utc_now() + self._next_sweep_at = now + dt.timedelta( + seconds=self._cfg.scan_interval_seconds + ) + before = now - dt.timedelta(hours=self._cfg.row_retention_hours) await purge_expired(self._inbox, before=before) await trim_failed_payloads( self._inbox, max_bytes=self._cfg.max_failed_payload_bytes diff --git a/tests/unit/test_service/test_memorize_queue.py b/tests/unit/test_service/test_memorize_queue.py index 5cf3e61d8..d0629abd6 100644 --- a/tests/unit/test_service/test_memorize_queue.py +++ b/tests/unit/test_service/test_memorize_queue.py @@ -852,6 +852,42 @@ async def test_sweep_keeps_only_the_newest_failed_bodies_within_budget( assert new is not None and json.loads(new.payload_json) == _payload("bad2") +async def test_a_drain_that_never_empties_still_bounds_failed_bodies( + repo: MemorizeInboxRepo, +) -> None: + """Steady traffic during an outage keeps the drain busy; trimming must not wait.""" + one_body = len(json.dumps(_payload("bad"), ensure_ascii=False).encode()) + w = _worker( + _settings(max_failed_payload_bytes=one_body, scan_interval_seconds=0.01) + ) + calls = 0 + kept: list[int] = [] # failed rows still holding a body, seen mid-drain + + async def fail_and_replace(payload: dict[str, Any], **_: Any) -> object: + nonlocal calls + calls += 1 + await asyncio.sleep(0.02) # longer than the scan interval + rows = await repo.list_all() + kept.append(sum(1 for r in rows if r.status == "failed" and r.payload_json)) + if calls < 20: # each failure is replaced before the drain could empty + await w.enqueue( + _payload("bad"), + request_id=f"r{calls + 1}", + is_final=False, + defer_extraction=False, + ) + raise RuntimeError("boom") + + _wiring["deliver"] = fail_and_replace + await w.enqueue( + _payload("bad"), request_id="r1", is_final=False, defer_extraction=False + ) + await w.drain_once() + + assert calls == 20 + assert max(kept) <= 2, kept + + async def test_lost_status_write_is_reaped_before_the_next_row( repo: MemorizeInboxRepo, fake: _FakeMemorize, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unit/test_service/test_memorize_queue_stateful.py b/tests/unit/test_service/test_memorize_queue_stateful.py index 7c85b3838..887a7400a 100644 --- a/tests/unit/test_service/test_memorize_queue_stateful.py +++ b/tests/unit/test_service/test_memorize_queue_stateful.py @@ -446,6 +446,10 @@ def drain( die_after_loss: bool, ) -> None: """One ``drain_once``: rows deliver in id order with these outcomes.""" + if self.q.now() >= self.q.worker._next_sweep_at: + # A due sweep runs before the drain's first claim. + self._model_purge() + event("drain: swept first") queued = sorted( (m["row_id"], rid) for rid, m in self.model.items() From 3c0b5b7be6c6fc5a45d50f640389b0ec962a8461 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:04:16 +0800 Subject: [PATCH 3/3] test(purge): a crashed process delivers nothing until it restarts claim_and_crash left a row processing as if the process had died in it, then let the same process keep draining. drain_once now runs the queue sweep itself, which fails processing rows this scheduler is not running, so the row was failed instead of replayed. Production never drains in that state: start() requeues processing rows before the first drain, and the loop already swept before every drain. The rule now marks the crash like crash_mid_event does, and deliver_one waits for the restart. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_purge_interleavings.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/integration/test_purge_interleavings.py b/tests/integration/test_purge_interleavings.py index b0f217cc4..066417991 100644 --- a/tests/integration/test_purge_interleavings.py +++ b/tests/integration/test_purge_interleavings.py @@ -306,11 +306,14 @@ async def go() -> None: @rule() def deliver_one(self) -> None: + if self.crashed: # a dead process delivers nothing until the restart + return self.run(self.queue.drain_once()) @rule() def claim_and_crash(self) -> None: """A row claimed and left ``processing`` (the process died in it).""" + self.crashed = True self.run(self.queue._inbox.claim_next()) @rule()