Skip to content

Commit e78d84c

Browse files
fix(inbox): roll back a runner handler that returns handler_retry() and complete a skipped row (#63)
A handler passed to InboxConsumerRunner that returned handler_retry() committed its writes and left the inbox row pending and locked, so every redelivery skipped it until release_stale_locks freed the row and the handler ran a second time on top of the first. The runner now treats a returned failure like a raise: the transaction rolls back and the commit follows the handler-exception rule of the ack strategy. handler_skipped() marks the row completed, so a redelivery is a duplicate instead of a row locked forever, and AT_LEAST_ONCE + ON_SUCCESS commits a skip but not a returned failure. Closes #59
1 parent d9ef2f9 commit e78d84c

7 files changed

Lines changed: 282 additions & 33 deletions

File tree

‎docs/agents.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -296,8 +296,8 @@ Commit semantics, exactly as the runner implements them:
296296
|---|---|
297297
| `AT_MOST_ONCE` | before the transaction is even attempted |
298298
| `AT_LEAST_ONCE` + `ON_PERSIST` | after the transaction, success or failure |
299-
| `AT_LEAST_ONCE` + `ON_SUCCESS` | only when the handler returned a result with `processed=True`, or the row was already `completed` |
300-
| `EXACTLY_ONCE_INBOX` | when there is no handler, when the handler succeeded, when it skipped, or when the row was already `completed` — and on a handler exception only if `exactly_once_commit_on_failed=True`. Not when another worker held the row's lock: the handler did not run, so the message is left for redelivery |
299+
| `AT_LEAST_ONCE` + `ON_SUCCESS` | when the handler succeeded or skipped, or the row was already `completed`; not when it raised or returned a failure |
300+
| `EXACTLY_ONCE_INBOX` | when there is no handler, when the handler succeeded, when it skipped, or when the row was already `completed` — and on a handler exception or a returned failure only if `exactly_once_commit_on_failed=True`. Not when another worker held the row's lock: the handler did not run, so the message is left for redelivery |
301301

302302
A message that is not committed — `committed=False`, or `process_one()` raised after reading
303303
it — is rewound: `process_one()` calls `AckHandle.rewind()` before it returns, and the next
@@ -362,6 +362,14 @@ constructors are re-exported at the top level:
362362
| `handler_skipped(status=SKIPPED)` | skipped — not completed, not failed, `attempts_made` untouched |
363363
| `handler_retry(message, *, count_as_attempt=True, next_retry_at=None, status=RETRY)` | failure; `attempts_made + 1` unless you say otherwise |
364364

365+
That table is the batch processors. A handler passed to `InboxConsumerRunner` has no
366+
attempt budget (rule 5), so there `handler_completed()` and `None` complete the row,
367+
`handler_skipped()` completes it as well (the message was handled by deciding not to act on
368+
it, and a redelivery is a duplicate), and `handler_retry(...)` — or any `EventHandlerResult`
369+
with `success=False, processed=True` — is handled exactly like a raise: the handler's writes
370+
and the inbox row roll back together and the commit follows the handler-exception rule of
371+
the `ack_strategy`. `count_as_attempt` and `next_retry_at` have no effect there.
372+
365373
`EventHandlerStatus` is `COMPLETED`, `STALE`, `SKIPPED`, `FAILED`, `RETRY`.
366374

367375
### Routing (`omni_box.core.dispatch`)
@@ -465,7 +473,9 @@ base of the two protocols, not a third implementation. `EventBatchProcessor` set
465473
get `processed=False, duplicate=False, committed=False`. In both cases the runner rewinds
466474
the message, so the next read is that message again rather than the one after it.
467475
5. **The runner never records a failure.** It calls neither `mark_failed` nor anything that
468-
increments `attempts_made`, so `max_attempts` does nothing on that path. The retry budget
476+
increments `attempts_made`, so `max_attempts` does nothing on that path. A handler that
477+
returns `handler_retry(...)` there is rolled back like one that raises, and the retry comes
478+
from the broker. The retry budget
469479
only exists for the batch processors (`create_*_processor`, `EventBatchProcessor`).
470480
6. **`worker_id` is validated** by the PostgreSQL fetch-and-lock path: `[A-Za-z0-9.\-/:]`
471481
only, at most 255 characters. An underscore or a space raises `ValueError` at fetch time,

‎docs/architecture.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ graph TD
8787
`InboxConsumerRunner` supports three strategies:
8888

8989
- **`AT_MOST_ONCE`** — commit the broker offset *before* attempting to persist. Lost messages on crash; never duplicated.
90-
- **`AT_LEAST_ONCE`** — commit after persistence (`ON_PERSIST`) or after a successful handler (`ON_SUCCESS`).
90+
- **`AT_LEAST_ONCE`** — commit after persistence (`ON_PERSIST`) or after a handler that succeeded or skipped (`ON_SUCCESS`).
9191
- **`EXACTLY_ONCE_INBOX`** — commit only after persistence + handler succeed (or when a duplicate is detected). Combined with the inbox unique index on `(message_id, consumer_group)` this yields effectively-once processing.
9292

9393
The `exactly_once_commit_on_failed` flag (default `False`) lets you commit even on handler failure when the message is unrecoverable — useful when you rely on DLQ + maintenance to clean up.

‎docs/user_guide.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,9 @@ finally:
156156

157157
The handler runs inside the transaction that inserts the inbox row, and `repo.session` is that
158158
transaction. Write the side effect through it and the invoice and the inbox row commit
159-
together — or roll back together when the handler raises. A session the handler opens itself
160-
is a second transaction and does not get that.
159+
together — or roll back together when the handler raises or returns `handler_retry(...)`. A
160+
skip (`handler_skipped()`) completes the row like a success. A session the handler opens
161+
itself is a second transaction and does not get that.
161162

162163
### Option B — batch processing already-stored inbox rows
163164

‎omni_box/application/services/consume.py‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
if TYPE_CHECKING:
2929
from ...core.models.entities import InboxEvent
30+
from ...core.protocols import InboxEventRepository
3031
from ...core.protocols.metrics import InboxMetrics
3132
from ...core.protocols.transaction import InboxTransactionProviderProtocol
3233

@@ -48,6 +49,19 @@ class CommitOffsetPolicy(StrEnum):
4849
ON_SUCCESS = "on_success"
4950

5051

52+
class _HandlerRetryRequestedError(Exception):
53+
"""Rolls back the inbox transaction when a runner's handler returns a failure.
54+
55+
The runner has no failure to record (it never calls ``mark_failed``), so a
56+
returned failure is handled as a raised one: the handler's writes and the
57+
inbox row roll back together and the broker redelivers the message.
58+
"""
59+
60+
def __init__(self, result: EventHandlerResult) -> None:
61+
super().__init__(result.error_message or "Handler requested a retry")
62+
self.result = result
63+
64+
5165
@dataclass(frozen=True, slots=True)
5266
class InboxConsumeResult:
5367
"""Result of one inbox consume cycle."""
@@ -137,14 +151,7 @@ async def process_in_transaction(
137151
timeout=self._process_timeout,
138152
)
139153
handler_result = coerce_handler_outcome(raw)
140-
if handler_result.success:
141-
await repo.mark_completed(stored.id, self._worker_id)
142-
logger.info(
143-
"Inbox event processed successfully",
144-
event_id=str(stored.id),
145-
message_id=stored.message_id,
146-
duration_seconds=round(perf_counter() - started_at, 4),
147-
)
154+
await self._settle(repo, stored, handler_result, started_at)
148155
except Exception as exc:
149156
handler_error = exc
150157
raise
@@ -159,6 +166,13 @@ async def process_in_transaction(
159166
event_id=str(event.id),
160167
message_id=event.message_id,
161168
)
169+
elif isinstance(e, _HandlerRetryRequestedError):
170+
logger.warning(
171+
"Inbox handler requested a retry; transaction rolled back",
172+
event_id=str(event.id),
173+
message_id=event.message_id,
174+
reason=str(e),
175+
)
162176
else:
163177
logger.exception(
164178
"Inbox handler failed; transaction rolled back",
@@ -169,6 +183,24 @@ async def process_in_transaction(
169183

170184
return stored, handler_result, handler_error, started_at
171185

186+
async def _settle(
187+
self, repo: InboxEventRepository, stored: InboxEvent, result: EventHandlerResult, started_at: float
188+
) -> None:
189+
"""Complete the row on a success or a skip; on a returned failure, roll the transaction back.
190+
191+
A skip is a decision about the message, so it finishes the row too: a
192+
redelivery is then a duplicate rather than a row left locked.
193+
"""
194+
if result.processed and not result.success:
195+
raise _HandlerRetryRequestedError(result)
196+
await repo.mark_completed(stored.id, self._worker_id)
197+
logger.info(
198+
"Inbox event processed successfully" if result.processed else "Inbox event skipped by its handler",
199+
event_id=str(stored.id),
200+
message_id=stored.message_id,
201+
duration_seconds=round(perf_counter() - started_at, 4),
202+
)
203+
172204

173205
class InboxConsumerRunner:
174206
"""High-level service for consuming broker messages into the Transactional Inbox."""
@@ -401,7 +433,7 @@ def _should_commit_offset(self, handler_result: EventHandlerResult | None, commi
401433
if self._commit_offset_policy == CommitOffsetPolicy.ON_PERSIST:
402434
return True
403435
if self._commit_offset_policy == CommitOffsetPolicy.ON_SUCCESS:
404-
return handler_result is None or handler_result.processed
436+
return handler_result is None or not handler_result.processed or handler_result.success
405437

406438
elif self._ack_strategy == AckStrategy.EXACTLY_ONCE_INBOX:
407439
if not self._processor.has_handler:

‎tests/integration/test_atomicity.py‎

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,15 @@
1010
from sqlalchemy import Column, Integer, MetaData, String, Table, func, insert, select
1111
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
1212

13-
from omni_box import InboxConsumerRunner, InboxEvent, InboxEventRepository
13+
from omni_box import (
14+
AckStrategy,
15+
EventHandlerResult,
16+
InboxConsumerRunner,
17+
InboxEvent,
18+
InboxEventRepository,
19+
handler_retry,
20+
handler_skipped,
21+
)
1422
from omni_box.core.models.entities import OutboxEvent
1523
from omni_box.core.models.enums import EventStatus
1624
from omni_box.core.protocols import ConsumedMessage, NullAckHandle
@@ -287,3 +295,106 @@ async def handler(event: InboxEvent, repo: InboxEventRepository) -> None:
287295
).scalar_one_or_none()
288296
assert business_rows == []
289297
assert inbox_row is None
298+
299+
300+
async def _inbox_row(session_factory: async_sessionmaker[AsyncSession], message_id: str) -> ConcreteInboxEvent | None:
301+
async with session_factory() as session:
302+
return (
303+
await session.execute(select(ConcreteInboxEvent).where(ConcreteInboxEvent.message_id == message_id))
304+
).scalar_one_or_none()
305+
306+
307+
async def _business_rows(session_factory: async_sessionmaker[AsyncSession]) -> list[str]:
308+
async with session_factory() as session:
309+
return [row.data for row in (await session.execute(select(business_table))).all()]
310+
311+
312+
@pytest.mark.integration
313+
@pytest.mark.asyncio
314+
async def test__inbox_runner__handler_returns_retry__rolls_back_and_the_redelivery_runs_it_once_more(
315+
db_engine: AsyncEngine,
316+
) -> None:
317+
# Arrange: the handler writes, then asks for a retry on its first call only
318+
session_factory = async_sessionmaker(db_engine, expire_on_commit=False, class_=AsyncSession)
319+
message = _make_message()
320+
calls: list[int] = []
321+
322+
async def handler(event: InboxEvent, repo: InboxEventRepository) -> EventHandlerResult | None:
323+
assert isinstance(repo, PostgresInboxRepository)
324+
calls.append(1)
325+
await repo.session.execute(insert(business_table).values(id=1, data=event.payload["order_id"]))
326+
if len(calls) == 1:
327+
return handler_retry("downstream not ready")
328+
return None
329+
330+
runner = InboxConsumerRunner(
331+
consumer=OneMessageConsumer(message), # redelivers the uncommitted message, as Kafka does
332+
transaction_provider=SessionPerTransactionProvider(session_factory),
333+
handler=handler,
334+
worker_id="inbox-1",
335+
consumer_group="billing",
336+
ack_strategy=AckStrategy.EXACTLY_ONCE_INBOX,
337+
)
338+
await runner.start()
339+
340+
# Act
341+
try:
342+
first = await runner.process_one()
343+
rows_after_first = await _business_rows(session_factory)
344+
inbox_after_first = await _inbox_row(session_factory, message.message_id)
345+
second = await runner.process_one()
346+
finally:
347+
await runner.stop()
348+
349+
# Assert: the retry left nothing behind, and the redelivery did the work exactly once
350+
assert (first.committed, first.processed) == (False, False)
351+
assert rows_after_first == []
352+
assert inbox_after_first is None
353+
assert (second.committed, second.processed) == (True, True)
354+
assert len(calls) == 2
355+
assert await _business_rows(session_factory) == ["42"]
356+
inbox_row = await _inbox_row(session_factory, message.message_id)
357+
assert inbox_row is not None
358+
assert inbox_row.status == EventStatus.COMPLETED
359+
assert inbox_row.locked_by is None
360+
361+
362+
@pytest.mark.integration
363+
@pytest.mark.asyncio
364+
async def test__inbox_runner__handler_returns_skipped__completes_the_row_and_the_redelivery_is_a_duplicate(
365+
db_engine: AsyncEngine,
366+
) -> None:
367+
# Arrange
368+
session_factory = async_sessionmaker(db_engine, expire_on_commit=False, class_=AsyncSession)
369+
message = _make_message()
370+
calls: list[int] = []
371+
372+
async def handler(event: InboxEvent, repo: InboxEventRepository) -> EventHandlerResult:
373+
calls.append(1)
374+
return handler_skipped()
375+
376+
runner = InboxConsumerRunner(
377+
consumer=OneMessageConsumer(message),
378+
transaction_provider=SessionPerTransactionProvider(session_factory),
379+
handler=handler,
380+
worker_id="inbox-1",
381+
consumer_group="billing",
382+
ack_strategy=AckStrategy.EXACTLY_ONCE_INBOX,
383+
)
384+
await runner.start()
385+
386+
# Act
387+
try:
388+
first = await runner.process_one()
389+
inbox_after_first = await _inbox_row(session_factory, message.message_id)
390+
redelivery = await runner.process_one()
391+
finally:
392+
await runner.stop()
393+
394+
# Assert: the row is finished and unlocked, so retention can delete it and a redelivery is a duplicate
395+
assert (first.committed, first.processed) == (True, False)
396+
assert inbox_after_first is not None
397+
assert inbox_after_first.status == EventStatus.COMPLETED
398+
assert inbox_after_first.locked_by is None
399+
assert (redelivery.duplicate, redelivery.committed) == (True, True)
400+
assert len(calls) == 1

0 commit comments

Comments
 (0)