# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-correlation-drift-when-a-retried-tool-call-reuses-a-span-id-but-commits-a-different-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-correlation-drift-when-a-retried-tool-call-reuses-a-span-id-but-commits-a-different-side-effect.warrant.json
# Markdown SHA-256:   28a46645bc46757bd3221115e29aa57569021d0ff20e93103849b95b3b573755
# Code AST SHA-256:   2dff6a61ca7cc5b516f624d1b6b75aa8dcf844e3f42d4af0d0f1c576b5a2830a
# Verified Classes:   TraceCorrelationDrift, AttestedEffect, CommittedEffect
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class TraceCorrelationDrift(RuntimeError):
    """Raised when span-attested effects and committed effects disagree."""


@dataclass(frozen=True)
class AttestedEffect:
    span_id: str
    idempotency_key: str
    arguments: dict

    def fingerprint(self) -> str:
        payload = json.dumps(self.arguments, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class CommittedEffect:
    idempotency_key: str
    arguments: dict

    def fingerprint(self) -> str:
        payload = json.dumps(self.arguments, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(payload.encode()).hexdigest()


def reconcile(
    attested: list[AttestedEffect],
    committed: list[CommittedEffect],
) -> None:
    """Enforce: every committed effect has exactly one matching span, and vice versa.

    Matching is on (arguments_fingerprint, idempotency_key), never on span_id
    alone, because span reuse across re-planned retries is the drift vector.
    """
    attested_keys = {(a.fingerprint(), a.idempotency_key) for a in attested}
    committed_keys = {(c.fingerprint(), c.idempotency_key) for c in committed}

    orphan_effects = committed_keys - attested_keys
    phantom_effects = attested_keys - committed_keys

    if orphan_effects:
        # A charge committed with no span attesting it: the retry-reuse case.
        raise TraceCorrelationDrift(
            f"{len(orphan_effects)} committed effect(s) have no matching span: "
            f"{sorted(orphan_effects)}. A retried tool call likely reused a span ID "
            f"while minting a new idempotency key and re-planned arguments."
        )
    if phantom_effects:
        # A span attests an effect that never committed: the inverse drift.
        raise TraceCorrelationDrift(
            f"{len(phantom_effects)} span(s) attest an effect that never committed: "
            f"{sorted(phantom_effects)}. Trace asserts causality the ledger denies."
        )


def guarded_tool_retry(
    prior_attempt: AttestedEffect,
    retry_arguments: dict,
    new_span_id: str,
    new_key: str,
) -> AttestedEffect:
    """Decide whether a retry is a re-attempt (span reuse) or a new operation (fresh span)."""
    if prior_attempt.arguments == retry_arguments:
        # Byte-identical: legitimate re-attempt. Reuse span and key; effect boundary dedups.
        return AttestedEffect(
            span_id=prior_attempt.span_id,
            idempotency_key=prior_attempt.idempotency_key,
            arguments=retry_arguments,
        )
    # Arguments changed: this is a NEW logical operation. Refuse to reuse the span.
    if new_span_id == prior_attempt.span_id:
        raise TraceCorrelationDrift(
            f"Retry re-planned arguments under reused span {new_span_id!r}. "
            f"Arguments {prior_attempt.arguments} -> {retry_arguments}. "
            f"Mint a fresh child span and a fresh idempotency key."
        )
    return AttestedEffect(
        span_id=new_span_id,
        idempotency_key=new_key,
        arguments=retry_arguments,
    )
