# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-trace-span-when-opentelemetry-genai-semantic-convention-attributes-disagree-with-the-tool-call-result-the-agent-actually.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-trace-span-when-opentelemetry-genai-semantic-convention-attributes-disagree-with-the-tool-call-result-the-agent-actually.warrant.json
# Markdown SHA-256:   53eb7bbacac53d9115a8ae0d43171d7701010e88ea0fd1759ca51dc3ed3cb498
# Code AST SHA-256:   7d4434840c07ff92ef681b8cfd55060f662ea4a7891a7e850c1520cd9a6d2b44
# Verified Classes:   SpanAttributeDivergenceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpanAttributeDivergenceError(RuntimeError):
    """Raised when a span's gen_ai.* attributes would misrepresent the observed tool result."""
    pass


def close_tool_span(span, tool_result: dict, convention_attrs: dict) -> None:
    """
    Close a gen_ai tool-call span. Abort if the result cannot be faithfully
    encoded by the GenAI semantic conventions.
    """
    degraded_markers = {"truncated", "partial", "rate_limited"}
    observed_degraded = any(tool_result.get(k) for k in degraded_markers)

    claims_ok = convention_attrs.get("status") == "OK"

    if observed_degraded and claims_ok:
        # The convention has no attribute for "successful but truncated".
        # Patching status=OK would produce a poisoned provenance record.
        span.set_attribute("status", "ERROR")
        span.set_attribute("gen_ai.tool.call.result", repr(tool_result))
        span.add_event(
            "semantic_gap",
            {"gap": "degraded_result_unrepresentable", "markers": str(observed_degraded)},
        )
        raise SpanAttributeDivergenceError(
            f"tool result {tool_result!r} is degraded but span would claim OK; "
            "span aborted to preserve replay fidelity"
        )

    for key, value in convention_attrs.items():
        span.set_attribute(key, value)
    span.set_attribute("status", "OK")
