Skip to content

EventStorePort

Event store interface for event-sourced persistence. Every event store adapter (Memory, MessageDB, etc.) implements EventStorePort, and domain.event_store is the EventStore service that calls it.

See Event Store Adapters for concrete adapter configuration, and Write an Event-Store Adapter for a worked adapter that implements this Port.


EventStorePort

The typing.Protocol every event store adapter implements. The EventStore service builds the event store's reads, writes, aggregate loading and snapshots on these members.

Bases: Protocol

The operations an event-store adapter implements.

Every read includes the row at position. A stream read pages by the stream position. A category read and an all read page by global_position (ADR-0024). A category read returns only streams whose category equals category exactly, and never a snapshot stream (<category>:snapshot-<id>).

Build the adapter named name for domain from config.

Source code in src/protean/port/event_store.py
96
97
def __init__(self, name: str, domain: Domain, config: Mapping[str, Any]) -> None:
    """Build the adapter named ``name`` for ``domain`` from ``config``."""

capabilities abstractmethod property

capabilities: EventStoreCapabilities

The guarantees this event store makes.

write_message abstractmethod

write_message(
    stream_name: str,
    message_type: str,
    data: Mapping[str, Any],
    metadata: Mapping[str, Any] | None = None,
    expected_version: int | None = None,
) -> int

Append a message to stream_name and return its stream position.

RAISES DESCRIPTION
ExpectedVersionError

When expected_version is given and is not the stream's current version. Nothing is written.

Source code in src/protean/port/event_store.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@abstractmethod
def write_message(
    self,
    stream_name: str,
    message_type: str,
    data: Mapping[str, Any],
    metadata: Mapping[str, Any] | None = None,
    expected_version: int | None = None,
) -> int:
    """Append a message to ``stream_name`` and return its stream position.

    Raises:
        ExpectedVersionError: When ``expected_version`` is given and is not
            the stream's current version. Nothing is written.
    """

get_stream_messages abstractmethod

get_stream_messages(
    stream_name: str, position: int = 0, limit: int = 1000
) -> list[RawMessage]

Return up to limit rows of one stream from stream position.

Source code in src/protean/port/event_store.py
120
121
122
123
124
@abstractmethod
def get_stream_messages(
    self, stream_name: str, position: int = 0, limit: int = 1000
) -> list[RawMessage]:
    """Return up to ``limit`` rows of one stream from stream ``position``."""

get_category_messages abstractmethod

get_category_messages(
    category: str,
    position: int = 0,
    limit: int = 1000,
    *,
    consumer_group_member: int | None = None,
    consumer_group_size: int | None = None,
) -> list[RawMessage]

Return up to limit rows of category from global_position.

With consumer_group_member and consumer_group_size, return only the streams that belong to that member of the group.

RAISES DESCRIPTION
NotSupportedError

When a consumer-group argument is given and the adapter does not declare CONSUMER_GROUPS.

ValueError

When an adapter that declares CONSUMER_GROUPS gets only one of the two consumer-group arguments.

Source code in src/protean/port/event_store.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@abstractmethod
def get_category_messages(
    self,
    category: str,
    position: int = 0,
    limit: int = 1000,
    *,
    consumer_group_member: int | None = None,
    consumer_group_size: int | None = None,
) -> list[RawMessage]:
    """Return up to ``limit`` rows of ``category`` from ``global_position``.

    With ``consumer_group_member`` and ``consumer_group_size``, return only
    the streams that belong to that member of the group.

    Raises:
        NotSupportedError: When a consumer-group argument is given and the
            adapter does not declare ``CONSUMER_GROUPS``.
        ValueError: When an adapter that declares ``CONSUMER_GROUPS``
            gets only one of the two consumer-group arguments.
    """

get_all_messages abstractmethod

get_all_messages(
    position: int = 0, limit: int = 1000
) -> list[RawMessage]

Return up to limit rows of the whole store from global_position.

Source code in src/protean/port/event_store.py
148
149
150
151
152
@abstractmethod
def get_all_messages(
    self, position: int = 0, limit: int = 1000
) -> list[RawMessage]:
    """Return up to ``limit`` rows of the whole store from ``global_position``."""

get_last_stream_message abstractmethod

get_last_stream_message(
    stream_name: str,
) -> RawMessage | None

Return the newest row of one stream, or None when it is empty.

