# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-document-taint-after-a-retrieval-re-rank-and-why-does-the-sandbox-s-taint-label-silently-detach-from-the-document-bod.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-document-taint-after-a-retrieval-re-rank-and-why-does-the-sandbox-s-taint-label-silently-detach-from-the-document-bod.warrant.json
# Markdown SHA-256:   31f050594b910b7d4541195b59f3e7e33c0eb9e8f06e32475f92b8a9b77f88eb
# Code AST SHA-256:   e10bbb9e75779112af12551e7ae715080755fd3abd0e7f564c3c96d05d0146d6
# Verified Classes:   TaintProvenanceError, ContentObject, TaintTable
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintProvenanceError(RuntimeError):
    """Raised when a content object's taint label cannot be reconciled
    with the provenance set of its actual bytes."""


@dataclass(frozen=True)
class ContentObject:
    body: bytes
    source_ids: frozenset  # full contributor set, never a singleton after a merge

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


class TaintTable:
    def __init__(self):
        self._by_hash: dict[str, bool] = {}  # hash -> is_tainted

    def register(self, obj: ContentObject, is_tainted: bool) -> None:
        self._by_hash[obj.content_hash] = is_tainted

    def is_tainted(self, obj: ContentObject) -> bool:
        if obj.content_hash not in self._by_hash:
            # Unregistered bytes are maximally tainted by construction.
            return True
        return self._by_hash[obj.content_hash]


def join_taint(inputs: list[ContentObject], table: TaintTable) -> bool:
    """Least upper bound: any tainted contributor taints the output."""
    return any(table.is_tainted(i) for i in inputs)


def admit_to_sandbox(obj: ContentObject, table: TaintTable) -> None:
    """Enforce that a CLEAN claim is consistent with the object's bytes.

    A content object is admissible as CLEAN only if:
      (a) its hash is registered, and
      (b) its registered taint is False, and
      (c) its provenance set is non-empty (a merge that lost contributors
          cannot be validated).
    """
    if not obj.source_ids:
        raise TaintProvenanceError(
            f"content {obj.content_hash[:12]} has empty provenance set; "
            "cannot validate taint — refusing admission"
        )
    if obj.content_hash not in table._by_hash:
        raise TaintProvenanceError(
            f"content {obj.content_hash[:12]} produced by an uninstrumented "
            "transform (hash not registered); treating as tainted and refusing "
            "CLEAN admission"
        )
    if table.is_tainted(obj):
        raise TaintProvenanceError(
            f"content {obj.content_hash[:12]} is tainted (provenance "
            f"{sorted(obj.source_ids)}); CLEAN admission refused"
        )


def rerank_with_taint(
    inputs: list[ContentObject], table: TaintTable
) -> list[ContentObject]:
    """A taint-aware re-rank: output chunks carry the join of contributor
    taints and the union of contributor source_ids."""
    out_tainted = join_taint(inputs, table)
    merged_body = b"".join(i.body for i in inputs)
    merged_ids = frozenset().union(*(i.source_ids for i in inputs))
    out = ContentObject(body=merged_body, source_ids=merged_ids)
    table.register(out, out_tainted)
    return [out]
