# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-provenance-graph-that-validates-its-own-poisoned-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-provenance-graph-that-validates-its-own-poisoned-memory.warrant.json
# Markdown SHA-256:   1bc395f53f095ba5d8e2c9504d872b0594be89b30cdfc6a269b3a956808a3bcd
# Code AST SHA-256:   d5baff0b3335dcce0151f2c46b87d767adc059ac0661ee63c6fd0a4ea33a4026
# Verified Classes:   ProvenanceSelfValidationError, UnboundedAncestryError, Edge, Chunk
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceSelfValidationError(RuntimeError):
    """Raised when a provenance edge was authored by the same step that authored
    the content it describes, making the edge non-evidentiary."""
    pass


class UnboundedAncestryError(RuntimeError):
    """Raised when a chunk's ancestry does not terminate at an external root
    within the allowed hop budget (laundering / second-generation edge)."""
    pass


@dataclass
class Edge:
    child_id: str
    root_id: str
    writer_id: str          # component that emitted this edge
    is_external_root: bool  # True only if root is an externally verifiable source


@dataclass
class Chunk:
    chunk_id: str
    content_writer_id: str  # component that authored the chunk body
    body: str
    edges: list = field(default_factory=list)


def verify_provenance(chunk: Chunk, max_hops: int = 3) -> float:
    if not chunk.edges:
        raise ProvenanceSelfValidationError(
            f"chunk {chunk.chunk_id}: no provenance edges, cannot attest origin"
        )

    # Invariant 1: edge-writer must be causally independent of content-writer.
    for e in chunk.edges:
        if e.writer_id == chunk.content_writer_id:
            raise ProvenanceSelfValidationError(
                f"chunk {chunk.chunk_id}: edge written by content author "
                f"{e.writer_id!r}; edge is a restatement, not an observation"
            )

    # Invariant 2: every ancestry path must terminate at an external root
    # within the hop budget; synthesized intermediate nodes do not count.
    external = sum(1 for e in chunk.edges if e.is_external_root)
    if external == 0:
        raise UnboundedAncestryError(
            f"chunk {chunk.chunk_id}: no path terminates at an external root "
            f"within {max_hops} hops; suspect laundering"
        )

    # Rooting ratio is only meaningful over independent, externally rooted edges.
    return external / len(chunk.edges)


def admit(chunk: Chunk) -> bool:
    try:
        ratio = verify_provenance(chunk)
    except (ProvenanceSelfValidationError, UnboundedAncestryError):
        return False  # quarantine; requires out-of-band re-verification
    return ratio >= 0.4