Source code in src/protean/port/event_store.py
154
155
156
@abstractmethod
def get_last_stream_message(self, stream_name: str) -> RawMessage | None:
    """Return the newest row of one stream, or ``None`` when it is empty."""

get_last_category_message abstractmethod

get_last_category_message(
    category: str,
) -> RawMessage | None

Return the row of category with the highest global_position.

Returns None when the category is empty.

Source code in src/protean/port/event_store.py
158
159
160
161
162
163
@abstractmethod
def get_last_category_message(self, category: str) -> RawMessage | None:
    """Return the row of ``category`` with the highest ``global_position``.

    Returns ``None`` when the category is empty.
    """

get_last_message abstractmethod

get_last_message() -> RawMessage | None

Return the row with the highest global_position in the store.

Returns None when the store is empty.

Source code in src/protean/port/event_store.py
165
166
167
168
169
170
@abstractmethod
def get_last_message(self) -> RawMessage | None:
    """Return the row with the highest ``global_position`` in the store.

    Returns ``None`` when the store is empty.
    """

stream_ids abstractmethod

stream_ids(category: str) -> list[str]

Return the sorted, unique identifiers of the streams in category.

A stream <category>-<id> gives <id>. Snapshot streams are left out.

Source code in src/protean/port/event_store.py
172
173
174
175
176
177
178
@abstractmethod
def stream_ids(self, category: str) -> list[str]:
    """Return the sorted, unique identifiers of the streams in ``category``.

    A stream ``<category>-<id>`` gives ``<id>``. Snapshot streams are left
    out.
    """

ping abstractmethod

ping() -> bool

Return whether the store answers. Never raises.

Source code in src/protean/port/event_store.py
180
181
182
@abstractmethod
def ping(self) -> bool:
    """Return whether the store answers. Never raises."""

health abstractmethod

health() -> EventStoreHealth

Return the store's health record.

Source code in src/protean/port/event_store.py
184
185
186
@abstractmethod
def health(self) -> EventStoreHealth:
    """Return the store's health record."""

get_connection abstractmethod

get_connection() -> object

Return the native client, or None for an adapter without one.

Source code in src/protean/port/event_store.py
188
189
190
@abstractmethod
def get_connection(self) -> object:
    """Return the native client, or ``None`` for an adapter without one."""

clear abstractmethod

clear() -> None

Delete every message. Test-harness use only.

Source code in src/protean/port/event_store.py
192
193
194
@abstractmethod
def clear(self) -> None:
    """Delete every message. Test-harness use only."""

close

close() -> None

Release the store's connections. The default does nothing.

Source code in src/protean/port/event_store.py
196
197
198
def close(self) -> None:
    """Release the store's connections. The default does nothing."""
    return

create_schema

create_schema() -> None

Create the store's tables, behind SCHEMA_MANAGEMENT.

The default does nothing.

Source code in src/protean/port/event_store.py
200
201
202
203
204
205
def create_schema(self) -> None:
    """Create the store's tables, behind ``SCHEMA_MANAGEMENT``.

    The default does nothing.
    """
    return

drop_schema

drop_schema() -> None

Drop the store's tables, behind SCHEMA_MANAGEMENT.

The default does nothing.

Source code in src/protean/port/event_store.py
207
208
209
210
211
212
def drop_schema(self) -> None:
    """Drop the store's tables, behind ``SCHEMA_MANAGEMENT``.

    The default does nothing.
    """
    return

EventStoreCapabilities

The guarantees an event store declares on its capabilities property.

Bases: Flag

The guarantees an event store makes.

Each event store declares its flags on capabilities. Check a guarantee with EventStoreCapabilities.DURABLE in store.capabilities.


RawMessage

The row an event store returns from a read.

Bases: TypedDict

One row as an event store returns it.

position is the row's place in its stream, from 0 with no gaps. global_position is its place in the whole store and may have gaps. A snapshot row has type == "SNAPSHOT" and metadata of None.


EventStoreHealth

What health() reports: whether the store answered, and its connection pool counts when the store has a pool.

The health of an event store.

reachable is the result of ping(). pool describes the adapter's connection pool, or is None for an adapter without one or whose pool does not exist yet.


EventStore

The service that domain.event_store returns. It holds the domain's adapter and provides reads, writes, aggregate loading, snapshots, causation tracing and the integrity check.

The framework's view of the domain's event-store adapter.

domain.event_store returns one. The adapter is built by domain.init(); until then _adapter is None.

