Keep events of committed transactions in multi-step commands

A command may now run several transactions: the upload compensation
commits a removal after the ready commit failed, and a sweep commits
one removal per abandoned intent and ends with a rolled back lookup.
The unit of work cleared every collected event on any rollback, and the
command bus published nothing when the handler raised, so the audit
trail lost discards that had really been committed.

A rollback now drops only the events recorded inside that transaction,
and the bus publishes what was collected even when the handler fails.
Events still come only from committed transactions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-28 22:39:31 +03:00
co-authored by Claude Opus 5.5
parent a41580aceb
commit 70a0c6065e
2 changed files with 8 additions and 6 deletions
@@ -28,11 +28,12 @@ class CommandBus:
handler = self._handlers.get(type(command))
if handler is None:
raise LookupError(f"нет обработчика для команды {type(command).__name__}")
result = await handler(command)
events = self._uow.collect_new_events()
if events:
await self._publisher.publish(events)
return result
try:
return await handler(command)
finally:
events = self._uow.collect_new_events()
if events:
await self._publisher.publish(events)
class EventBus:
@@ -95,11 +95,12 @@ class PostgresUnitOfWork:
self._transaction = connection.transaction()
await self._transaction.start()
self._committed = False
mark = len(self._events)
try:
yield
finally:
if not self._committed:
self._events.clear()
del self._events[mark:]
await self._transaction.rollback()
self.seen.clear()
self._connection = None