# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-writes-to-memory-during-a-tool-call-that-the-harness-later-rejects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-writes-to-memory-during-a-tool-call-that-the-harness-later-rejects.warrant.json
# Markdown SHA-256:   e09a3b4397405378f2821ab83e0e305fb06b13c996e634346d75cafd65ba8a36
# Code AST SHA-256:   28b997f8201df40ecf783183b0c60c8ca6535a631b9584be49dc0f93be87451f
# Verified Classes:   PhantomWriteDivergence, RejectionAwareMemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PhantomWriteDivergence(RuntimeError):
    """Raised when a memory read returns a value whose originating write
    was rejected by the harness but never rolled back in the store."""
    pass


REJECTED = "rejected"
ACCEPTED = "accepted"


class RejectionAwareMemoryStore:
    def __init__(self):
        self._records = {}          # key -> (value, call_id)
        self._call_status = {}      # call_id -> ACCEPTED | REJECTED

    def mark_rejected(self, call_id: str) -> None:
        # Harness calls this when post-dispatch validation fails.
        # The store must record the rejection so reads can reconcile.
        self._call_status[call_id] = REJECTED

    def write(self, key: str, value: str, call_id: str) -> None:
        self._records[key] = (value, call_id)
        self._call_status.setdefault(call_id, ACCEPTED)

    def read(self, key: str) -> str:
        if key not in self._records:
            raise PhantomWriteDivergence(f"no record for key={key!r}")
        value, call_id = self._records[key]
        status = self._call_status.get(call_id, ACCEPTED)
        if status == REJECTED:
            # The write landed but the harness disowned it. Returning the
            # value would let the model reason over a phantom write.
            raise PhantomWriteDivergence(
                f"key={key!r} value={value!r} originates from rejected "
                f"call_id={call_id!r}; store must be reconciled before read"
            )
        return value


def safe_read(store: RejectionAwareMemoryStore, key: str) -> str:
    try:
        return store.read(key)
    except PhantomWriteDivergence as exc:
        # Force re-derivation rather than trusting the store.
        raise PhantomWriteDivergence(
            f"stale_write_detected key={key!r}: {exc}; "
            "agent must re-derive from primary source"
        ) from exc
