Outbox Ring Migration (+ Connection-Helper Consolidation)

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Split repositories/outbox.py (1,080 lines) into a pure ports/outbox.py and three driver-specific adapters, consolidate the two identical SQL connection helpers onto adapters/_sql/connection.py::sql_connection, and delete the src/eventsource/repositories/ package. After this slice the string eventsource.repositories does not appear in any executable file in the repository, and eventsource.ports.outbox imports without sqlalchemy.

Architecture: OutboxEntry, OutboxStats, the OutboxRepository Protocol, and a new shared outbox_event_data() payload builder move to ports/outbox.py (Tier 0). The three implementations move to adapters/memory/outbox.py, adapters/postgresql/outbox.py, and adapters/sqlite/outbox.py โ€” split by driver, not dialect-parameterized like adapters/sql/{checkpoints,dlq}.py, because the SQLite outbox takes a raw aiosqlite.Connection where the PostgreSQL one takes a sqlalchemy AsyncConnection | AsyncEngine. outbox_event_data() becomes the single authority for the six-key payload that adapters/postgresql/store.py::_write_to_outbox writes and the outbox repositories read. repositories/_connection.py dies; its five non-outbox consumers retarget onto sql_connection.

Tech Stack: Python 3.13, pydantic v2, sqlalchemy 2 (adapters only), asyncpg, aiosqlite, pytest + pytest-asyncio + hypothesis, mypy strict, ruff, import-linter, mutmut.

Spec: docs/superpowers/specs/2026-07-31-outbox-ring-design.md (in full)

Predecessor: the four legacy-store-retirement slices have ALL LANDED. Verified against the tree at HEAD: src/eventsource/stores/ is gone, adapters/postgresql/store.py already carries outbox_enabled and _write_to_outbox (slice (d) Task 1), SQLITE_AVAILABLE already comes from adapters.sqlite rather than from the outbox try/except, and ADR 0025 is Accepted. Do not redo any of it.

Global Constraints

`` Co-Authored-By: Claude Fable 5 ``

Why the split, the deletion, and the public-API swap are one task

Task 3 is large and cannot be subdivided. Three constraints interlock:

  1. The port cannot precede the deletion. OutboxEntry and OutboxStats are dataclasses, and dataclass identity is nominal: if ports/outbox.py defines OutboxEntry while repositories/outbox.py still defines its own, an adapter returning one and a test importing the other compare unequal and isinstance fails. Two referents for one name is exactly the collision slice (d) spent a task eliminating. Having repositories/outbox.py import the VOs from the port during a transitional window would be a shim, which the standing rule forbids.
  2. The __init__.py swap cannot precede the deletion. eventsource/__init__.py:191 imports six outbox names from eventsource.repositories, and tests/unit/test_public_api.py pins them. Rebinding them to the new paths while the old module still exists gives two live definitions again.
  3. The deletion cannot precede the swap. __init__.py is a runtime importer of eventsource.repositories. Deleting the package first makes import eventsource an ImportError โ€” nothing collects, no test runs, the commit cannot pass pre-commit. The same is true of the pyproject.toml forbidden_modules row: import-linter fails on a named module that does not exist, so that edit cannot land early either.

Everything that can be lifted out has been. Task 1 (outbox_event_data()) and Task 2 (the connection retarget) are green before and after and land first; the conformance suite and property tests (Task 4) are additive and land after; the ADR and docs (Task 5) reference nothing at import time.

Task 2 must precede Task 3 for a smaller reason: it strips execute_with_connection down to a single consumer (repositories/outbox.py), so Task 3 deletes the helper outright rather than negotiating five other importers mid-deletion.

Behavior deltas this slice makes visible

Spec ยง3. Repeated in the task that first encounters each.

Delta Before After Who feels it
list_pending_events on the Protocol and all three backends removed; use get_pending_events Task 3; CHANGELOG (Task 5)
OutboxRepositoryProtocol importable self-alias removed Task 3; CHANGELOG
eventsource.repositories importable package ModuleNotFoundError Task 3; pinned by test_public_api.py
in-memory event_data serialization orjson json_dumps, {"a":1} stdlib json.dumps, {"a": 1} Task 3; any exact-string assertion on event_data
execute_with_connection eventsource.repositories._connection gone; sql_connection(conn, *, write=) Task 2 (consumers), Task 3 (deletion)

Task 1: The shared payload builder

Files:

Interfaces:


def outbox_event_data(event: DomainEvent) -> dict[str, Any]: ...

