# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-drift-score-when-otel-genai-trace-embeddings-alias-semantically-distinct-tool-call-topologies.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-drift-score-when-otel-genai-trace-embeddings-alias-semantically-distinct-tool-call-topologies.warrant.json
# Markdown SHA-256:   ac34eefef80fd5a044e92d5c2431b253d1d0c5c593bb5b6e1c770212b1605191
# Code AST SHA-256:   90e83c1349a39dd5a4aab04e1566e79edb27b3b407b0691def2287b1759ba5f4
# Verified Classes:   DriftScoreUntrustedError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DriftScoreUntrustedError(RuntimeError):
    """Raised when a low drift score is used as a verdict over an
    anomaly class the embedder cannot represent (ordering/multiplicity)."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    name: str
    start_ns: int
    attrs: str  # canonicalized attribute string


def topology_hash(spans: list[Span]) -> str:
    """Order- and multiplicity-sensitive Merkle hash over the span DAG.
    Children are hashed in start_ns order; duplicate spans hash twice."""
    by_parent: dict[str | None, list[Span]] = {}
    for s in spans:
        by_parent.setdefault(s.parent_id, []).append(s)

    def node_hash(s: Span) -> str:
        kids = sorted(by_parent.get(s.span_id, []), key=lambda k: k.start_ns)
        child_hashes = "".join(node_hash(k) for k in kids)
        payload = f"{s.name}|{s.attrs}|{child_hashes}"
        return hashlib.sha256(payload.encode()).hexdigest()

    roots = sorted(by_parent.get(None, []), key=lambda r: r.start_ns)
    return hashlib.sha256("".join(node_hash(r) for r in roots).encode()).hexdigest()


def assert_score_trustworthy(
    drift_score: float,
    threshold: float,
    topo_hash: str,
    known_topology_hashes: set[str],
    order_swap_probe_passed: bool,
    multiplicity_probe_passed: bool,
) -> None:
    """Enforce: a low drift score may not clear a structurally novel trace
    unless the embedder is proven order- and multiplicity-sensitive."""
    low_score = drift_score < threshold
    novel_structure = topo_hash not in known_topology_hashes

    if low_score and novel_structure:
        if not (order_swap_probe_passed and multiplicity_probe_passed):
            raise DriftScoreUntrustedError(
                f"low drift score {drift_score:.3f} over novel topology "
                f"{topo_hash[:12]} but embedder failed order/multiplicity "
                f"probes (order={order_swap_probe_passed}, "
                f"mult={multiplicity_probe_passed}); score is uninformative, "
                f"not exculpatory"
            )
    # High score may always escalate; low score over known structure is safe.
    return None