RAISES DESCRIPTION
ConfigurationError

From every feature method and forwarder that reaches the adapter, when domain.init() has not built it yet. The error carries the code CONFIG_EVENT_STORE_NOT_INITIALIZED. close and the static category need no adapter and do not raise ConfigurationError.

Source code in src/protean/infra/event_store.py
231
232
233
def __init__(self, domain: Domain) -> None:
    self.domain: Domain = domain
    self._adapter: EventStorePort | None = None

capabilities property

capabilities: EventStoreCapabilities

The guarantees the adapter makes.

close

close() -> None

Close the event store and release all connections.

Delegates to the adapter's close() without clearing the reference, so the service remains usable (e.g., in test mode where the domain is still accessed after Engine.shutdown()).

Source code in src/protean/infra/event_store.py
235
236
237
238
239
240
241
242
243
244
def close(self) -> None:
    """Close the event store and release all connections.

    Delegates to the adapter's close() without clearing the
    reference, so the service remains usable (e.g., in test mode
    where the domain is still accessed after Engine.shutdown()).
    """
    if self._adapter is not None:
        self._adapter.close()
        logger.debug("Event store closed")

clear

clear() -> None

Delete every message. Test-harness use only.

Source code in src/protean/infra/event_store.py
286
287
288
def clear(self) -> None:
    """Delete every message. Test-harness use only."""
    self._require_adapter().clear()

ping

ping() -> bool

Return whether the store answers.

Source code in src/protean/infra/event_store.py
290
291
292
def ping(self) -> bool:
    """Return whether the store answers."""
    return self._require_adapter().ping()

health

health() -> EventStoreHealth

Return the store's health record.

Source code in src/protean/infra/event_store.py
294
295
296
def health(self) -> EventStoreHealth:
    """Return the store's health record."""
    return self._require_adapter().health()

get_connection

get_connection() -> object

Return the adapter's native client, or None for an adapter without one.

Source code in src/protean/infra/event_store.py
298
299
300
def get_connection(self) -> object:
    """Return the adapter's native client, or `None` for an adapter without one."""
    return self._require_adapter().get_connection()

category staticmethod

category(stream: str) -> str

Return the category of stream: the part before the first -.

Returns "" for an empty or None stream name.

Source code in src/protean/infra/event_store.py
367
368
369
370
371
372
373
374
375
376
377
@staticmethod
def category(stream: str) -> str:
    """Return the category of ``stream``: the part before the first ``-``.

    Returns ``""`` for an empty or ``None`` stream name.
    """
    if not stream:
        return ""

    stream_category, _, _ = stream.partition("-")
    return stream_category

read

read(
    stream: str, position: int = 0, limit: int = 1000
) -> list[Message]

Return up to limit messages of stream from position.

stream is $all, a category, or a category-id stream. Snapshot rows count toward limit and are left out of the result.

Source code in src/protean/infra/event_store.py
379
380
381
382
383
384
385
386
387
388
def read(self, stream: str, position: int = 0, limit: int = 1000) -> list[Message]:
    """Return up to ``limit`` messages of ``stream`` from ``position``.

    ``stream`` is ``$all``, a category, or a ``category-id`` stream. Snapshot
    rows count toward ``limit`` and are left out of the result.
    """
    messages, _ = self._read_with_snapshot_positions(
        stream, position=position, limit=limit
    )
    return messages

read_all

read_all(
    stream: str = "$all", *, page_size: int = 1000
) -> Iterator[Message]

Yield every message in stream, reading the store in pages of page_size rows.

A single read returns at most limit rows, so use this for a read that must be complete, such as a projection rebuild or a backup. Memory use stays bounded whatever the size of the stream. Snapshot rows are skipped, so only events and commands are yielded.

PARAMETER DESCRIPTION
stream

The stream to read. $all (default), a category, or a specific category-id stream.

TYPE: str DEFAULT: '$all'

page_size

Number of rows to read from the store per page.

TYPE: int DEFAULT: 1000

YIELDS DESCRIPTION
Message

Every Message in stream, in read order, with no gaps and

Message

no duplicates across page boundaries.

RAISES DESCRIPTION
IncorrectUsageError

If page_size is not a positive integer, or a stored row is missing its position.

