# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-retry-storm-metrics-from-silently-under-counting-agent-tool-failures.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-retry-storm-metrics-from-silently-under-counting-agent-tool-failures.warrant.json
# Markdown SHA-256:   531c299694e299e06f92f072c026ae51b6c7558a8e91cdb0c6092d23f0dc4fc6
# Code AST SHA-256:   7e337e3cfcd2837f6f429587a1918cbcc64a2b77030575992411d8c479c4ab24
# Verified Classes:   MetricPartitionViolation, AttemptLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class MetricPartitionViolation(RuntimeError):
    """Raised when an attempt metric cannot be attributed to a unique (logical_request_id, attempt) pair."""
    pass

@dataclass
class AttemptLedger:
    # key: (logical_request_id, attempt) -> outcome
    seen: dict = field(default_factory=dict)

    def record(self, logical_request_id: str, attempt: int, outcome: str) -> None:
        key = (logical_request_id, attempt)
        if key in self.seen:
            raise MetricPartitionViolation(
                f"duplicate attempt datapoint for {key}: "
                f"already recorded {self.seen[key]!r}, now {outcome!r} — "
                f"retry path likely reset attempt ordinal or regenerated logical_request_id"
            )
        if attempt < 1:
            raise MetricPartitionViolation(
                f"attempt ordinal {attempt} for {logical_request_id} is non-monotonic; "
                f"baggage propagation lost"
            )
        self.seen[key] = outcome

def emit_attempt_metric(ledger: AttemptLedger, logical_request_id: Optional[str],
                        attempt: Optional[int], outcome: str) -> None:
    if logical_request_id is None or attempt is None:
        # Fail closed: an orphaned retry (context evicted, handoff without baggage)
        # must not be silently counted as a fresh attempt=1 request.
        raise MetricPartitionViolation(
            "orphaned tool attempt: logical_request_id or attempt missing from baggage; "
            "refusing to emit attempt=1 to avoid under-counting retry storm"
        )
    ledger.record(logical_request_id, attempt, outcome)
