# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attribute-tool-call-latency-to-the-tool-and-instead-book-it-against-its-own-reasoning-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attribute-tool-call-latency-to-the-tool-and-instead-book-it-against-its-own-reasoning-budget.warrant.json
# Markdown SHA-256:   23a256c0ce9050d90357a298f4a83ae18c3d3025391ca0a03b908bec557faa1a
# Code AST SHA-256:   e8640c562afa94d3a88c201adac60b11905f2f248be29f4c018d6de285a06078
# Verified Classes:   AttributionConservationError, TurnTrace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttributionConservationError(RuntimeError):
    """Raised when a turn's parts do not reconcile to its total, or when a
    tool-latency sample cannot be causally bounded to the tool span."""


@dataclass
class TurnTrace:
    inference_ms: float
    pre_dispatch_ms: float   # parse + validate + guardrail on model-emitted args
    tool_ms: float           # transport first-write -> last-byte
    total_ms: float
    pre_dispatch_fraction_threshold: float = 0.15
    resolution_ms: float = 5.0


def reconcile_turn(trace: TurnTrace) -> str:
    parts = trace.inference_ms + trace.pre_dispatch_ms + trace.tool_ms
    if abs(parts - trace.total_ms) > trace.resolution_ms:
        raise AttributionConservationError(
            f"conservation violation: parts={parts:.1f}ms total={trace.total_ms:.1f}ms "
            f"delta={parts - trace.total_ms:.1f}ms"
        )
    if trace.total_ms <= 0:
        raise AttributionConservationError("zero-duration turn cannot be attributed")
    frac = trace.pre_dispatch_ms / trace.total_ms
    if frac > trace.pre_dispatch_fraction_threshold:
        # Pre-dispatch work is model-shaped; do not emit a tool-latency sample.
        return "unverified"
    return "tool_attributed"


def emit_tool_sample(trace: TurnTrace) -> float:
    verdict = reconcile_turn(trace)
    if verdict != "tool_attributed":
        raise AttributionConservationError(
            "refusing to emit tool-latency sample: pre-dispatch fraction "
            f"{trace.pre_dispatch_ms / trace.total_ms:.2%} exceeds bound; "
            "route gap to reasoning budget instead"
        )
    return trace.tool_ms