Source code in src/protean/infra/event_store.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def read_all(
    self, stream: str = "$all", *, page_size: int = 1000
) -> Iterator[Message]:
    """Yield every message in ``stream``, reading the store in pages of ``page_size`` rows.

    A single ``read`` returns at most ``limit`` rows, so use this for
    a read that must be complete, such as a projection rebuild or a backup.
    Memory use stays bounded whatever the size of the stream. Snapshot rows
    are skipped, so only events and commands are yielded.

    Args:
        stream: The stream to read. ``$all`` (default), a category, or a
            specific ``category-id`` stream.
        page_size: Number of rows to read from the store per page.

    Yields:
        Every `Message` in ``stream``, in read order, with no gaps and
        no duplicates across page boundaries.

    Raises:
        IncorrectUsageError: If ``page_size`` is not a positive integer, or
            a stored row is missing its position.
    """
    for raw_message in self._read_all_raw(stream, page_size=page_size):
        yield Message.deserialize(raw_message)

read_last_message

read_last_message(stream: str) -> Message | None

Return the newest event or command of stream, or None when it has none.

Source code in src/protean/infra/event_store.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def read_last_message(self, stream: str) -> Message | None:
    """Return the newest event or command of ``stream``, or ``None`` when it has none."""
    raw_message = self._read_last_raw(stream)
    if raw_message is None:
        return None

    # The newest row can be a snapshot (aggregate state, no metadata), which
    # is neither an event nor a command and would raise on deserialize. In
    # practice this is the `$all` scan (outbox reconciliation reads it that
    # way), where snapshot streams interleave with event streams; a specific
    # or bare-category read filters to `{category}-` and never sees a
    # `{category}:snapshot-` row, so its tail is already an event. Skip back
    # to the newest actual message so those callers do not crash.
    if _is_snapshot_row(raw_message):
        raw_message = self._last_non_snapshot_message(stream, raw_message)
        if raw_message is None:
            return None

    return Message.deserialize(raw_message)

category_head_position

category_head_position(category: str) -> int

Return the global_position of the newest row in category.

For $all the row can be a snapshot row, because this reads raw rows and skips nothing.

Subscription lag monitoring uses it to find how far a subscription is behind the head of its category.

PARAMETER DESCRIPTION
category

A category, such as test::user, or $all for the whole store. A stream name, such as test::user-1, gives the newest row of that one stream.

TYPE: str

RETURNS DESCRIPTION
int

The global_position of the newest row, or -1 when the

int

category has no rows.

Source code in src/protean/infra/event_store.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def category_head_position(self, category: str) -> int:
    """Return the ``global_position`` of the newest row in ``category``.

    For ``$all`` the row can be a snapshot row, because this reads raw rows
    and skips nothing.

    Subscription lag monitoring uses it to find how far a subscription is
    behind the head of its category.

    Args:
        category: A category, such as ``test::user``, or ``$all`` for the
            whole store. A stream name, such as ``test::user-1``, gives
            the newest row of that one stream.

    Returns:
        The ``global_position`` of the newest row, or ``-1`` when the
        category has no rows.
    """
    # A subscription whose category names one stream passes that stream
    # here, so a name with a ``-`` reads the stream through the
    # ``_read_raw`` scope rule; Message DB finds no category of that name.
    message = self._read_last_raw(category)
    return message["global_position"] if message else -1

append

append(message_object: BaseEvent | BaseCommand) -> int

Write an event or command to its stream and return its stream position.

RAISES DESCRIPTION
ExpectedVersionError

When the message carries an expected version that is not the stream's current version. Nothing is written.

Source code in src/protean/infra/event_store.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def append(self, message_object: BaseEvent | BaseCommand) -> int:
    """Write an event or command to its stream and return its stream position.

    Raises:
        ExpectedVersionError: When the message carries an expected version
            that is not the stream's current version. Nothing is written.
    """
    adapter = self._require_adapter()
    tracer = self.domain.tracer

    with tracer.start_as_current_span(
        "protean.event_store.append",
        record_exception=False,
        set_status_on_exception=False,
    ) as span:
        message = Message.from_domain_object(message_object)
        assert message.metadata is not None, "Message metadata cannot be None"

        stream = message.metadata.headers.stream
        message_type = message.metadata.headers.type
        assert stream is not None, "Message stream cannot be None"
        assert message_type is not None, "Message type cannot be None"

        span.set_attribute("protean.event_store.stream", stream)
        span.set_attribute("protean.event_store.message_type", message_type)

        try:
            position = adapter.write_message(
                stream,
                message_type,
                message.data,
                metadata=message.metadata.to_dict(),
                expected_version=message.metadata.domain.expected_version
                if message.metadata.domain
                else None,
            )

            span.set_attribute("protean.event_store.position", position)
            return position
        except Exception as exc:  # marks the span as failed, then re-raises
            set_span_error(span, exc)
            raise