Why this is lifted out of Task 3. The six-key payload dict is written out as a literal in four places today โ€” repositories/outbox.py:258-265, :551-558, :831-838, and adapters/postgresql/store.py:377-384 โ€” and it is a contract between the store's writer and the repositories' reader that nothing enforces. Landing the shared builder first means Task 3's three adapter moves each delete a literal rather than copying one, and it means the writer/reader alignment the slice was asked to pin is verified by its own test before the move churn starts.

Read all four sites listed above. Confirm by reading, not assumption, that they produce the same six keys with the same value types. Two spellings differ and must be reconciled deliberately:

Create tests/unit/ports/test_outbox_payload.py. Read a neighbouring module in tests/unit/ports/ (e.g. test_envelopes.py) for house style first.

Cases:

Run: uv run pytest tests/unit/ports/test_outbox_payload.py -q โ€” Expected: FAIL (ModuleNotFoundError: eventsource.ports.outbox).

Create src/eventsource/ports/outbox.py:


"""Transactional outbox port.

Pure boundary interface: stdlib, typing, uuid, datetime, dataclasses, and
`DomainEvent` only. No sqlalchemy, no driver types.
"""

from typing import Any

from eventsource.events.base import DomainEvent


def outbox_event_data(event: DomainEvent) -> dict[str, Any]:
    """Build the JSON-safe payload stored in `event_outbox.event_data`.

    This is the single authority for that shape. Both sides of the outbox
    depend on it: the same-transaction writer
    (`eventsource.adapters.postgresql.store.PostgreSQLEventStore._write_to_outbox`)
    produces it, and every `OutboxRepository` adapter stores it and hands it
    back on `OutboxEntry.event_data`. A drain worker parses it to rebuild the
    event, so adding or renaming a key is a wire-format change, not a
    refactor.

    The result contains only `str`, `None`, and JSON-native values, so
    `json.dumps` serializes it without a custom encoder.
    """
    return {
        "event_id": str(event.event_id),
        "aggregate_id": str(event.aggregate_id),
        "aggregate_type": event.aggregate_type,
        "tenant_id": str(event.tenant_id) if event.tenant_id else None,
        "occurred_at": event.occurred_at.isoformat(),
        "payload": event.model_dump(mode="json"),
    }


__all__ = ["outbox_event_data"]

Add outbox_event_data to ports/__init__.py's imports and __all__, in the position the file's existing grouping implies (it groups by concept with a comment per group โ€” add an outbox group rather than appending to an unrelated one).

In src/eventsource/adapters/postgresql/store.py::_write_to_outbox, replace the inline outbox_event_data = {...} literal (:377-384) with a call to the new helper. The local variable currently shares the helper's name โ€” rename the local or import the function under its own name so the two do not shadow each other; do not rename the function to avoid the collision.

Keep json.dumps(...) at the serialization site exactly as it is, including the comment at :368-372 explaining why stdlib json.dumps is used rather than the module's orjson json_dumps. Update that comment to note the payload now comes from ports.outbox.outbox_event_data, which guarantees JSON-safety.

Update the docstring at :358-370: the sentence pointing at eventsource.repositories.outbox as the reader is about to become false. Point it at eventsource.ports.outbox.OutboxRepository (the contract) โ€” not at eventsource.adapters.postgresql.outbox, which does not exist until Task 3. Also update the outbox_enabled property docstring at :149, which carries the same stale pointer.


grep -rn "occurred_at\": \|\"payload\": " src/eventsource/ | grep -v ports/outbox.py

Expected: the three literals still in repositories/outbox.py (Task 3 removes them) and nothing in adapters/.


grep -rn "eventsource.repositories" src/eventsource/adapters/

Expected: no matches.

Run: uv run pytest tests/unit/ports/ tests/unit/adapters/test_postgresql_outbox.py -q โ€” Expected: PASS. Run: uv run mypy src/eventsource/ --config-file=pyproject.toml โ€” Expected: clean. Run: uv run ruff check src/eventsource/ tests/unit/ports/ โ€” Expected: clean. Run: uv run lint-imports โ€” Expected: clean. (eventsource.ports is already a Tier-0 source_modules row; the new module inherits it and imports no sqlalchemy.)


git add src/eventsource/ports/outbox.py src/eventsource/ports/__init__.py \
        src/eventsource/adapters/postgresql/store.py tests/unit/ports/test_outbox_payload.py
git commit --only src/eventsource/ports/outbox.py src/eventsource/ports/__init__.py \
        src/eventsource/adapters/postgresql/store.py tests/unit/ports/test_outbox_payload.py \
        -m "refactor: pin the outbox payload shape in one place"

