# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-trace-correlation-key-across-an-mcp-server-restart-and-an-a2a-hop-the-semantic-convention-collision-that-silent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-trace-correlation-key-across-an-mcp-server-restart-and-an-a2a-hop-the-semantic-convention-collision-that-silent.warrant.json
# Markdown SHA-256:   ba1bf34620ee441d38999150a3c01486ff7077588acc8fcd066dca50c280b912
# Code AST SHA-256:   8126e2e9d102753062cbbf30b52550e8372f86ea86c964ef8ea576a71e191bf3
# Verified Classes:   CorrelationKeyCollision, CorrelationKey, InstanceIdentity, EpisodicRecord, MemoryBackend
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import uuid
from dataclasses import dataclass, field
from typing import Optional


class CorrelationKeyCollision(RuntimeError):
    """Raised when a correlation key is reused by a distinct authoring instance
    across a restart or A2A hop, violating the instance-identity invariant."""


@dataclass(frozen=True)
class CorrelationKey:
    # Semantic convention: stable across restarts, greppable, NOT unique.
    task_hash: str
    turn_index: int

    def as_str(self) -> str:
        return f"{self.task_hash}:{self.turn_index}"


@dataclass(frozen=True)
class InstanceIdentity:
    # Process identity: unique per boot, NOT derivable from task state.
    boot_id: str = field(default_factory=lambda: uuid.uuid4().hex)

    @property
    def discriminator(self) -> str:
        return hashlib.sha256(self.boot_id.encode()).hexdigest()[:16]


@dataclass
class EpisodicRecord:
    key: CorrelationKey
    boot_discriminator: str
    checkpoint_digest: str
    writes: list[str] = field(default_factory=list)


class MemoryBackend:
    """Partitions on (correlation_key, boot_discriminator). Rejects any write
    that attempts to append to a partition owned by a different boot."""

    def __init__(self) -> None:
        self._partitions: dict[tuple[str, str], EpisodicRecord] = {}

    def open_or_resume(
        self,
        key: CorrelationKey,
        identity: InstanceIdentity,
        checkpoint_digest: str,
    ) -> EpisodicRecord:
        partition = (key.as_str(), identity.discriminator)
        existing = self._partitions.get(partition)
        if existing is None:
            rec = EpisodicRecord(
                key=key,
                boot_discriminator=identity.discriminator,
                checkpoint_digest=checkpoint_digest,
            )
            self._partitions[partition] = rec
            return rec
        # Same partition can only be resumed by the same boot (impossible after
        # restart) or by a boot presenting the exact checkpoint the partition
        # was opened with. Anything else is a cross-instance collision.
        if existing.checkpoint_digest != checkpoint_digest:
            raise CorrelationKeyCollision(
                f"key {key.as_str()!r} partition owned by boot "
                f"{existing.boot_discriminator} with checkpoint "
                f"{existing.checkpoint_digest[:8]}; caller boot "
                f"{identity.discriminator} presented "
                f"{checkpoint_digest[:8]} — refusing cross-instance append"
            )
        return existing

    def append(
        self,
        key: CorrelationKey,
        identity: InstanceIdentity,
        checkpoint_digest: str,
        entry: str,
    ) -> None:
        # Guard: any write must resolve to a partition owned by this boot, or
        # to a partition whose checkpoint matches exactly (same-boot resume).
        partition = (key.as_str(), identity.discriminator)
        rec = self._partitions.get(partition)
        if rec is None:
            raise CorrelationKeyCollision(
                f"no partition for key {key.as_str()!r} under boot "
                f"{identity.discriminator}; instance attempted to write to a "
                f"key it never opened — likely a semantic-convention collision"
            )
        if rec.checkpoint_digest != checkpoint_digest:
            raise CorrelationKeyCollision(
                f"checkpoint mismatch on append for key {key.as_str()!r}: "
                f"partition opened with {rec.checkpoint_digest[:8]}, caller "
                f"presents {checkpoint_digest[:8]}"
            )
        rec.writes.append(entry)


def handle_post_restart_turn(
    key: CorrelationKey,
    identity: InstanceIdentity,
    checkpoint_digest: str,
    backend: MemoryBackend,
    turn_text: str,
) -> EpisodicRecord:
    """Entry point for a resumed instance's turn. Demonstrates the guard:
    a restarted instance carries a NEW boot_id, so it lands in a fresh
    partition and cannot silently append to the pre-crash record."""
    try:
        rec = backend.open_or_resume(key, identity, checkpoint_digest)
        backend.append(key, identity, checkpoint_digest, turn_text)
        return rec
    except CorrelationKeyCollision as exc:
        # Surface, do not swallow: the orchestrator must reconcile the
        # pre-crash partition and the retry agent's partition explicitly.
        raise CorrelationKeyCollision(
            f"resumed turn for key {key.as_str()!r} rejected: {exc}"
        ) from exc