load_aggregate

load_aggregate(
    part_of: type[BaseAggregate],
    identifier: str,
    *,
    at_version: int | None = None,
    as_of: datetime | None = None,
) -> BaseAggregate | None

Load an aggregate by replaying its events.

By default, rebuilds the aggregate in its current (latest) state. When at_version or as_of is given, rebuilds its state at that point in history.

PARAMETER DESCRIPTION
part_of

The EventSourced Aggregate's class.

TYPE: type[BaseAggregate]

identifier

Unique aggregate identifier.

TYPE: str

at_version

Reconstitute to this exact version (0-indexed). Version 0 is the state after the first event.

TYPE: int | None DEFAULT: None

as_of

Reconstitute the aggregate as of this timestamp. Only events written on or before as_of are applied.

TYPE: datetime | None DEFAULT: None

RETURNS DESCRIPTION
BaseAggregate | None

The aggregate, or None when its stream holds no events.

RAISES DESCRIPTION
ObjectNotFoundError

If at_version is past the aggregate's latest version, or no event was written on or before as_of.

Source code in src/protean/infra/event_store.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def load_aggregate(
    self,
    part_of: type[BaseAggregate],
    identifier: str,
    *,
    at_version: int | None = None,
    as_of: datetime | None = None,
) -> BaseAggregate | None:
    """Load an aggregate by replaying its events.

    By default, rebuilds the aggregate in its current (latest) state. When
    ``at_version`` or ``as_of`` is given, rebuilds its state at that point
    in history.

    Args:
        part_of: The EventSourced Aggregate's class.
        identifier: Unique aggregate identifier.
        at_version: Reconstitute to this exact version (0-indexed).
            Version 0 is the state after the first event.
        as_of: Reconstitute the aggregate as of this timestamp.
            Only events written on or before ``as_of`` are applied.

    Returns:
        The aggregate, or ``None`` when its stream holds no events.

    Raises:
        ObjectNotFoundError: If ``at_version`` is past the aggregate's latest
            version, or no event was written on or before ``as_of``.
    """
    if as_of is not None:
        return self._load_aggregate_as_of(part_of, identifier, as_of)
    if at_version is not None:
        return self._load_aggregate_at_version(part_of, identifier, at_version)
    return self._load_aggregate_current(part_of, identifier)

create_snapshot

create_snapshot(
    part_of: type[BaseAggregate], identifier: str
) -> bool

Create a snapshot for a specific event-sourced aggregate instance.

Rebuilds the aggregate from its full event stream and writes its current state to the snapshot stream. The snapshot is written whatever the snapshot threshold.

PARAMETER DESCRIPTION
part_of

The EventSourced Aggregate class.

TYPE: type[BaseAggregate]

identifier

Unique aggregate identifier.

TYPE: str

RETURNS DESCRIPTION
bool

True if a snapshot was created.

RAISES DESCRIPTION
IncorrectUsageError

If the aggregate is not event-sourced.

ObjectNotFoundError

If no events exist for the given identifier.

Source code in src/protean/infra/event_store.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
def create_snapshot(self, part_of: type[BaseAggregate], identifier: str) -> bool:
    """Create a snapshot for a specific event-sourced aggregate instance.

    Rebuilds the aggregate from its full event stream and writes its current
    state to the snapshot stream. The snapshot is written whatever the
    snapshot threshold.

    Args:
        part_of: The EventSourced Aggregate class.
        identifier: Unique aggregate identifier.

    Returns:
        True if a snapshot was created.

    Raises:
        IncorrectUsageError: If the aggregate is not event-sourced.
        ObjectNotFoundError: If no events exist for the given identifier.
    """
    adapter = self._require_adapter()
    if not part_of.meta_.is_event_sourced:
        raise IncorrectUsageError(
            f"`{part_of.__name__}` is not an event-sourced aggregate"
        )

    # Read ALL events (fresh reconstruction, not from existing snapshot),
    # paging the whole stream so the snapshot reflects the head state even
    # when the stream is longer than one read page.
    event_stream = self._read_stream_fully(
        f"{part_of.meta_.stream_category}-{identifier}"
    )

    if not event_stream:
        raise ObjectNotFoundError(
            f"`{part_of.__name__}` object with identifier {identifier} "
            f"does not exist."
        )

    events = [Message.deserialize(msg).to_domain_object() for msg in event_stream]
    aggregate = part_of.from_events(events)

    adapter.write_message(
        f"{part_of.meta_.stream_category}:snapshot-{identifier}",
        SNAPSHOT_TYPE,
        aggregate.to_dict(),
    )

    return True

