# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-span-and-its-parent-model-invocation-span-disagree-on-retry-iden.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-span-and-its-parent-model-invocation-span-disagree-on-retry-iden.warrant.json
# Markdown SHA-256:   a07e4ffe53d72ec2e8d1f39e5ce39ef3c948d8d37add880a196af1b903794be8
# Code AST SHA-256:   271da09a06e8ea1dbd2bde8776bb1116c1e3e922d80b8d4964b6e2614f6d5586
# Verified Classes:   StaleGroundingError, SpanAttrs
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class StaleGroundingError(RuntimeError):
    """Raised when a tool result cannot be bound to the active model attempt."""


@dataclass(frozen=True)
class SpanAttrs:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str                       # "chat" | "execute_tool"
    attempt: Optional[int]               # tracer-owned, monotonic per model attempt
    tool_call_id: Optional[str] = None   # model-issued, NOT unique across attempts
    tool_result_digest: Optional[str] = None
    response_id: Optional[str] = None


def result_digest(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def reconcile_tool_result(
    model_span: SpanAttrs,
    tool_span: SpanAttrs,
    *,
    active_attempt: int,
    active_grounding: dict[str, str],   # tool_call_id -> digest already accepted
) -> str:
    """Validate that a tool result may ground the active model attempt.

    Returns the digest to record. Raises StaleGroundingError on any
    correlation failure rather than silently accepting.
    """
    if model_span.operation != "chat" or tool_span.operation != "execute_tool":
        raise StaleGroundingError(
            f"unexpected span operations: {model_span.operation!r}/{tool_span.operation!r}"
        )

    # Invariant 1: attempt discriminator must exist on BOTH spans.
    if model_span.attempt is None or tool_span.attempt is None:
        raise StaleGroundingError(
            "gen_ai.attempt missing on model or tool span; result is unverified, not valid"
        )

    # Invariant 2: the tool span must belong to the active model attempt.
    if tool_span.attempt != active_attempt:
        raise StaleGroundingError(
            f"tool span attempt {tool_span.attempt} != active attempt {active_attempt}"
        )

    # Invariant 3: parentage alone is insufficient; require attempt match too.
    if tool_span.parent_span_id != model_span.span_id:
        raise StaleGroundingError(
            f"tool span parent {tool_span.parent_span_id} != model span {model_span.span_id}"
        )

    # Invariant 4: call-id collisions must be resolved by digest, not overwritten.
    if tool_span.tool_call_id is None or tool_span.tool_result_digest is None:
        raise StaleGroundingError(
            "tool span missing tool_call_id or tool_result_digest"
        )

    prior = active_grounding.get(tool_span.tool_call_id)
    if prior is not None and prior != tool_span.tool_result_digest:
        raise StaleGroundingError(
            f"digest mismatch for call_id {tool_span.tool_call_id!r}: "
            f"prior {prior} vs incoming {tool_span.tool_result_digest}"
        )

    return tool_span.tool_result_digest
