# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-has-silently-corrupted-genai-tool-call-lineage-across-an-otel-instrumented-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-has-silently-corrupted-genai-tool-call-lineage-across-an-otel-instrumented-agent-handoff.warrant.json
# Markdown SHA-256:   bdd18fef1528155f09c0b6f28bc15f38317717bf1c45776872f9757c6c4eac71
# Code AST SHA-256:   5a835cd31a5ee5a2ff43682461b641c9903e5359e5b1faa80831dba8e79a3b1c
# Verified Classes:   LineageTruncationError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class LineageTruncationError(RuntimeError):
    """Raised when a GenAI lineage-bearing span attribute is truncated or
    fails digest verification, so lineage reconstruction must fail closed."""


def reconstruct_tool_call(span_attrs: dict[str, Any]) -> dict[str, Any]:
    call_id = span_attrs.get("gen_ai.tool.call.id")
    if not call_id:
        raise LineageTruncationError(
            "span missing gen_ai.tool.call.id; cannot anchor lineage"
        )

    raw_args = span_attrs.get("gen_ai.tool.call.arguments")
    recorded_digest = span_attrs.get("gen_ai.tool.call.arguments.digest")
    truncated = span_attrs.get("gen_ai.tool.call.arguments.truncated", False)

    if raw_args is None:
        raise LineageTruncationError(
            f"call {call_id}: arguments attribute absent, not reconstructable"
        )

    if truncated:
        # A truncation sentinel means the value is known-incomplete.
        # Fail closed rather than parse a partial payload.
        raise LineageTruncationError(
            f"call {call_id}: arguments flagged truncated; "
            "content is untrusted, refuse to parse"
        )

    if recorded_digest is None:
        # No digest means we cannot distinguish complete from silently
        # truncated content. Structural validity is not content validity.
        raise LineageTruncationError(
            f"call {call_id}: no content digest; truncation status unknowable"
        )

    actual_digest = hashlib.sha256(raw_args.encode("utf-8")).hexdigest()
    if actual_digest != recorded_digest:
        raise LineageTruncationError(
            f"call {call_id}: digest mismatch "
            f"(recorded={recorded_digest[:12]} actual={actual_digest[:12]}); "
            "attribute content diverged from emission"
        )

    try:
        args = json.loads(raw_args)
    except json.JSONDecodeError as exc:
        # Do NOT fall back to {} — that launders corruption into lineage.
        raise LineageTruncationError(
            f"call {call_id}: arguments not valid JSON despite digest match: {exc}"
        ) from exc

    return {"call_id": call_id, "arguments": args, "verified": True}
