# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-provenance-valid-memory-entry-whose-retrieval-was-authorized-by-a-stale-capability-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-provenance-valid-memory-entry-whose-retrieval-was-authorized-by-a-stale-capability-warrant.warrant.json
# Markdown SHA-256:   8246d1d046607b2ae1c4d4b9a6dba1f5ce269e4ab49f1642137ec208b2bf804f
# Code AST SHA-256:   ef7c8d9e8bb1454dfdb97c2b280b8de8e26bae7d6b3ccd62e59198139290dc98
# Verified Classes:   WarrantStaleRetrievalError, LaunderingCandidateError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class WarrantStaleRetrievalError(RuntimeError):
    """Raised when a provenance-valid memory entry is read under a warrant
    that does not cover the requested key's namespace, or when a write-back
    narrows scope below its source key namespaces (laundering candidate)."""
    pass


class LaunderingCandidateError(WarrantStaleRetrievalError):
    """Raised when a distilled record's declared scope is a strict subset of
    the union of its source entries' key namespaces."""
    pass


def resolve_namespace(key: str, known_namespaces: set[str]) -> str:
    matches = [ns for ns in known_namespaces if key == ns or key.startswith(ns + ":")]
    if not matches:
        raise WarrantStaleRetrievalError(f"unresolvable key namespace: {key}")
    # most-specific namespace wins; ambiguity => fail closed
    matches.sort(key=len, reverse=True)
    if len(matches) > 1 and len(matches[0]) == len(matches[1]):
        raise WarrantStaleRetrievalError(f"ambiguous namespace for key: {key}")
    return matches[0]


def eligible_for_read(entry, requested_key, reader_warrant, known_namespaces) -> bool:
    if not entry.signature_valid():
        raise WarrantStaleRetrievalError(f"signature invalid: {entry.id}")
    ns = resolve_namespace(requested_key, known_namespaces)
    if not reader_warrant.covers(ns):
        # provenance valid, authorization stale -> distinct event class
        raise WarrantStaleRetrievalError(
            f"warrant-stale: reader warrant {reader_warrant.id} does not cover {ns}"
        )
    return True


def commit_distillation(distilled, source_entries, known_namespaces) -> None:
    source_ns = {resolve_namespace(e.key, known_namespaces) for e in source_entries}
    distilled_ns = resolve_namespace(distilled.key, known_namespaces)
    if not source_ns.issubset({distilled_ns}) and any(
        not distilled_ns.startswith(s) for s in source_ns
    ):
        raise LaunderingCandidateError(
            f"distilled scope {distilled_ns} narrower than sources {source_ns}"
        )
    distilled.commit()
