# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-step-level-trace-attribution-before-the-trace-itself-becomes-the-drift-signal.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-step-level-trace-attribution-before-the-trace-itself-becomes-the-drift-signal.warrant.json
# Markdown SHA-256:   b2d90986baae6cdbd227d22a94adf499bc8d86ad08d58aebe727698af54d328b
# Code AST SHA-256:   4cd10858c44a07011d9562d71f7a68296e67acab43dc415523237d7f959a95f6
# Verified Classes:   AttributionIndependenceViolation, LogicalStep, TraceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class AttributionIndependenceViolation(RuntimeError):
    """Raised when instrumentation overhead correlates with the attributed metric."""


@dataclass
class LogicalStep:
    step_id: str
    tokens: int
    wall_ms: float
    retries: int = 0


@dataclass
class TraceLedger:
    # span-level records, including retries and flush overhead
    span_tokens: Dict[str, List[int]] = field(default_factory=dict)
    span_wall_ms: Dict[str, List[float]] = field(default_factory=dict)
    flush_overhead_ms: float = 0.0


def attribute_step(step: LogicalStep, trace: TraceLedger, overhead_band: float = 0.15) -> Dict[str, float]:
    """
    Attribute cost to a logical step, guarding against instrumentation-induced drift.
    Raises if trace-ledger cost diverges from agent-ledger cost beyond the band,
    which is the signal that the trace has begun to perturb the loop.
    """
    span_tokens = sum(trace.span_tokens.get(step.step_id, []))
    agent_tokens = step.tokens
    if agent_tokens <= 0:
        raise AttributionIndependenceViolation(
            f"step {step.step_id} has non-positive agent-ledger tokens; cannot attribute"
        )
    trace_ratio = span_tokens / agent_tokens
    if abs(trace_ratio - 1.0) > overhead_band:
        # The trace is inflating (retries/flush) or deflating the step's cost.
        # Do not feed this window into the drift baseline.
        raise AttributionIndependenceViolation(
            f"step {step.step_id}: trace/agent token ratio {trace_ratio:.2f} "
            f"exceeds band {overhead_band}; attribution independence lost for this window"
        )
    return {
        "step_id": step.step_id,
        "agent_tokens": agent_tokens,
        "trace_tokens": span_tokens,
        "attributable_wall_ms": step.wall_ms,
        "instrumentation_overhead_ms": trace.flush_overhead_ms,
        "retries": step.retries,
    }


def update_drift_baseline(step: LogicalStep, trace: TraceLedger, window: List[int]) -> List[int]:
    """
    Only logical-step token counts enter the baseline. If attribution fails,
    the window is frozen rather than appended, preventing contaminated samples.
    """
    try:
        attributed = attribute_step(step, trace)
    except AttributionIndependenceViolation:
        # Freeze the baseline; the alert for this window is suppressed upstream.
        return window
    window.append(attributed["agent_tokens"])
    return window[-50:]
