# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-write-span-as-committed-only-after-its-forget-span-tombstone-is-causally-ordered-not-merely-emitted.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-write-span-as-committed-only-after-its-forget-span-tombstone-is-causally-ordered-not-merely-emitted.warrant.json
# Markdown SHA-256:   4438eda8681504e7688afa3c4aab861cbbdcb7a38c524dd3f5aa4ef1773850e7
# Code AST SHA-256:   63792aea396ad36e7274d65e0840fa7a619c411339c1d041717193dffc3a1155
# Verified Classes:   MemoryOpStatus, MemorySpan, IndeterminateMemoryState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class MemoryOpStatus(Enum):
    ENQUEUED = "ENQUEUED"
    APPLIED = "APPLIED"
    REJECTED = "REJECTED"


@dataclass
class MemorySpan:
    span_id: str
    key: str
    op: str  # "read" | "write" | "forget"
    start: float
    end: float
    status: MemoryOpStatus
    causally_after: list[str] = field(default_factory=list)
    key_version: Optional[int] = None


class IndeterminateMemoryState(RuntimeError):
    """Raised when replay cannot soundly determine a key's state."""


def replay_key_state(spans: list[MemorySpan], key: str) -> Optional[str]:
    """Reconstruct a key's state from spans, or raise if indeterminate.

    Returns 'present' or 'absent'. Raises IndeterminateMemoryState when
    causal ordering and applied-status do not uniquely determine the state.
    """
    relevant = [s for s in spans if s.key == key and s.op in ("write", "forget")]

    # Enqueued or rejected forgets are not effective; drop them from the fold.
    effective = [s for s in relevant if s.status == MemoryOpStatus.APPLIED]

    # Any non-applied write/forget leaves the key's history open.
    open_ops = [s for s in relevant if s.status == MemoryOpStatus.ENQUEUED]
    if open_ops:
        raise IndeterminateMemoryState(
            f"key {key!r} has {len(open_ops)} enqueued op(s); "
            f"cannot fold until commit status is known: "
            f"{[s.span_id for s in open_ops]}"
        )

    # Build causal edges among effective ops; detect concurrency on the key.
    by_id = {s.span_id: s for s in effective}
    has_edge = {s.span_id: set(s.causally_after) & by_id.keys() for s in effective}

    # Two effective ops on the same key with no causal path between them
    # are concurrent; timestamp order is not a substitute.
    for i, a in enumerate(effective):
        for b in effective[i + 1:]:
            if b.span_id in has_edge[a.span_id] or a.span_id in has_edge[b.span_id]:
                continue
            if a.key_version is not None and b.key_version is not None and a.key_version != b.key_version:
                continue
            raise IndeterminateMemoryState(
                f"key {key!r} has concurrent ops {a.span_id} and {b.span_id} "
                f"with no causal edge and no distinguishing version; "
                f"quarantine and query live store"
            )

    # Fold in causal order; version breaks ties when present.
    def sort_key(s: MemorySpan):
        return (s.key_version if s.key_version is not None else s.start, s.start)

    state = "absent"
    for s in sorted(effective, key=sort_key):
        state = "present" if s.op == "write" else "absent"
    return state
