# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-acknowledgement-as-provisional-until-provenance-is-reconciled.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-acknowledgement-as-provisional-until-provenance-is-reconciled.warrant.json
# Markdown SHA-256:   d1052547d1034bc6e62db0b81a98f788fac104fdc8ce0177cba88705756c5267
# Code AST SHA-256:   ecfd7eae2ef56fb51952a3e3246c817aa450da6726dddba2df67aecb979bfb4a
# Verified Classes:   UncommittedProvenanceError, Provenance, MemoryRecord, ProvenanceAwareMemory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UncommittedProvenanceError(RuntimeError):
    """Raised when a derivation is attempted from a record whose provenance
    tuple is not closed, or when a forget reveals a dangling derivation."""
    pass


@dataclass
class Provenance:
    source: str
    confidence: float
    record_id: Optional[str] = None
    superseded_by: Optional[str] = None

    def is_closed(self) -> bool:
        return (
            self.source is not None
            and self.record_id is not None
            and self.superseded_by is None
            and 0.0 < self.confidence <= 1.0
        )


@dataclass
class MemoryRecord:
    key: str
    value: str
    provenance: Provenance
    committed: bool = False


class ProvenanceAwareMemory:
    def __init__(self) -> None:
        self._store: dict[str, MemoryRecord] = {}

    def write(self, record: MemoryRecord) -> str:
        # Acknowledgement attests to storage only; committed stays False
        # until a read confirms provenance closure.
        rid = f"m_{len(self._store):04x}"
        record.provenance.record_id = rid
        self._store[rid] = record
        return rid

    def read(self, record_id: str) -> MemoryRecord:
        rec = self._store.get(record_id)
        if rec is None:
            raise UncommittedProvenanceError(
                f"record {record_id} does not resolve; cannot treat as committed"
            )
        if not rec.provenance.is_closed():
            raise UncommittedProvenanceError(
                f"record {record_id} has open provenance "
                f"(superseded_by={rec.provenance.superseded_by}); provisional only"
            )
        rec.committed = True
        return rec

    def derive(self, source_id: str, key: str, value: str) -> str:
        # Derivation must re-read and verify the source before citing it.
        source = self.read(source_id)
        if source.provenance.superseded_by is not None:
            raise UncommittedProvenanceError(
                f"cannot derive from superseded record {source_id}"
            )
        derived = MemoryRecord(
            key=key,
            value=value,
            provenance=Provenance(
                source=source_id,
                confidence=source.provenance.confidence * 0.9,
            ),
        )
        return self.write(derived)

    def forget(self, record_id: str) -> None:
        rec = self._store.get(record_id)
        if rec is None:
            raise UncommittedProvenanceError(
                f"forget on {record_id} returned not_found; "
                f"audit all derivations citing this id"
            )
        if not rec.committed:
            raise UncommittedProvenanceError(
                f"forget on {record_id} targets an uncommitted record; "
                f"its derivations are dangling by construction"
            )
        rec.provenance.superseded_by = "forgotten"
