# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-span-attribute-that-a-downstream-auditor-must-reconstruct-from-partial-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-span-attribute-that-a-downstream-auditor-must-reconstruct-from-partial-trace-context.warrant.json
# Markdown SHA-256:   bae1314f9bbbc3d89b7590a076fe235725834808c73c78bc078cff6c1f73108b
# Code AST SHA-256:   9c23a90f020ffac85a643b693606d1a320a13db1ae167d4b39213a8916335939
# Verified Classes:   TaintWarrantError, Observation, TaintAttribute
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaintWarrantError(RuntimeError):
    """Raised when a propagated taint attribute cannot be reconstructed by an auditor."""
    pass


@dataclass
class Observation:
    content: bytes
    origin_label: str
    content_hash: str = field(init=False)

    def __post_init__(self):
        self.content_hash = "sha256:" + hashlib.sha256(self.content).hexdigest()


@dataclass
class TaintAttribute:
    trust: str
    origin_label: str
    content_hash: Optional[str]
    summary_truncated_at: Optional[int] = None
    full_length: Optional[int] = None
    taint_unverifiable: bool = False


def propagate_taint(obs: Observation, summary_limit: int = 200) -> TaintAttribute:
    """Producer-side: emit a taint attribute for an observation."""
    truncated_at = min(summary_limit, len(obs.content)) if len(obs.content) > summary_limit else None
    return TaintAttribute(
        trust="trusted" if obs.origin_label.endswith("_kb") else "untrusted",
        origin_label=obs.origin_label,
        content_hash=obs.content_hash,
        summary_truncated_at=truncated_at,
        full_length=len(obs.content),
    )


def auditor_clear_action(
    taint: TaintAttribute,
    resolve_hash,  # callable: hash -> Optional[bytes]
) -> bool:
    """
    Auditor-side: decide whether to clear the action.
    Fails closed unless the taint label is a warrant, not an annotation.
    """
    if taint.taint_unverifiable:
        raise TaintWarrantError(
            f"taint explicitly marked unverifiable for origin={taint.origin_label}"
        )

    if taint.content_hash is None:
        raise TaintWarrantError(
            f"taint attribute for origin={taint.origin_label} carries no content hash; "
            "auditor cannot re-derive label and must not treat as warrant"
        )

    resolved = resolve_hash(taint.content_hash)
    if resolved is None:
        raise TaintWarrantError(
            f"content hash {taint.content_hash} unresolvable (index rotated?); "
            f"producer label trust={taint.trust} cannot be verified"
        )

    # Truncation boundary check: if the producer truncated before the full
    # observation, the label derivation may depend on unseen bytes.
    if taint.summary_truncated_at is not None and taint.full_length is not None:
        if taint.summary_truncated_at < taint.full_length:
            # Label derived from URL prefix is still checkable, but any
            # content-derived label is not. Treat as warrant only if the
            # label is purely origin-based.
            if not taint.origin_label:
                raise TaintWarrantError(
                    "truncated observation with no origin label; "
                    "decision-relevant region may lie past truncation boundary"
                )

    return taint.trust == "trusted"