create_snapshots

create_snapshots(part_of: type[BaseAggregate]) -> int

Create snapshots for all instances of an event-sourced aggregate.

Discovers all unique aggregate identifiers in the stream category, then creates a snapshot for each.

PARAMETER DESCRIPTION
part_of

The EventSourced Aggregate class

TYPE: type[BaseAggregate]

RETURNS DESCRIPTION
int

Number of snapshots created.

RAISES DESCRIPTION
IncorrectUsageError

If the aggregate is not event-sourced.

Source code in src/protean/infra/event_store.py
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
def create_snapshots(self, part_of: type[BaseAggregate]) -> int:
    """Create snapshots for all instances of an event-sourced aggregate.

    Discovers all unique aggregate identifiers in the stream category,
    then creates a snapshot for each.

    Args:
        part_of: The EventSourced Aggregate class

    Returns:
        Number of snapshots created.

    Raises:
        IncorrectUsageError: If the aggregate is not event-sourced.
    """
    adapter = self._require_adapter()
    if not part_of.meta_.is_event_sourced:
        raise IncorrectUsageError(
            f"`{part_of.__name__}` is not an event-sourced aggregate"
        )

    identifiers = adapter.stream_ids(part_of.meta_.stream_category)

    # With fact_events enabled, persisting also writes a
    # ``{category}-fact-{id}`` stream that shares the category prefix. Those
    # are not aggregate instances and have no ``@apply`` handler, so exclude
    # them. Scoped to fact_events so an ordinary instance whose identifier
    # happens to start with ``fact-`` is never wrongly skipped.
    if part_of.meta_.fact_events:
        identifiers = [
            identifier
            for identifier in identifiers
            if not _is_fact_stream_identifier(identifier)
        ]

    count = 0
    for identifier in identifiers:
        self.create_snapshot(part_of, identifier)
        count += 1

    return count

trace_causation

trace_causation(message_id: str | Message) -> list[Message]

Return the causation chain from the root message down to message_id.

PARAMETER DESCRIPTION
message_id

A Protean message ID string (headers.id) or a Message object.

TYPE: str | Message

RETURNS DESCRIPTION
list[Message]

Message objects in causal order, root first and the given message

list[Message]

last. Empty when message_id is a Message the store does not

list[Message]

hold.

RAISES DESCRIPTION
ValueError

message_id is a string that no message in the store has, or a Message with no headers.id. A Message the store does not hold is not looked up and raises nothing.

Source code in src/protean/infra/event_store.py
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def trace_causation(self, message_id: str | Message) -> list[Message]:
    """Return the causation chain from the root message down to ``message_id``.

    Args:
        message_id: A Protean message ID string (``headers.id``) or
            a `Message` object.

    Returns:
        `Message` objects in causal order, root first and the given message
        last. Empty when ``message_id`` is a `Message` the store does not
        hold.

    Raises:
        ValueError: ``message_id`` is a string that no message in the
            store has, or a `Message` with no ``headers.id``. A `Message`
            the store does not hold is not looked up and raises nothing.
    """
    return causation.trace_causation(self._require_adapter(), message_id)

trace_effects

trace_effects(
    message_id: str | Message, *, recursive: bool = True
) -> list[Message]

Return the messages caused by message_id.

PARAMETER DESCRIPTION
message_id

A Protean message ID string (headers.id) or a Message object.

TYPE: str | Message

recursive

If True (default), return the full subtree of effects. If False, return only direct children.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
list[Message]

Message objects caused by the given message, ordered by

list[Message]

global_position. The given message itself is not included.

RAISES DESCRIPTION
ValueError

message_id is a string that no message in the store has, or a Message with no headers.id. A Message the store does not hold is not looked up and raises nothing.

