# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-memory-events-from-desynchronizing-from-the-memory-store-they-instrument.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-memory-events-from-desynchronizing-from-the-memory-store-they-instrument.warrant.json
# Markdown SHA-256:   089cd7f8b61eadd0f4a2e232d60a300cfd55334990d22b9d6e9c8f6522125112
# Code AST SHA-256:   74d86260b8bf59b604e8bb7d8e23794ccc056864e6d9762fae291fc33e760876
# Verified Classes:   MemoryEventIntegrityError, MemoryEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import time


class MemoryEventIntegrityError(RuntimeError):
    """Raised when a memory event cannot be reconciled with store commit state."""
    pass


@dataclass
class MemoryEvent:
    operation: str                      # "read" | "write" | "forget"
    record_id: str
    content_hash: Optional[str] = None
    commit_token: Optional[str] = None  # store-issued; None => not committed
    commit_seq: Optional[int] = None    # store monotonic sequence
    outcome: str = "not_committed"      # "committed" | "not_committed" | "failed"
    predicate_unresolved: bool = False  # for forget-by-predicate
    wall_ts: float = field(default_factory=time.time)


def emit_write_event(record_id: str, content_hash: str,
                     commit_token: Optional[str],
                     commit_seq: Optional[int]) -> MemoryEvent:
    """Emit a write event. Must be called AFTER the store acknowledges the upsert."""
    if commit_token is None or commit_seq is None:
        # The write did not commit. This is a legal, first-class event:
        # it records the attempt without asserting state.
        return MemoryEvent(
            operation="write", record_id=record_id, content_hash=content_hash,
            commit_token=None, commit_seq=None, outcome="not_committed",
        )
    return MemoryEvent(
        operation="write", record_id=record_id, content_hash=content_hash,
        commit_token=commit_token, commit_seq=commit_seq, outcome="committed",
    )


def fold_events_to_state(events: list[MemoryEvent]) -> dict[str, MemoryEvent]:
    """Reconstruct store state from events. Folds by commit_seq, never wall_ts."""
    for e in events:
        if e.outcome == "committed" and (e.commit_token is None or e.commit_seq is None):
            raise MemoryEventIntegrityError(
                f"event claims committed but lacks commit_token/commit_seq: {e}"
            )
        if e.operation == "forget" and e.predicate_unresolved and e.outcome == "committed":
            raise MemoryEventIntegrityError(
                f"committed forget event has unresolved predicate; cannot fold: {e}"
            )
    committed = [e for e in events if e.outcome == "committed"]
    if any(e.commit_seq is None for e in committed):
        raise MemoryEventIntegrityError("committed event missing commit_seq")
    committed.sort(key=lambda e: e.commit_seq)
    state: dict[str, MemoryEvent] = {}
    for e in committed:
        if e.operation == "write":
            state[e.record_id] = e
        elif e.operation == "forget":
            state.pop(e.record_id, None)
    return state


def assert_replay_matches_live(replayed: dict[str, MemoryEvent],
                               live_ids: set[str]) -> None:
    """Guardrail: event-derived state must equal live store key set."""
    replayed_ids = set(replayed.keys())
    if replayed_ids != live_ids:
        only_replay = replayed_ids - live_ids
        only_live = live_ids - replayed_ids
        raise MemoryEventIntegrityError(
            f"event stream diverged from live store: "
            f"replay_only={only_replay} live_only={only_live}"
        )
