# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-past-its-otel-trace-baseline-without-triggering-a-policy-diff-alert-baseline-contamination-via-in-trace-retry-folding.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-past-its-otel-trace-baseline-without-triggering-a-policy-diff-alert-baseline-contamination-via-in-trace-retry-folding.warrant.json
# Markdown SHA-256:   6d35346785da12cc5216900b402ec710479ccd693c01a1d34697a51c4f3358b7
# Code AST SHA-256:   6f52c3db7b2743d3aff1074ef24a2c37cc252dba341bf76f8c7a467041aed13c
# Verified Classes:   BaselineContaminationError, RetryBudgetExceeded, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, Mapping


class BaselineContaminationError(RuntimeError):
    """Raised when a span is inadmissible for the canonical baseline."""


class RetryBudgetExceeded(RuntimeError):
    """Raised when observed retry count exceeds the declared per-step budget."""


@dataclass(frozen=True)
class Span:
    agent: str
    tool: str
    step_index: int
    duration_s: float
    retry_count: int | None  # None means the instrumentor did not emit it
    retry_budget_declared: int = 0


CANONICAL_RETRY_COUNT = 0


def admit_to_baseline(span: Span) -> tuple[str, ...]:
    """Return the baseline key for a span, or raise if the span is inadmissible.

    The canonical baseline is defined only over single-attempt observations.
    Retry-folded spans (retry_count > 0) and spans whose retry dimension was
    never emitted (retry_count is None) must not enter it.
    """
    if span.retry_count is None:
        raise BaselineContaminationError(
            f"span ({span.agent}, {span.tool}, step={span.step_index}) "
            "has no retry.count attribute; instrumentor is not emitting the "
            "dimension required for baseline comparability"
        )
    if span.retry_count != CANONICAL_RETRY_COUNT:
        # Route to the retry-partitioned baseline instead of the canonical one.
        return (span.agent, span.tool, str(span.step_index), f"retry={span.retry_count}")
    return (span.agent, span.tool, str(span.step_index), "retry=0")


def check_policy_diff(span: Span) -> None:
    """Assert the observed retry count is within the declared per-step budget.

    A non-zero retry count on a step whose declared budget is zero is a policy
    diff even when the tool sequence is unchanged, because the declared
    behavior is 'single attempt'.
    """
    observed = span.retry_count or 0
    if observed > span.retry_budget_declared:
        raise RetryBudgetExceeded(
            f"step {span.step_index} of {span.agent}.{span.tool}: "
            f"observed retry.count={observed} exceeds declared budget "
            f"{span.retry_budget_declared}; trace is not a valid canonical "
            "observation and must not update the single-attempt baseline"
        )


def ingest(spans: Iterable[Span], baseline: dict[tuple[str, ...], list[float]]) -> None:
    """Ingest spans into the partitioned baseline, failing closed on violation."""
    for span in spans:
        check_policy_diff(span)
        key = admit_to_baseline(span)
        baseline.setdefault(key, []).append(span.duration_s)