Source code in src/protean/infra/event_store.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
def trace_effects(
    self, message_id: str | Message, *, recursive: bool = True
) -> list[Message]:
    """Return the messages caused by ``message_id``.

    Args:
        message_id: A Protean message ID string (``headers.id``) or
            a `Message` object.
        recursive: If ``True`` (default), return the full subtree of
            effects.  If ``False``, return only direct children.

    Returns:
        `Message` objects caused by the given message, ordered by
        ``global_position``. The given message itself is not included.

    Raises:
        ValueError: ``message_id`` is a string that no message in the
            store has, or a `Message` with no ``headers.id``. A `Message`
            the store does not hold is not looked up and raises nothing.
    """
    return causation.trace_effects(
        self._require_adapter(), message_id, recursive=recursive
    )

build_causation_tree

build_causation_tree(
    correlation_id: str,
) -> CausationNode | None

Build a full causation tree for a correlation ID.

Returns the root node of the tree with children recursively populated.

PARAMETER DESCRIPTION
correlation_id

The correlation ID to trace.

TYPE: str

RETURNS DESCRIPTION
CausationNode | None

Root CausationNode with

CausationNode | None

children, or None if no messages found.

Source code in src/protean/infra/event_store.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
def build_causation_tree(self, correlation_id: str) -> CausationNode | None:
    """Build a full causation tree for a correlation ID.

    Returns the root node of the tree with children recursively populated.

    Args:
        correlation_id: The correlation ID to trace.

    Returns:
        Root [`CausationNode`][protean.infra.causation.CausationNode] with
        children, or ``None`` if no messages found.
    """
    return causation.build_causation_tree(self._require_adapter(), correlation_id)

verify

verify() -> IntegrityReport

Check the store's internal invariants and report every violation.

Reads the whole store and changes nothing. See protean.infra.integrity.verify for the invariants it checks.

RETURNS DESCRIPTION
IntegrityReport
IntegrityReport

the violations found. ok is True when there are none.

Source code in src/protean/infra/event_store.py
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
def verify(self) -> IntegrityReport:
    """Check the store's internal invariants and report every violation.

    Reads the whole store and changes nothing. See
    [`protean.infra.integrity.verify`][protean.infra.integrity.verify] for
    the invariants it checks.

    Returns:
        An [`IntegrityReport`][protean.infra.integrity.IntegrityReport] of
        the violations found. ``ok`` is ``True`` when there are none.
    """
    return integrity.verify(self._require_adapter())

CausationNode

Tree node used by build_causation_tree() to represent the causation hierarchy of messages sharing a correlation_id.

A node in the causation tree, representing a single message and its effects.


verify

The integrity check that domain.event_store.verify() runs. Pass it an adapter to check one that is not the domain's.

Check the store's internal invariants and report every violation.

Reads the whole store through $all, then reads the snapshot of each stream with a - in its name, other than :snapshot- streams, whose snapshot $all did not return. It changes nothing. It checks that:

  • every row carries id, stream_name and position,
  • each stream's position runs from 0 with no gaps,
  • global_position strictly increases across the store,
  • message ids are unique,
  • every row outside a :snapshot- stream has a body that is an object (data is a dict, not NULL, an array or a scalar),
  • each :snapshot- stream holds a well-formed snapshot whose _version is not past the head of its aggregate stream.

A corrupt row, such as one missing a required field, a message with a NULL or non-object body or a snapshot with a non-integer _version, is reported as a violation and never skipped. A NULL or non-object body is reported as malformed_message and still counts as its stream's position.

PARAMETER DESCRIPTION
adapter

The event store to check.

TYPE: EventStorePort

RETURNS DESCRIPTION
IntegrityReport

An IntegrityReport of the violations found. ok is True

IntegrityReport

when there are none.

