# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-tier-promotion-poisoning-when-episodic-to-semantic-distillation-outruns-decay.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-tier-promotion-poisoning-when-episodic-to-semantic-distillation-outruns-decay.warrant.json
# Markdown SHA-256:   a333301c6f665b5b4df0ad3b72045ac391bc6219834494feba707bd6b2de8574
# Code AST SHA-256:   32b2c083c427f54f67f1485638a7aaa58b1c4be737e270311311f23a6968ec2e
# Verified Classes:   PromotionPoisoningError, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class PromotionPoisoningError(RuntimeError):
    """Raised when a semantic promotion would launder a single root into a belief."""


@dataclass
class Trace:
    trace_id: str
    source_type: str          # "direct_observation" | "tool_response_verified" | "user_statement" | "derived_from_memory"
    derived_from: list[str] = field(default_factory=list)


INDEPENDENT_ROOTS = {"direct_observation", "tool_response_verified", "user_statement"}


def distinct_roots(cluster: Iterable[Trace], index: dict[str, Trace]) -> set[str]:
    roots: set[str] = set()
    stack = [t.trace_id for t in cluster]
    seen: set[str] = set()
    while stack:
        tid = stack.pop()
        if tid in seen:
            continue
        seen.add(tid)
        node = index.get(tid)
        if node is None:
            raise PromotionPoisoningError(f"dangling provenance reference: {tid}")
        if node.source_type in INDEPENDENT_ROOTS:
            roots.add(tid)
        else:
            stack.extend(node.derived_from)
    return roots


def promote(cluster: list[Trace], index: dict[str, Trace], threshold: int) -> dict:
    roots = distinct_roots(cluster, index)
    if len(roots) < threshold:
        raise PromotionPoisoningError(
            f"promotion refused: cluster size={len(cluster)} but distinct_roots={len(roots)} "
            f"< threshold={threshold}; provenance graph is star-shaped (single-root echo)."
        )
    confidence = min(1.0, len(roots) / threshold) * 0.9
    return {"distinct_roots": sorted(roots), "confidence": confidence}


if __name__ == "__main__":
    idx = {
        "e1": Trace("e1", "tool_response_verified"),                 # the one real root
        "e2": Trace("e2", "derived_from_memory", ["e1"]),
        "e3": Trace("e3", "derived_from_memory", ["e1"]),
        "e4": Trace("e4", "derived_from_memory", ["e1"]),
        "e5": Trace("e5", "derived_from_memory", ["e1"]),
    }
    try:
        promote(list(idx.values()), idx, threshold=5)
    except PromotionPoisoningError as exc:
        print(f"BLOCKED: {exc}")
