# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-forget-the-write-acknowledged-but-uncommitted-retention-boundary-in-scoped-memory-contracts.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-forget-the-write-acknowledged-but-uncommitted-retention-boundary-in-scoped-memory-contracts.warrant.json
# Markdown SHA-256:   e881f9412c21a589ae94b176d8e6250041b7cb8a1e7514757f978f52361b26ad
# Code AST SHA-256:   0a82d08f14c857b68612d49dda511c4588f97fa6f0110f3f84753f2345bb0d40
# Verified Classes:   OrphanedScopeError, RetentionViolationError, Scope, MemoryStore
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class OrphanedScopeError(RuntimeError):
    """Raised when a scope is resolved without a terminal commit/abort state."""


class RetentionViolationError(RuntimeError):
    """Raised when a record would escape its retention scope."""


@dataclass
class Scope:
    scope_id: str
    tenant: str
    retention_days: int
    lease_expires_at: float
    state: str = "open"  # open | committed | aborted
    staged_keys: list = field(default_factory=list)


class MemoryStore:
    def __init__(self):
        self._scopes: dict[str, Scope] = {}
        self._records: dict[str, dict] = {}  # key -> {scope_id, value}
        self._committed_members: set[tuple[str, str]] = set()

    def open_scope(self, scope_id: str, tenant: str, retention_days: int, lease_seconds: float = 30.0) -> Scope:
        scope = Scope(scope_id, tenant, retention_days, time.monotonic() + lease_seconds)
        self._scopes[scope_id] = scope
        return scope

    def write(self, scope_id: str, key: str, value: str) -> None:
        scope = self._scopes.get(scope_id)
        if scope is None or scope.state != "open":
            raise OrphanedScopeError(f"write to non-open scope {scope_id!r}")
        if time.monotonic() > scope.lease_expires_at:
            self._force_resolve(scope_id)
            raise OrphanedScopeError(f"scope {scope_id!r} lease expired before write")
        self._records[key] = {"scope_id": scope_id, "value": value}
        scope.staged_keys.append(key)

    def commit_scope(self, scope_id: str) -> None:
        scope = self._scopes.get(scope_id)
        if scope is None:
            raise OrphanedScopeError(f"commit of unknown scope {scope_id!r}")
        if scope.state != "open":
            raise OrphanedScopeError(f"commit of scope {scope_id!r} in state {scope.state!r}")
        scope.state = "committed"
        for key in scope.staged_keys:
            self._committed_members.add((scope_id, key))

    def _force_resolve(self, scope_id: str) -> None:
        """Lease expiry must reach a terminal state, never silent abandonment."""
        scope = self._scopes.get(scope_id)
        if scope is None or scope.state != "open":
            return
        # Abort: unstage and make direct-key reads fail, so no orphan persists.
        scope.state = "aborted"
        for key in scope.staged_keys:
            self._records.pop(key, None)

    def read(self, key: str) -> str:
        rec = self._records.get(key)
        if rec is None:
            raise KeyError(key)
        scope_id = rec["scope_id"]
        if (scope_id, key) not in self._committed_members:
            # In-window or orphaned record: not readable through the contract.
            raise RetentionViolationError(
                f"record {key!r} is not committed under scope {scope_id!r}"
            )
        return rec["value"]

    def forget_pass(self, now_days: float) -> list[str]:
        forgotten = []
        for (scope_id, key) in list(self._committed_members):
            scope = self._scopes[scope_id]
            if now_days >= scope.retention_days:
                self._records.pop(key, None)
                self._committed_members.discard((scope_id, key))
                forgotten.append(key)
        # Any record not in committed members is an anomaly, not a skip.
        for key, rec in list(self._records.items()):
            if (rec["scope_id"], key) not in self._committed_members:
                raise RetentionViolationError(
                    f"record {key!r} escaped retention scope {rec['scope_id']!r}"
                )
        return forgotten

    def audit_export(self, tenant: str) -> list[dict]:
        out = []
        for (scope_id, key) in self._committed_members:
            scope = self._scopes[scope_id]
            if scope.tenant != tenant:
                continue
            if scope.state != "committed":
                raise OrphanedScopeError(
                    f"scope {scope_id!r} reached audit in state {scope.state!r}"
                )
            out.append({"scope_id": scope_id, "key": key, "value": self._records[key]["value"]})
        return out
