Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 3 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
| `scan_interval_seconds` | float | `5.0` | Fallback sweep interval; an enqueue wakes the worker immediately. |
| `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` | 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`). |
| `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]`

Expand Down
6 changes: 5 additions & 1 deletion src/everos/config/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,11 @@ max_pending_per_session = 50
max_pending_total = 200
# One request body (serialised); beyond this the answer is 413.
max_payload_bytes = 4194304
# Fallback sweep interval. Enqueue wakes the worker immediately.
# 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
# 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
Expand Down
12 changes: 8 additions & 4 deletions src/everos/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down
29 changes: 28 additions & 1 deletion src/everos/infra/persistence/sqlite/_repos/memorize_inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
"""

Expand All @@ -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
Expand Down Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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``."""
Expand Down
3 changes: 3 additions & 0 deletions src/everos/infra/persistence/sqlite/stores.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.
Expand Down
4 changes: 4 additions & 0 deletions src/everos/memory/ports/stores.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
23 changes: 19 additions & 4 deletions src/everos/service/memory/_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
purge_expired,
queue_health,
recover_processing,
trim_failed_payloads,
wait_any,
wait_for_wake,
write_status,
Expand Down Expand Up @@ -106,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) ────────────────────────────────

Expand Down Expand Up @@ -287,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 (
Expand Down Expand Up @@ -353,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:
Expand Down Expand Up @@ -408,16 +413,26 @@ 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.

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(
Comment thread
gloryfromca marked this conversation as resolved.
Resolved
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()
14 changes: 14 additions & 0 deletions src/everos/service/memory/_queue_steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"purge_expired",
"queue_health",
"recover_processing",
"trim_failed_payloads",
"wait_any",
"wait_for_wake",
"write_status",
Expand Down Expand Up @@ -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,
*,
Expand Down
3 changes: 3 additions & 0 deletions tests/integration/test_purge_interleavings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""

Expand Down Expand Up @@ -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):
Expand Down
62 changes: 62 additions & 0 deletions tests/unit/test_service/test_memorize_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from __future__ import annotations

import asyncio
import json
from datetime import timedelta
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -826,6 +827,67 @@ 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_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:
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/test_service/test_memorize_queue_stateful.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down