Record in the commit body: that four literals become one builder (three of them in Task 3), the model_dump(mode="json")-vs-json.loads(model_dump_json()) equivalence you confirmed in Step 1, and that the falsy tenant_id check was preserved deliberately.


Task 2: Retarget the five non-outbox `execute_with_connection` consumers

Files:

Interfaces:

Why sql_connection is the survivor (spec ยง2.3): no shims are permitted, so the helper cannot move and re-export; adapters/_sql/ is where the ring map puts shared SQL infrastructure and repositories/ has no successor; and write is keyword-only with no default, so every call site states its intent, where transactional=True was a silent default. adapters/_sql/connection.py's own docstring schedules this merge for "the outbox slice".

The mapping is exact and total: execute_with_connection(c, transactional=True) โ†’ sql_connection(c, write=True); transactional=False โ†’ write=False; a bare execute_with_connection(c) (which defaulted to transactional) โ†’ sql_connection(c, write=True). Both functions branch identically on isinstance(conn, AsyncEngine) and both yield a live AsyncConnection through without committing. Check every bare call โ€” readmodels/postgresql.py and migration/repositories/position_mapping.py both have call sites that omit the keyword, and reading write=True into them is a decision, not a transcription. Confirm each such site is a write (INSERT/UPDATE/DELETE) before assigning write=True; if one is a bare SELECT, that is a pre-existing bug where a read took a transaction, and you must report it rather than silently changing it to write=False.

adapters/_sql/connection.py has no direct test today โ€” it is covered only incidentally through adapters/sql/{checkpoints,dlq}.py. Before it becomes the tree's only connection helper it gets its own suite.

Create tests/unit/adapters/test_sql_connection.py. tests/unit/test_connection_helper.py (316 lines) is the working model for the mock shapes โ€” read it and port its cases, translating transactional= to write=. Note it patches "eventsource.repositories._connection.isinstance" by dotted string at eight sites; the equivalent target is "eventsource.adapters._sql.connection.isinstance". Do not delete tests/unit/test_connection_helper.py in this task โ€” execute_with_connection is still live until Task 3, and deleting its only coverage early would drop the module's line coverage below the gate for one commit.

