# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-consensus-ordered-shared-memory-write-that-has-already-been-committed-by-a-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-consensus-ordered-shared-memory-write-that-has-already-been-committed-by-a-quorum.warrant.json
# Markdown SHA-256:   6399d778622c81a536e7ffa32b31d70fc8e6faa4e832afa055f17f6097ee4896
# Code AST SHA-256:   50b4d2026070740a4c720be28b77ba599a37344a6651f1019d7870367b81fedf
# Verified Classes:   CommittedButInapplicableError, Entry, SharedMemoryMaterializer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CommittedButInapplicableError(RuntimeError):
    """Raised when a quorum-committed entry cannot be legally applied to the
    local materialized state because its causal base no longer matches."""
    pass


@dataclass(frozen=True)
class Entry:
    key: str
    value: object
    base_version: int
    commit_index: int
    is_crdt_op: bool = False
    is_retraction: bool = False


class SharedMemoryMaterializer:
    def __init__(self) -> None:
        # key -> (version, value, retracted)
        self._state: dict[str, tuple[int, object, bool]] = {}
        self.quarantine: list[Entry] = []

    def apply(self, entry: Entry) -> None:
        current = self._state.get(entry.key)
        current_version = current[0] if current else 0
        current_retracted = current[2] if current else False

        # CRDT ops are join-defined for all reachable states: always apply.
        if entry.is_crdt_op:
            self._state[entry.key] = (
                current_version + 1,
                self._join(current[1] if current else None, entry.value),
                current_retracted,
            )
            return

        # A retraction must dominate any earlier-versioned value; applying it
        # is only legal if we have actually materialized the version it targets.
        if entry.is_retraction:
            if entry.base_version != current_version:
                self.quarantine.append(entry)
                raise CommittedButInapplicableError(
                    f"retraction of {entry.key}@v{entry.base_version} "
                    f"committed at index {entry.commit_index} cannot apply: "
                    f"local version is v{current_version}"
                )
            self._state[entry.key] = (current_version + 1, current[1], True)
            return

        # Stale-base register write: committed, ordered, but computed against a
        # state that no longer exists. Reject and quarantine; do NOT LWW-fold.
        if entry.base_version != current_version:
            self.quarantine.append(entry)
            raise CommittedButInapplicableError(
                f"stale-base write to {entry.key} (base v{entry.base_version}, "
                f"local v{current_version}) committed at index "
                f"{entry.commit_index}; quarantine and force re-read"
            )

        if current_retracted:
            self.quarantine.append(entry)
            raise CommittedButInapplicableError(
                f"write to retracted key {entry.key} at index "
                f"{entry.commit_index}; resurrection requires explicit un-retract"
            )

        self._state[entry.key] = (current_version + 1, entry.value, False)

    @staticmethod
    def _join(a: object, b: object) -> object:
        # Placeholder for the CRDT's total join; must be defined for all
        # reachable carrier values of the specific CRDT type.
        return b if a is None else a
