# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-surviving-write-audit-lineage-depth-laundering-through-semantic-distillation-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-surviving-write-audit-lineage-depth-laundering-through-semantic-distillation-hops.warrant.json
# Markdown SHA-256:   f812f8f6ef98107f1bec252242421ae4e2889a95a69922e358b9a57709fa819e
# Code AST SHA-256:   7c1cfb9742ba745ca0ef4fe93a6142ecd2c005a67002928dfbd12b50048d8ad3
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a distillation emit carries less taint than the join of its raw inputs."""
    pass


def audit_distillation_emit(
    emitted_fact: dict,
    raw_input_episodes: list[dict],
    claim_hash_index: dict[str, set[str]],
) -> None:
    """
    Enforce: taint(emit) must be a superset of the join of taints of every
    raw episode whose claim-hash set intersects the emitted fact's claim hashes.

    raw_input_episodes must be the job's UNFILTERED read set, not its declared
    input. If the caller passes the filtered set, this check is defeated.
    """
    emitted_hashes = set(emitted_fact["claim_hashes"])
    emitted_taint = set(emitted_fact["taint"])

    contributing_taints: set[str] = set()
    echo_collisions: list[tuple[str, str]] = []

    for ep in raw_input_episodes:
        ep_hashes = set(ep["claim_hashes"])
        overlap = emitted_hashes & ep_hashes
        if not overlap:
            continue
        contributing_taints |= set(ep["taint"])
        for h in overlap:
            origins = claim_hash_index.get(h, set())
            if len(origins) > 1 and "untrusted" in origins:
                echo_collisions.append((h, ep["origin_domain"]))

    missing = contributing_taints - emitted_taint
    if missing:
        raise ProvenanceLaunderingError(
            f"emit taint {sorted(emitted_taint)} missing joined taint "
            f"{sorted(missing)} from raw inputs; echo collisions={echo_collisions}"
        )

    if echo_collisions and "untrusted" not in emitted_taint:
        raise ProvenanceLaunderingError(
            f"echo-corroborated claim hashes {echo_collisions} survived as trusted; "
            f"distillation laundered provenance"
        )
