# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-tagged-retention-when-a-memory-tool-s-write-and-forget-paths-disagree-on-tag-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-tagged-retention-when-a-memory-tool-s-write-and-forget-paths-disagree-on-tag-lineage.warrant.json
# Markdown SHA-256:   0c2a4f6e6db702f4cfd734fce7c0444adaae82dc7445500b8c10e8b3c3e1f1ab
# Code AST SHA-256:   0783ac46843056841315404e82ffe336c8c2d98b634168fd03dcae7e1cd27da9
# Verified Classes:   RetentionLineageError, RetentionToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class RetentionLineageError(RuntimeError):
    """Raised when a record's retention token does not match its stored provenance."""
    pass


@dataclass(frozen=True)
class RetentionToken:
    policy_id: str
    ttl_seconds: int
    provenance_hash: str
    minted_at: float


def _hash_provenance(provenance: dict) -> str:
    canonical = "|".join(f"{k}={provenance[k]}" for k in sorted(provenance))
    return hashlib.sha256(canonical.encode()).hexdigest()


def mint_token(provenance: dict, policy_registry: dict) -> RetentionToken:
    # Resolve policy ONCE, at write time, against the registry as it exists now.
    key = f"{provenance['source']}/{provenance['derivation']}/{provenance['trust']}"
    policy = policy_registry.get(key)
    if policy is None:
        raise RetentionLineageError(f"no retention policy for provenance key {key!r}")
    return RetentionToken(
        policy_id=policy["id"],
        ttl_seconds=policy["ttl"],
        provenance_hash=_hash_provenance(provenance),
        minted_at=time.time(),
    )


def forget(record: dict, live_registry: dict) -> bool:
    """
    Forget a record. Consumes the write-time token; never re-resolves from the
    live registry. Fails closed on any lineage mismatch.
    """
    token: RetentionToken | None = record.get("retention_token")
    if token is None:
        raise RetentionLineageError(
            f"record {record.get('id')!r} has no retention token; refusing to forget"
        )

    stored_hash = _hash_provenance(record["provenance"])
    if stored_hash != token.provenance_hash:
        raise RetentionLineageError(
            f"record {record.get('id')!r} provenance mutated after write: "
            f"stored={stored_hash[:12]} token={token.provenance_hash[:12]}"
        )

    # Detect registry drift: if the live registry would now resolve a different
    # policy, the record is in an indeterminate state and must be quarantined,
    # not silently forgotten under either policy.
    key = (
        f"{record['provenance']['source']}/"
        f"{record['provenance']['derivation']}/"
        f"{record['provenance']['trust']}"
    )
    live = live_registry.get(key)
    if live is not None and live["id"] != token.policy_id:
        raise RetentionLineageError(
            f"record {record.get('id')!r} policy drift: token={token.policy_id} "
            f"live={live['id']}; quarantine required"
        )

    age = time.time() - token.minted_at
    if age >= token.ttl_seconds:
        record["forgotten"] = True
        return True
    return False


if __name__ == "__main__":
    registry_v1 = {
        "peer-b/merge/unverified": {"id": "pol-unverified", "ttl": 3600},
        "peer-b/merge/verified": {"id": "pol-verified", "ttl": 90 * 86400},
    }
    registry_v2 = {
        "peer-b/merge/unverified": {"id": "pol-verified", "ttl": 90 * 86400},
        "peer-b/merge/verified": {"id": "pol-verified", "ttl": 90 * 86400},
    }
    prov = {"source": "peer-b", "derivation": "merge", "trust": "unverified"}
    rec = {"id": "r1", "provenance": prov, "retention_token": mint_token(prov, registry_v1)}
    rec["retention_token"] = RetentionToken(
        policy_id=rec["retention_token"].policy_id,
        ttl_seconds=rec["retention_token"].ttl_seconds,
        provenance_hash=rec["retention_token"].provenance_hash,
        minted_at=time.time() - 7200,  # simulate 2h elapsed
    )
    try:
        forget(rec, registry_v2)  # registry promoted; must raise, not leak
    except RetentionLineageError as e:
        print(f"quarantined: {e}")