Source code in src/protean/infra/integrity.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def verify(adapter: EventStorePort) -> IntegrityReport:
    """Check the store's internal invariants and report every violation.

    Reads the whole store through ``$all``, then reads the snapshot of each
    stream with a ``-`` in its name, other than ``:snapshot-`` streams,
    whose snapshot ``$all`` did not return. It changes
    nothing. It checks that:

    - every row carries ``id``, ``stream_name`` and ``position``,
    - each stream's ``position`` runs from 0 with no gaps,
    - ``global_position`` strictly increases across the store,
    - message ids are unique,
    - every row outside a ``:snapshot-`` stream has a body that is an
      object (``data`` is a dict, not NULL, an array or a scalar),
    - each ``:snapshot-`` stream holds a well-formed snapshot whose
      ``_version`` is not past the head of its aggregate stream.

    A corrupt row, such as one missing a required field, a message with a
    NULL or non-object body or a snapshot with a non-integer ``_version``,
    is reported as a violation and never skipped. A NULL or non-object body
    is reported as ``malformed_message`` and still counts as its stream's
    position.

    Args:
        adapter: The event store to check.

    Returns:
        An `IntegrityReport` of the violations found. ``ok`` is ``True``
        when there are none.
    """
    violations: list[IntegrityViolation] = []

    seen_ids: set[str] = set()
    prev_global_position: int | None = None
    # Per-stream: the last position seen (streams appear in position order
    # within the global_position-ordered scan) and the head (max) position.
    last_position: dict[str, int] = {}
    stream_head: dict[str, int] = {}
    # Per snapshot stream: the ``_version`` of its most recent snapshot.
    snapshot_version: dict[str, int] = {}

    message_count = 0
    # Scan raw rows: ``read_all`` leaves out snapshot rows and raises on
    # malformed rows, and this check must inspect both.
    for msg in _iter_all_messages(adapter):
        message_count += 1
        stream = msg.get("stream_name")
        position = msg.get("position")
        global_position = msg.get("global_position")
        message_id = msg.get("id")

        # A row read from ``$all`` always carries a ``global_position`` (the
        # read filters ``>= position``), so check monotonicity FIRST, before
        # the malformed guard can ``continue``. A row can be malformed and
        # break monotonicity at once, and verify reports every violation.
        assert global_position is not None  # read-contract guarantee (mypy)
        violation = _global_order_violation(
            stream, position, global_position, prev_global_position
        )
        if violation is not None:
            violations.append(violation)
        prev_global_position = global_position

        # A row missing any required field is itself a corruption. Flag it
        # and move on: the remaining checks need those values, and running
        # them on a half-populated row would either crash or invent a
        # spurious gap.
        violation = _missing_fields_violation(msg, stream, position)
        if violation is not None:
            violations.append(violation)
            continue

        # Past the guard the three required fields are present. Narrow them
        # for the checks below (the raw dict values are ``Any | None``).
        assert message_id is not None and stream is not None and position is not None

        violations.extend(
            _identity_and_position_violations(
                message_id,
                stream,
                position,
                seen_ids,
                last_position,
                stream_head,
            )
        )

        violation = _check_body(msg, stream, position, snapshot_version)
        if violation is not None:
            violations.append(violation)

    violations.extend(
        _unscanned_snapshot_violations(adapter, stream_head, snapshot_version, seen_ids)
    )
    violations.extend(_snapshot_violations(snapshot_version, stream_head))

    return IntegrityReport(
        message_count=message_count,
        stream_count=len(stream_head),
        violations=tuple(violations),
    )

IntegrityReport

The result of verify(), and the data payload of protean eventstore verify --json.

The result of verify.

message_count is every message scanned; stream_count is the number of streams that held at least one positioned message. ok is derived: a report is ok exactly when it carries no violations, so the two can never disagree. This shape (with ok included) is the documented, stable contract behind protean eventstore verify --json.

ok property

ok: bool

Whether the scan found no violations.

as_dict

as_dict() -> dict[str, Any]

Serialize to the --json data payload, ok included.

dataclasses.asdict omits the ok property, so build the wire payload explicitly to keep data.ok in the contract.

Source code in src/protean/infra/integrity.py
76
77
78
79
80
81
82
83
84
85
86
87
def as_dict(self) -> dict[str, Any]:
    """Serialize to the ``--json`` ``data`` payload, ``ok`` included.

    ``dataclasses.asdict`` omits the ``ok`` property, so build the wire
    payload explicitly to keep ``data.ok`` in the contract.
    """
    return {
        "ok": self.ok,
        "message_count": self.message_count,
        "stream_count": self.stream_count,
        "violations": [asdict(v) for v in self.violations],
    }

IntegrityViolation

One broken invariant that verify() found.

A single violation of the event store's internal invariants.

kind names the invariant that broke; stream and position name where the violation was found (either may be None when it is not stream- or position-specific); detail is a human-readable explanation.


ViolationKind

The kinds of IntegrityViolation. Each value is the string that --json writes.

Bases: StrEnum

The kind of an IntegrityViolation.

Each value is a stable machine token in the protean eventstore verify --json output.