# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-shared-memory-write-rather-than-propagate-it-provenance-freshness-divergence-in-multi-agent-memory-sto.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-shared-memory-write-rather-than-propagate-it-provenance-freshness-divergence-in-multi-agent-memory-sto.warrant.json
# Markdown SHA-256:   b4dadfe6fc1a788dd00277893883f21dd9776da031a6db1bf87e060c987c9f00
# Code AST SHA-256:   73916c9e3c67a95ed315f47993a07ddbbdb429772aa7ebb99c4609c12dc64e31
# Verified Classes:   StaleDerivationError, UnverifiableProvenanceError, Write, SharedMemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleDerivationError(RuntimeError):
    """Raised when a provenance-valid write is derived from a superseded root."""
    pass


class UnverifiableProvenanceError(RuntimeError):
    """Raised when a provenance chain cannot be walked to a source-grounded node."""
    pass


MAX_CHAIN_DEPTH = 8


@dataclass
class Write:
    entity: str
    attribute: str
    value: object
    writer_id: str
    consumed_epoch: int          # epoch of the fact consumed, NOT emission time
    chain: list = field(default_factory=list)  # list of parent write ids
    source_grounded: bool = False


class SharedMemoryStore:
    def __init__(self):
        self.writes: dict[str, Write] = {}
        self.head_epoch: dict[tuple[str, str], int] = {}
        self.quarantine: list[tuple[Write, str]] = []
        self.quarantine_budget: dict[str, int] = {}
        self.QUARANTINE_LIMIT = 5

    def _walk_root_epoch(self, write: Write, depth: int = 0) -> int:
        if depth > MAX_CHAIN_DEPTH:
            raise UnverifiableProvenanceError(
                f"chain depth exceeded at {write.entity}.{write.attribute}"
            )
        if write.source_grounded:
            return write.consumed_epoch
        if not write.chain:
            raise UnverifiableProvenanceError(
                f"derived write {write.entity}.{write.attribute} has no chain"
            )
        root_epochs = []
        for parent_id in write.chain:
            parent = self.writes.get(parent_id)
            if parent is None:
                raise UnverifiableProvenanceError(f"missing parent {parent_id}")
            root_epochs.append(self._walk_root_epoch(parent, depth + 1))
        return min(root_epochs)

    def commit(self, write: Write, provenance_valid: bool) -> str:
        key = (write.entity, write.attribute)
        if not provenance_valid:
            self.quarantine.append((write, "invalid_provenance"))
            return "rejected"
        try:
            root_epoch = self._walk_root_epoch(write)
        except UnverifiableProvenanceError:
            self.quarantine.append((write, "unverifiable_provenance"))
            return "quarantined"
        head = self.head_epoch.get(key, 0)
        if root_epoch < head:
            # atomic check-and-quarantine: head read inside commit
            self.quarantine.append((write, "stale_derivation"))
            self.quarantine_budget[write.writer_id] = (
                self.quarantine_budget.get(write.writer_id, 0) + 1
            )
            if self.quarantine_budget[write.writer_id] > self.QUARANTINE_LIMIT:
                raise StaleDerivationError(
                    f"writer {write.writer_id} exceeded quarantine budget; "
                    f"force cold-restart of context"
                )
            return "quarantined"
        self.writes[f"{write.entity}.{write.attribute}@{write.consumed_epoch}"] = write
        if write.source_grounded:
            self.head_epoch[key] = max(head, write.consumed_epoch)
        return "committed"

    def reconcile(self, write: Write, new_head: int) -> str:
        if write.consumed_epoch >= new_head:
            return self.commit(write, provenance_valid=True)
        raise StaleDerivationError(
            f"re-derivation required: consumed_epoch={write.consumed_epoch} "
            f"< head={new_head}"
        )
