# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-provenance-when-span-correlation-outlives-the-agent-identity-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-provenance-when-span-correlation-outlives-the-agent-identity-that-minted-it.warrant.json
# Markdown SHA-256:   2940273058a20b588f99c5cab4900150abff63a4a1bd91355b6fcb221e40fa4c
# Code AST SHA-256:   caed0a7a0a0ebcf7efd0a8b3cf19615cd35d59b3c5253c113ecaeb60e26c592d
# Verified Classes:   TaintProvenanceError, TaintRecord, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TaintProvenanceError(RuntimeError):
    """Raised when a span carries a taint label it cannot re-derive or verify."""
    pass


@dataclass(frozen=True)
class TaintRecord:
    label: str
    minting_identity: str
    observation_hash: str
    signature: str  # in production: ed25519 over (label, identity, observation_hash)


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    identity: str
    taint: TaintRecord | None
    parent_span_id: str | None


def verify_taint_at_boundary(span: Span, observed_inputs: dict[str, str]) -> None:
    """
    Enforce the provenance invariant at every identity boundary.

    A span may carry a taint label only if:
      (a) it was minted by the same identity that emitted the span, AND
      (b) the observation_hash matches an input this identity actually observed, OR
      (c) the signature verifies against the minting identity's key (cross-instance handoff).
    """
    if span.taint is None:
        return

    rec = span.taint

    # Branch (a): same-identity minting — must match an observed input.
    if rec.minting_identity == span.identity:
        observed = observed_inputs.get(rec.observation_hash)
        if observed is None:
            raise TaintProvenanceError(
                f"span {span.span_id} on trace {span.trace_id}: label {rec.label!r} "
                f"claims identity {span.identity!r} observed input "
                f"{rec.observation_hash!r}, but no such observation is recorded"
            )
        return

    # Branch (c): cross-identity handoff — signature must verify.
    expected = hashlib.sha256(
        f"{rec.label}|{rec.minting_identity}|{rec.observation_hash}".encode()
    ).hexdigest()
    if rec.signature != expected:
        raise TaintProvenanceError(
            f"span {span.span_id} on trace {span.trace_id}: label {rec.label!r} "
            f"inherited from identity {rec.minting_identity!r} into {span.identity!r} "
            f"has an unverifiable signature; refusing to treat trace continuity "
            f"as provenance continuity"
        )


def evaluate_sink(span: Span, observed_inputs: dict[str, str]) -> bool:
    """Returns True if the sink action is permitted (no unverifiable taint)."""
    try:
        verify_taint_at_boundary(span, observed_inputs)
    except TaintProvenanceError:
        # Fail-closed: unverifiable taint blocks the sink.
        return False
    return span.taint is None
