# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-trace-correlation-when-a-model-span-re-enters-a-tool-span-under-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-trace-correlation-when-a-model-span-re-enters-a-tool-span-under-retry.warrant.json
# Markdown SHA-256:   c9771803216434ab02becaa20d9915d42704d65fcfa27a4543bb750df5a98690
# Code AST SHA-256:   d73587dec0faa4bce6912b0e489507dee21188eafa89398526e4f8e2905b4ab5
# Verified Classes:   TraceCorrelationForkError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TraceCorrelationForkError(RuntimeError):
    """Raised when a retry re-opens a span from root instead of captured parent."""


@dataclass(frozen=True)
class SpanContext:
    correlation_id: str
    parent_span_id: str | None
    attempt_epoch: int


def open_retry_span(
    captured: SpanContext | None,
    root_correlation_id: str,
    layer: str,
) -> SpanContext:
    # Invariant: a correlation ID is minted only at the task root.
    # Any retry below root MUST re-open from the captured parent tuple.
    if captured is None:
        if layer != "root":
            raise TraceCorrelationForkError(
                f"layer={layer} attempted to mint correlation_id={root_correlation_id!r} "
                "from root during a retry; parent context was not captured. "
                "This forks the trace and duplicates downstream tool spans."
            )
        return SpanContext(root_correlation_id, None, 0)

    if captured.correlation_id != root_correlation_id:
        raise TraceCorrelationForkError(
            f"correlation mismatch: captured={captured.correlation_id!r} "
            f"root={root_correlation_id!r} at layer={layer}"
        )

    # Re-open from captured tuple; increment epoch, never re-mint the ID.
    return SpanContext(
        correlation_id=captured.correlation_id,
        parent_span_id=captured.parent_span_id,
        attempt_epoch=captured.attempt_epoch + 1,
    )


def idempotency_key(correlation_id: str, tool_name: str, canonical_args: str) -> str:
    return hashlib.sha256(
        f"{correlation_id}|{tool_name}|{canonical_args}".encode()
    ).hexdigest()


def execute_tool_with_replay_guard(
    ctx: SpanContext,
    tool_name: str,
    canonical_args: str,
    seen_keys: set[str],
) -> str:
    key = idempotency_key(ctx.correlation_id, tool_name, canonical_args)
    if key in seen_keys:
        # Replay under same correlation ID: dedupe, do not re-execute.
        return f"deduped:{key}"
    seen_keys.add(key)
    return f"executed:{key}"
