# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-opentelemetry-genai-span-s-token-usage-attribute-has-been-silently-rewritten-by-a-downstream-exporter-corrupting-c.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-opentelemetry-genai-span-s-token-usage-attribute-has-been-silently-rewritten-by-a-downstream-exporter-corrupting-c.warrant.json
# Markdown SHA-256:   06b33d9a79626de2e14d7f31413d5eaa963db5880c6a5edfa391f51567e0bac7
# Code AST SHA-256:   20a152f760a7fe5c21610f7bb72a9af3c09ab31cff68257140a6754f47b5df48
# Verified Classes:   UsageProvenanceError, UsageBlock
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UsageProvenanceError(RuntimeError):
    """Raised when a GenAI span's token-usage block cannot be proven un-rewritten."""


@dataclass(frozen=True)
class UsageBlock:
    input_tokens: int
    output_tokens: int
    request_id: str
    writer: str  # component that first recorded the measurement
    digest: str  # sha256 of (input, output, request_id, writer)

    @classmethod
    def record(cls, input_tokens: int, output_tokens: int, request_id: str, writer: str) -> "UsageBlock":
        payload = f"{input_tokens}:{output_tokens}:{request_id}:{writer}".encode()
        return cls(input_tokens, output_tokens, request_id, writer,
                   hashlib.sha256(payload).hexdigest())

    def verify(self) -> bool:
        payload = f"{self.input_tokens}:{self.output_tokens}:{self.request_id}:{self.writer}".encode()
        return hashlib.sha256(payload).hexdigest() == self.digest


def reconcile_handoff(source: UsageBlock, received: UsageBlock,
                      expected_writer: str) -> None:
    if received.writer != expected_writer:
        raise UsageProvenanceError(
            f"usage block writer mismatch: expected {expected_writer!r}, "
            f"got {received.writer!r} — downstream processor rewrote measurement"
        )
    if not received.verify():
        raise UsageProvenanceError(
            f"usage block digest invalid for request {received.request_id!r}: "
            "attributes were mutated after span end"
        )
    if (received.input_tokens, received.output_tokens) != (
            source.input_tokens, source.output_tokens):
        raise UsageProvenanceError(
            f"usage value drift for {received.request_id!r}: "
            f"{source.input_tokens}/{source.output_tokens} -> "
            f"{received.input_tokens}/{received.output_tokens}"
        )


def accept_handoff(source: UsageBlock, received: UsageBlock,
                   expected_writer: str) -> UsageBlock:
    reconcile_handoff(source, received, expected_writer)
    return received
