# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-the-divergent-tool-call-event-stream-before-committing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-the-divergent-tool-call-event-stream-before-committing.warrant.json
# Markdown SHA-256:   6950850ca1489be28b24d3e9dc0fbf5edee78a5895794b2e49e7ce990bb1bfad
# Code AST SHA-256:   ff1a4209aefc1f71caa161c871b98cea2b893320cfbb7e9ee9fb2c7997efae83
# Verified Classes:   SpanReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpanReconciliationError(RuntimeError):
    """Raised when the GenAI span tree disagrees with the model response payload."""
    pass


def reconcile_turn_before_checkpoint(
    model_response: dict,
    span_tree: dict,
    tool_result_log: dict,
) -> dict:
    """
    Gate checkpoint commit on span/event/token agreement.

    model_response: parsed assistant message with 'tool_calls' list (source of truth
                    for what the model actually emitted).
    span_tree: reconstructed parent span with 'usage' dict and 'tool_events' list.
    tool_result_log: authoritative {tool_call_id: result} map from the executor.
    """
    expected_ids = [tc["id"] for tc in model_response.get("tool_calls", [])]
    observed_ids = [ev["attributes"].get("gen_ai.tool.call.id")
                    for ev in span_tree.get("tool_events", [])]

    # Duplicate export from retrying BatchSpanProcessor: dedupe by id.
    deduped = list(dict.fromkeys(observed_ids))
    if len(deduped) != len(observed_ids):
        # duplicates are recoverable; note but do not fail
        span_tree["_deduped"] = True

    missing = [tid for tid in expected_ids if tid not in deduped]
    if missing:
        # Attempt recovery from the authoritative tool-result log.
        recoverable = [tid for tid in missing if tid in tool_result_log]
        unrecoverable = [tid for tid in missing if tid not in tool_result_log]
        if unrecoverable:
            raise SpanReconciliationError(
                f"Span tree missing tool-call events {unrecoverable} with no "
                f"tool-result fallback; checkpoint must not be committed. "
                f"usage={span_tree.get('usage')}"
            )
        # Recoverable: patch events from the log before allowing commit.
        for tid in recoverable:
            span_tree["tool_events"].append(
                {"name": "gen_ai.tool.call",
                 "attributes": {"gen_ai.tool.call.id": tid,
                                "recovered": True}}
            )

    # Token-vs-event sanity: output tokens must cover at least the observed calls.
    out_tokens = span_tree.get("usage", {}).get("gen_ai.usage.output_tokens", 0)
    if out_tokens <= 0 and expected_ids:
        raise SpanReconciliationError(
            "Non-zero tool calls but zero output tokens recorded; usage attribute "
            "was likely set before the model response finalized."
        )

    span_tree["_reconciled"] = True
    return span_tree
