# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-semantic-convention-anomaly-detector-systematically-miss-runaway-tool-call-loops-that-straddle-a-telemetry-batch-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-semantic-convention-anomaly-detector-systematically-miss-runaway-tool-call-loops-that-straddle-a-telemetry-batch-boundary.warrant.json
# Markdown SHA-256:   79591b1d6fef5319d47f87410f28b936a2463d8094587bbd3388cbeb5f4d85a1
# Code AST SHA-256:   24ab3a847b0fdc61d7d3dfd9f639cffaf68ccd834c49e2f6304bf09f7f9d6db2
# Verified Classes:   RunawayLoopUndetectedError, Step, SessionAccumulator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class RunawayLoopUndetectedError(RuntimeError):
    """Raised when a window-local detector is asked to certify a session
    whose loop period aliases with the telemetry window cadence."""
    pass


@dataclass
class Step:
    tool_name: str
    args: dict
    result_is_noop: bool          # True for "[]", "", error, unchanged state
    input_tokens: int


@dataclass
class SessionAccumulator:
    """Session-scoped, outlives telemetry windows. The invariant: repetition
    and no-progress are session-local, never window-local."""
    canonical_sig_counts: dict = field(default_factory=dict)
    no_progress_streak: int = 0
    cumulative_input_tokens: int = 0
    last_input_tokens: int = 0

    @staticmethod
    def _canonical_sig(tool_name: str, args: dict) -> str:
        # Collapse oscillation: sort keys, sort list elements, drop volatile
        # fields so broaden/narrow variants hash identically.
        def normalize(v):
            if isinstance(v, dict):
                return tuple(sorted((k, normalize(x)) for k, x in v.items()))
            if isinstance(v, (list, tuple)):
                return tuple(sorted(normalize(x) for x in v))
            return v
        payload = repr((tool_name, normalize(args))).encode()
        return hashlib.sha256(payload).hexdigest()[:16]

    def observe(self, step: Step) -> Optional[str]:
        sig = self._canonical_sig(step.tool_name, step.args)
        self.canonical_sig_counts[sig] = self.canonical_sig_counts.get(sig, 0) + 1
        self.cumulative_input_tokens += step.input_tokens

        if step.result_is_noop:
            self.no_progress_streak += 1
        else:
            self.no_progress_streak = 0

        # Guardrail 1: no-progress streak (catches empty-result oscillation
        # even at low repetition count).
        if self.no_progress_streak >= 4:
            return f"runaway_tool_loop:no_progress_streak={self.no_progress_streak}"

        # Guardrail 2: canonicalized repetition count across the whole session.
        if self.canonical_sig_counts[sig] > 10:
            return f"runaway_tool_loop:repetition={self.canonical_sig_counts[sig]}"

        # Guardrail 3: monotone token growth with no state advance.
        if (self.no_progress_streak >= 2
                and step.input_tokens > self.last_input_tokens):
            self.last_input_tokens = step.input_tokens
            if self.cumulative_input_tokens > 200_000:
                return "runaway_tool_loop:cumulative_token_blowup"

        self.last_input_tokens = step.input_tokens
        return None


def certify_window_local_detector(window_size_s: int,
                                  min_loop_period_s: int,
                                  threshold: int) -> None:
    """A window-local detector may only be certified if the minimum loop
    period it must catch exceeds the window size. Otherwise it is
    structurally blind and must not be deployed as the sole guard."""
    if min_loop_period_s < window_size_s:
        raise RunawayLoopUndetectedError(
            f"window={window_size_s}s < min_loop_period={min_loop_period_s}s: "
            f"repetitions distribute across windows and never exceed "
            f"threshold={threshold}. Deploy session accumulator instead."
        )
