# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-an-anomalous-span-to-the-right-agent-when-trace-clusters-merge-on-shared-tool-call-signatures.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-an-anomalous-span-to-the-right-agent-when-trace-clusters-merge-on-shared-tool-call-signatures.warrant.json
# Markdown SHA-256:   261b00482849ff87d06bffd2057f5abae77ae3187fe97b70b922e29a445f44a3
# Code AST SHA-256:   03af3b7b6bdcec678f27cd66bd16c83c0ca305f05f64d0c55284ac7dfef2a4a2
# Verified Classes:   UnattributableClusterError, Span, Cluster
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class UnattributableClusterError(RuntimeError):
    """Raised when a cluster anomaly cannot be safely attributed to one agent."""
    pass


@dataclass
class Span:
    agent_id: str
    tool_name: str
    arg_schema_hash: str
    depth: int
    retry_count: int
    query_entropy: float
    window_bucket: int  # coarse time bucket for stationarity test


@dataclass
class Cluster:
    key: tuple
    spans: list = field(default_factory=list)


def attribute_anomaly(
    cluster: Cluster,
    anomaly_window: tuple,
    stationarity_tol: float = 0.35,
    entropy_tol: float = 0.25,
) -> str:
    """
    Return the agent_id to blame, or raise UnattributableClusterError.

    Invariant: attribution requires a partition homogeneous in agent_id,
    stationary in membership over the window, and comparable in argument
    distribution to the cluster's other partitions.
    """
    lo, hi = anomaly_window
    in_window = [s for s in cluster.spans if lo <= s.window_bucket <= hi]
    if not in_window:
        raise UnattributableClusterError(
            f"cluster {cluster.key} has no spans in anomaly window {anomaly_window}"
        )

    # Partition by the attribution dimension.
    partitions: dict[str, list[Span]] = {}
    for s in in_window:
        partitions.setdefault(s.agent_id, []).append(s)

    if len(partitions) == 1:
        return next(iter(partitions))

    # Stationarity: did each partition's share of the window change?
    buckets = sorted({s.window_bucket for s in in_window})
    if len(buckets) < 2:
        raise UnattributableClusterError(
            f"cluster {cluster.key} spans a single bucket; stationarity untestable"
        )
    first, last = buckets[0], buckets[-1]
    shares = {}
    for agent, spans in partitions.items():
        n_first = sum(1 for s in spans if s.window_bucket == first)
        n_last = sum(1 for s in spans if s.window_bucket == last)
        total_first = sum(1 for s in in_window if s.window_bucket == first)
        total_last = sum(1 for s in in_window if s.window_bucket == last)
        share_first = n_first / total_first if total_first else 0.0
        share_last = n_last / total_last if total_last else 0.0
        shares[agent] = abs(share_last - share_first)

    unstable = [a for a, d in shares.items() if d > stationarity_tol]
    if unstable:
        raise UnattributableClusterError(
            f"cluster {cluster.key} membership non-stationary for {unstable}; "
            "aggregate shift may be composition change, not degradation"
        )

    # Comparability: mean argument entropy across partitions.
    means = {
        a: sum(s.query_entropy for s in spans) / len(spans)
        for a, spans in partitions.items()
    }
    spread = max(means.values()) - min(means.values())
    if spread > entropy_tol:
        raise UnattributableClusterError(
            f"cluster {cluster.key} partitions non-comparable in argument "
            f"distribution (entropy spread {spread:.3f} > {entropy_tol}); "
            f"per-partition stats: {means}"
        )

    # Homogeneous, stationary, comparable: name the worst-degraded partition.
    blame = max(
        partitions,
        key=lambda a: sum(s.retry_count for s in partitions[a]) / len(partitions[a]),
    )
    return blame