Cases (all of test_connection_helper.py's, minus any that test only the defaulting behavior sql_connection deliberately does not have): engine + write=True uses begin(); engine + write=False uses connect(); a live AsyncConnection is yielded through unchanged for both values of write and is not committed; exceptions propagate and the engine context manager still exits; two sequential uses of the same engine each get their own context.

Run: uv run pytest tests/unit/adapters/test_sql_connection.py -q โ€” Expected: FAIL initially if you write the cases before checking the mock plumbing; if it passes on the first run, confirm the assertions actually exercise sql_connection (a suite that passes against an unmodified module is a suite that asserts nothing about this change โ€” check that a deliberate local inversion of the write branch, on a copy under $CLAUDE_JOB_DIR/tmp, would fail it).

Per module: change the import line to from eventsource.adapters._sql.connection import sql_connection, then rewrite each call site per the mapping above. The import line numbers at HEAD are readmodels/postgresql.py:29, migration/repositories/audit_log.py:64, migration/repositories/migration.py:67, migration/repositories/position_mapping.py:70, migration/repositories/routing.py:72 โ€” re-read each file rather than trusting these; other agents are active.

Do the modules one at a time and count call sites against the expected totals (readmodels 16, position_mapping 11, migration 10, routing 7, audit_log 5) before moving to the next. A count that does not match means either the file changed under you or you missed a site.

Do not reformat, reorder, or otherwise touch anything else in these five files. This is a rename.

The four migration unit-test modules patch the helper by dotted string on the consumer module, not on the helper's own module โ€” e.g. "eventsource.migration.repositories.routing.execute_with_connection". Each becomes "eventsource.migration.repositories.routing.sql_connection". Counts at HEAD: routing 23, position_mapping 22, migration 15, audit_log 16.

A stale patch target raises AttributeError at test time rather than passing vacuously, so a missed one fails loudly โ€” but verify by count and by grep anyway (Step 4), because a test that never runs cannot fail.

Any patched call whose mock asserts on the call's arguments (assert_called_with(..., transactional=True)) must have that assertion updated to write=True. Grep for transactional inside the test files, not only for the patch strings.

readmodels/postgresql.py's tests: locate them (grep -rln "readmodels" tests/unit/) and check whether they patch the helper the same way. If they do, they are part of this step; if they use a real engine or a different seam, leave them alone.


grep -rn "execute_with_connection" src/ tests/ bench/ examples/

Expected: only src/eventsource/repositories/_connection.py (the definition), src/eventsource/repositories/outbox.py (7 call sites + 1 import), and tests/unit/test_connection_helper.py. Anything else is a missed retarget.


grep -rn "transactional=" src/ tests/ bench/ examples/

Expected: the same three files only.

Run: uv run pytest tests/unit/adapters/test_sql_connection.py tests/unit/migration/ tests/unit/test_connection_helper.py -q โ€” Expected: PASS. Run: uv run pytest tests/unit/ -q --co โ€” Expected: collection succeeds. Run: uv run mypy src/eventsource/ --config-file=pyproject.toml โ€” Expected: clean. Run: uv run ruff check src/eventsource/ tests/unit/ โ€” Expected: clean. Run: uv run lint-imports โ€” Expected: clean.

The readmodels and migration integration suites need Docker and are the orchestrator's; do not start services.


git add src/eventsource/readmodels/postgresql.py src/eventsource/migration/repositories/ \
        tests/unit/adapters/test_sql_connection.py tests/unit/migration/
git commit --only src/eventsource/readmodels/postgresql.py src/eventsource/migration/repositories/ \
        tests/unit/adapters/test_sql_connection.py tests/unit/migration/ \
        -m "refactor: move the sql connection helper's consumers onto sql_connection"

Record in the commit body: the per-module call-site counts, the per-module patch-string counts, every bare execute_with_connection(c) call you resolved and which way you resolved it, and the accepted debt that four migration/ modules now name an adapters/ module by import (spec ยง2.3 โ€” no import-linter contract covers it, and their real destination is a later slice).


Task 3: The move โ€” port, three adapters, package deletion, public-API swap

Why this task is one commit. See "Why the split, the deletion, and the public-API swap are one task" above. In short: two live definitions of OutboxEntry is a nominal-identity collision, the __init__ swap needs the old module gone, and the deletion needs the swap done. Tasks 1 and 2 removed everything that could be removed. The steps are ordered so an implementer can work outside-in, and the orchestrator may dispatch Steps 1-5 and Steps 6-9 as separate work units against the same uncommitted tree โ€” but there is exactly one commit at the end.

Files:

Interfaces:


"""Transactional outbox port.

Pure boundary interface: stdlib, typing, uuid, datetime, dataclasses, and
`DomainEvent` only. No sqlalchemy, no driver types.

The outbox pattern lets events be published reliably even when the broker
is unavailable: the event row and the outbox row commit in one database
transaction, and a drain worker (which this library does not ship โ€” see
`docs/guides/repository-operations.md`) publishes and marks them.
"""

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Protocol, runtime_checkable
from uuid import UUID

from eventsource.events.base import DomainEvent


@dataclass
class OutboxEntry:
    """One row of the outbox.

    Attributes:
        id: Unique outbox entry identifier. A `UUID` on PostgreSQL and
            in memory; SQLite mints an autoincrement integer, so adapters
            may hand back either.
        event_id: Event ID being published
        event_type: Type of the event
        aggregate_id: Aggregate ID the event belongs to
        aggregate_type: Type of aggregate
        tenant_id: Tenant ID (optional)
        event_data: The `outbox_event_data()` payload, as the JSON string
            the backend stored or as the already-parsed dict
        created_at: When the entry was created
        status: Current status (pending, published, failed)
        published_at: When the event was published (if applicable)
        retry_count: Number of publish retry attempts
        last_error: Last error message (if any)
    """

    id: UUID
    event_id: UUID
    event_type: str
    aggregate_id: UUID
    aggregate_type: str
    tenant_id: UUID | None
    event_data: str | dict[str, Any]
    created_at: datetime
    status: str = "pending"
    published_at: datetime | None = None
    retry_count: int = 0
    last_error: str | None = None


@dataclass(frozen=True)
class OutboxStats:
    """Aggregate statistics for the outbox.

    Attributes:
        pending_count: Number of pending events
        published_count: Number of published events
        failed_count: Number of failed events
        oldest_pending: Timestamp of oldest pending event
        avg_retries: Average retry count for pending events
    """

    pending_count: int = 0
    published_count: int = 0
    failed_count: int = 0
    oldest_pending: datetime | None = None
    avg_retries: float = 0.0


@runtime_checkable
class OutboxRepository(Protocol):
    """Protocol for outbox repositories.

    Implementations store events transactionally with aggregate changes
    and hand them to a drain worker for asynchronous publishing.
    """

    async def add_event(self, event: DomainEvent) -> UUID:
        """Add an event to the outbox for publishing.

        Call this inside the same transaction that persists the event to
        the event store; that atomicity is the point of the pattern.

        Args:
            event: Domain event to publish

        Returns:
            Outbox record ID
        """
        ...

    async def get_pending_events(self, limit: int = 100) -> list[OutboxEntry]:
        """Get pending events that need to be published, oldest first.

        Args:
            limit: Maximum number of events to return

        Returns:
            List of OutboxEntry instances
        """
        ...

    async def mark_published(self, outbox_id: UUID) -> None:
        """Mark an outbox event as successfully published.

        Args:
            outbox_id: Outbox record ID
        """
        ...

    async def mark_failed(self, outbox_id: UUID, error: str) -> None:
        """Mark an outbox event as permanently failed.

        Args:
            outbox_id: Outbox record ID
            error: Error message
        """
        ...

    async def increment_retry(self, outbox_id: UUID, error: str | None = None) -> None:
        """Increment retry count for a failed publishing attempt.

        Args:
            outbox_id: Outbox record ID
            error: Error message (optional)
        """
        ...

    async def cleanup_published(self, days: int = 7) -> int:
        """Delete published events older than `days`.

        Args:
            days: Number of days to retain published events

        Returns:
            Number of records deleted
        """
        ...

    async def get_stats(self) -> OutboxStats:
        """Get outbox statistics.

        Returns:
            OutboxStats with outbox metrics
        """
        ...


def outbox_event_data(event: DomainEvent) -> dict[str, Any]:
    ...  # unchanged from Task 1


__all__ = [
    "OutboxEntry",
    "OutboxRepository",
    "OutboxStats",
    "outbox_event_data",
]
Name New source
OutboxRepository, OutboxEntry, OutboxStats, outbox_event_data eventsource.ports
InMemoryOutboxRepository eventsource.adapters.memory
PostgreSQLOutboxRepository eventsource.adapters.postgresql
SQLiteOutboxRepository (behind if SQLITE_AVAILABLE:) eventsource.adapters.sqlite

Names that die from eventsource and everywhere: OutboxRepositoryProtocol, OutboxRepository.list_pending_events (and its three implementations), the module path eventsource.repositories and every submodule of it, and the EventSourceJSONEncoder/json_dumps/json_loads re-exports that repositories/__init__.py carried (their home, eventsource.serialization, is untouched).

This file is the acceptance test for the export swap. Read it first; slice (d) rewrote it and it now has a TestBlessedStoreSurface-shaped identity section and a DEAD_NAMES absence case. Extend both rather than inventing a third idiom:


def test_top_level_outbox_repository_is_the_port_protocol(self) -> None:
    from eventsource.ports import OutboxRepository
    assert eventsource.OutboxRepository is OutboxRepository

def test_top_level_in_memory_outbox_is_the_memory_adapter(self) -> None:
    from eventsource.adapters.memory.outbox import InMemoryOutboxRepository
    assert eventsource.InMemoryOutboxRepository is InMemoryOutboxRepository

โ€” and the same shape for OutboxEntry, OutboxStats, and PostgreSQLOutboxRepository.

Run: uv run pytest tests/unit/test_public_api.py -q โ€” Expected: FAIL.

Add the two dataclasses and the Protocol per the Interfaces block, above the outbox_event_data Task 1 landed. Copy the dataclass field lists and docstrings from repositories/outbox.py:41-92 โ€” they are correct and reviewed; do not rewrite them, except for the id and event_data docstring lines, which the Interfaces block above improves (the id type genuinely varies by backend and the old docstring did not say so).

The Protocol carries seven methods, not eight: list_pending_events does not move. Update ports/__init__.py's outbox group and __all__.

Each is a move, not a rewrite. Copy the class verbatim, then apply exactly the changes listed for it and nothing else. Do not reformat, do not rename locals, do not "improve" a query.

src/eventsource/adapters/memory/outbox.py โ€” from repositories/outbox.py:497-751:

src/eventsource/adapters/postgresql/outbox.py โ€” from repositories/outbox.py:198-494:

src/eventsource/adapters/sqlite/outbox.py โ€” from repositories/outbox.py:754-1076:

Add the new class to each of adapters/{memory,postgresql,sqlite}/__init__.py's imports and __all__, following each file's existing alphabetical-within-__all__ convention. Update each package docstring's one-line summary: memory's currently reads "implementing the store, snapshot, checkpoint, and DLQ ports" and now also implements the outbox port; postgresql's and sqlite's read "implementing the store ports" and now cover snapshots and the outbox too โ€” fix all three, since the sqlite and postgresql summaries were already understating their contents before this slice.

In src/eventsource/__init__.py:


git status --porcelain src/eventsource/repositories/ tests/unit/test_connection_helper.py

Confirm no other agent has uncommitted work under those paths. If any file there is modified, stop and report rather than deleting someone's work. Then:


git rm -r src/eventsource/repositories/
git rm tests/unit/test_connection_helper.py

tests/unit/test_connection_helper.py dies with execute_with_connection; tests/unit/adapters/test_sql_connection.py (Task 2) is its successor and covers the same control flow.

Do not touch tests/unit/repositories/. It holds test_dialect.py and test_dialect_properties.py, which test adapters/_sql/dialect.py and have nothing to do with the deleted source package. The mutmut test selection names that directory.

In pyproject.toml:

Concurrency caveat: other agents edit pyproject.toml. Locate each contract by its name = line, not by line number, and re-read the file immediately before editing.


grep -rn "eventsource\.repositories\|OutboxRepositoryProtocol\|list_pending_events\|execute_with_connection" \
  src/ tests/ bench/ examples/ pyproject.toml

Expected: zero matches. (docs/ still has matches โ€” those are Task 5's.)


grep -rn "from eventsource.repositories\|import repositories" src/ tests/ bench/ examples/

Expected: zero matches.


git status --porcelain src/eventsource/migrations/

Expected: empty. This slice changes no SQL.

Run: uv run pytest tests/unit/test_public_api.py -q โ€” Expected: PASS. Run: uv run python -c "import eventsource.repositories" โ€” Expected: ModuleNotFoundError. Run: uv run python -c "import sys; import eventsource.ports.outbox; assert 'sqlalchemy' not in sys.modules" โ€” Expected: exits 0. This is the Tier-0 claim, checked at runtime rather than only statically. Run: uv run pytest tests/unit/ -q โ€” Expected: PASS. (This task is the one exception to "targeted tests only": the unit suite is the only thing that proves the deletion did not orphan a consumer. Do not run integration or make check.) Run: uv run mypy src/eventsource/ --config-file=pyproject.toml โ€” Expected: clean. Run: uv run ruff check src/ tests/ bench/ โ€” Expected: clean. Run: uv run lint-imports โ€” Expected: clean.


git add src/eventsource/ports/ src/eventsource/adapters/ src/eventsource/__init__.py \
        pyproject.toml tests/
git status --porcelain

Review that git status output line by line before committing โ€” this is the largest commit of the slice and a stray file from another agent must not ride along.


git commit -m "refactor: split the outbox onto ports and adapters, delete repositories/"

Record in the commit body: the four deleted-and-rehomed names (OutboxRepositoryProtocol, list_pending_events ร—3 implementations plus the Protocol method, the eventsource.repositories path, the JSON re-exports), behavior delta 4 and every assertion it forced you to rewrite, the two pyproject.toml contract edits, confirmation that mutmut needed no edit, and that migrations/ is untouched.


Task 4: Conformance suite and property tests

Files:

Interfaces:

Why after the move and not with it. The suite is additive and cannot be written against two competing OutboxEntry definitions. Landing it separately also keeps the gap it may find โ€” an adapter that does not honor the port it now formally claims โ€” reviewable on its own rather than buried in a 2,000-line move.

Create src/eventsource/testing/conformance_ports/outbox.py. Read conformance_ports/dlq.py first and match it exactly: an ABC with an abstract store pytest fixture, importing only from eventsource.ports, eventsource.events, and pytest/stdlib โ€” no sqlalchemy, no adapter imports. Use the shared helpers in conformance_ports/_fixtures.py for event construction; read two neighbouring suites before writing.


"""Conformance suite for the `OutboxRepository` port.

Subclass and provide a `store` fixture yielding a fresh adapter instance.
Cleanup cutoff semantics differ per backend (PostgreSQL computes
`NOW() - INTERVAL`, SQLite `datetime('now', ...)`, and the in-memory
adapter a Python `timedelta`), so only the status partition is asserted
here -- exact cutoff boundaries belong in the backend-specific modules,
following the pattern `dlq.py` established.
"""

Cases, one per behavior, named in the house test__ style:

Two things to get right, both learned from the existing suites: an unknown outbox_id passed to mark_published/mark_failed/increment_retry is a no-op on the in-memory adapter (it guards with if outbox_id in self._entries) and silently affects zero rows on both SQL adapters โ€” so a "missing id" case is legitimate conformance and should assert "does not raise and changes nothing", not an exception. And OutboxEntry.id is a UUID on PostgreSQL and in memory but an autoincrement integer on SQLite, so no case may assume its type; round-trip the value the adapter gave you.

Export the class from conformance_ports/__init__.py (import + __all__), and update that package docstring's list of suites.

Run: uv run pytest tests/unit/adapters/ -q โ€” Expected: PASS, with the collected count up by the number of suite cases ร— 2 backends.

If a newly added case fails on an adapter, stop and report. That is a genuine divergence between an adapter and the port it now formally claims, and deciding whether the adapter or the suite is wrong is not an implementer's call.

Create tests/unit/adapters/test_memory_outbox_properties.py, modelled on test_memory_dlq_properties.py. Exactly two properties (spec ยง4.2):

Use the project's existing hypothesis settings idiom (read the neighbouring properties module for the @settings decorator and any registered profile). Keep generated sizes small โ€” these run in the default unit suite.

Do not write property tests for the SQL adapters or for OutboxEntry construction.


grep -rn "sqlalchemy\|aiosqlite\|asyncpg\|eventsource.adapters" src/eventsource/testing/conformance_ports/outbox.py

Expected: no matches. The suite is backend-free.

Run: uv run pytest tests/unit/adapters/ tests/unit/test_conformance.py -q โ€” Expected: PASS. Run: uv run mypy src/eventsource/ --config-file=pyproject.toml โ€” Expected: clean. Run: uv run ruff check src/eventsource/testing/ tests/unit/adapters/ โ€” Expected: clean. Run: uv run lint-imports โ€” Expected: clean. (eventsource.testing.conformance is a Tier-0 row; conformance_ports inherits the same discipline and the new module must not break it.)

The PostgreSQL conformance run needs Docker and is the orchestrator's; do not start services.


git add src/eventsource/testing/conformance_ports/ \
        tests/unit/adapters/test_memory_outbox_conformance.py \
        tests/unit/adapters/test_memory_outbox_properties.py \
        tests/unit/adapters/test_sqlite_conformance.py \
        tests/integration/repositories/test_outbox.py
git commit --only <the same paths> -m "test: conformance and property suites for the outbox port"

Record in the commit body: the case count, the collected-count delta per backend, the two properties and what each fixes in place, and any divergence you found and reported rather than fixed.


Task 5: ADR 0026, docs, changelog, backlog

Files:

Interfaces:

docs/adrs/0026-outbox-ring-migration.md. Follow the house shape โ€” read 0024-projection-persistence-ports.md (the direct precedent, same refactor on the sibling modules) and 0025-legacy-store-retirement.md first. Confirm 0026 is still the next free number before writing; other agents are active and ADRs are numbered after the current highest.

The Decision must record:

  1. The split: VOs + Protocol to ports/outbox.py (Tier 0), implementations to adapters/{memory,postgresql,sqlite}/outbox.py. Same operation ADR 0024 applied to checkpoint and DLQ; this completes the set of three.
  2. Per-backend, not dialect-parameterized โ€” and the rule that follows from it: a repository belongs in adapters/sql/ when one sqlalchemy implementation serves both dialects, and in adapters// when the backends take different drivers. The SQLite outbox takes a raw aiosqlite.Connection; unifying it would mean rewriting a working adapter onto sqlalchemy. Rejected alternative, named and not built.
  3. outbox_event_data() as the single authority for the six-key payload, replacing four copies, one of which lived in a different ring from the other three.
  4. The connection-helper consolidation onto sql_connection, with the accepted debt that four migration/ modules and readmodels/postgresql.py now import an adapters/ module โ€” permitted by every contract, and resolved when those modules move to adapters/ in their own slice.
  5. Deletion of the repositories/ package.
  6. Death of OutboxRepositoryProtocol and list_pending_events โ€” no shims, unreleased software, one name per thing.
  7. The in-memory event_data serialization change (orjson โ†’ stdlib), and that it buys one fewer non-stdlib import in a Tier-0 adapter.
  8. That ADR 0016's tracing decision stands for the outbox repositories, unlike the store adapters that 0025 amended it for โ€” outbox repositories keep their spans.

Include an ADR Impact table per .claude/rules/definition-of-done.md, rendering spec ยง6's verdicts as this record's own impact statement rather than copying the prose: 0015 stands, 0016 stands, 0019 stands, 0024 stands (extended, not amended), 0025 stands. No existing ADR is amended by this one, so no Status pointer is added to any other record โ€” say so explicitly in the Consequences, because a reviewer checking the definition-of-done rule will look for the pointers and should find the reason they are absent.

Add the 0026 entry to docs/adrs/index.md in the style of its neighbours: one dense sentence naming what it decides, its relationships, and "Complete."


grep -rn "eventsource\.repositories\|OutboxRepositoryProtocol\|list_pending_events\|execute_with_connection\|repositories/outbox\|repositories/_connection" \
  docs/ examples/ README.md CLAUDE.md | grep -v "docs/superpowers/"

Skip docs/superpowers/ entirely โ€” specs and plans are dated records of what was decided when, and rewriting them destroys the audit trail. Work the rest:

CHANGELOG.md [Unreleased]. Add:

Call behavior delta 4 out explicitly โ€” the in-memory adapter's event_data JSON spacing changed with the move from orjson to stdlib json.dumps. It is cosmetic for any consumer that parses the field and breaking for one that compares the string.

Check whether any existing [Unreleased] bullet now describes a state that no longer holds (the slice-(d) adapters bullet mentions outbox_enabled and the outbox reader's location). [Unreleased] has not shipped, so edit such a bullet in place to describe the end state rather than layering a correction on top โ€” and say in the commit body that you did.

BACKLOG.md:


grep -rn "eventsource\.repositories\|OutboxRepositoryProtocol\|list_pending_events\|execute_with_connection" \
  src/ tests/ bench/ examples/ docs/ CLAUDE.md README.md pyproject.toml | grep -v "docs/superpowers/"

Expected: zero matches. This is the acceptance for the whole slice.


git status --porcelain src/eventsource/migrations/

Expected: empty.

Run: uv run ruff check examples/ โ€” Expected: clean. Run: uv run pytest tests/unit/test_public_api.py -q โ€” Expected: PASS (docs changes must not move the surface). Run: uv run lint-imports โ€” Expected: clean.


git add docs/ CLAUDE.md CHANGELOG.md BACKLOG.md examples/
git commit --only docs/ CLAUDE.md CHANGELOG.md BACKLOG.md examples/ \
        -m "docs: adr 0026 and the outbox ring documentation sweep"

Record in the commit body: which pages were rewritten wholesale versus patched, whether docs/api/repositories.md was renamed and why, the backlog items closed versus carried and what was edited in each, and any [Unreleased] changelog entry corrected in place.


Slice Completion Criteria

The orchestrator runs these; implementers do not.

Plan Self-Review

Spec Gaps and Contradictions Found (report, do not silently deviate)

  1. The backlog item this slice implements specifies the wrong destination. BACKLOG.md's "Migrate outbox repository to ports/adapters" says the SQL implementation goes to adapters/sql/outbox.py, following checkpoint and DLQ. That is not possible without rewriting SQLiteOutboxRepository off aiosqlite and onto sqlalchemy, which is a behavior change to a working adapter with no caller requesting it. The spec (ยง2.2) and this plan land three driver-specific modules instead. Recorded in ADR 0026 rather than silently diverging, and the backlog item is deleted rather than edited (Task 5 Step 4).
  2. docs/core-surface.md step 4 offers a choice this slice cannot take. It says to pick "either a backend-only subpackage under repositories/, or the shared SQL infrastructure directory at adapters/_sql/". The first option is unavailable, because the same document's step 5 and this slice both delete repositories/ entirely. Only one of the two options was ever real once the package deletion was in scope. No deviation โ€” the choice is made for us.
  3. docs/core-surface.md step 4 predicts a bare move breaks eight patch strings; the real count is larger and elsewhere. It flags tests/unit/test_connection_helper.py's eight "eventsource.repositories._connection.isinstance" patches. It does not mention the ~90 "....execute_with_connection" patches in the four migration test modules, which are the actual bulk of the churn (Task 2 Step 3) โ€” and test_connection_helper.py is deleted rather than moved, so its eight strings never need updating at all.
  4. The [tool.mutmut] edit the task brief anticipated is not needed. Verified at HEAD: only_mutate lists src/eventsource/ports and src/eventsource/adapters as whole directories, and pytest_add_cli_args_test_selection lists tests/unit/ports/ and tests/unit/adapters/. The new modules and their tests are covered the moment they land in those paths, which is why Task 3 Step 7 and Task 4 place every new test there. Task 3 Step 8 still says to verify rather than assume, since another agent could narrow those entries.
  5. tests/unit/repositories/ and tests/repositories/ are both live and neither corresponds to the deleted source package. The first holds dialect tests (and is named in the mutmut selection); the second holds SQLite checkpoint tests alongside the outbox tests this slice moves out. A sweep that deletes by name would take real coverage with it. Called out in Task 3 Steps 6 and 7.
  6. ADR 0016's tracing decision now means two different things in two rings. ADR 0025 amended it so store adapters emit no per-operation spans; the outbox repositories keep theirs, unchanged by this slice. Nothing is wrong, but "does this adapter trace?" no longer has one answer, and ADR 0026 item 8 states the outbox side explicitly so the next reader does not infer the store rule applies everywhere under adapters/.