# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-correlation-identity-when-an-mcp-session-is-renegotiated-mid-a2a-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-correlation-identity-when-an-mcp-session-is-renegotiated-mid-a2a-task.warrant.json
# Markdown SHA-256:   8cc73c9d3a0adcf1e7de39aa14ed20da9fd9574ebd7a66f57d702d1b40185aed
# Code AST SHA-256:   8eb0260c570461f00bbb1aff0f1bce580450e27fa0658207915cc2d3be7710ac
# Verified Classes:   CorrelationAnchorLost, TaskAnchor, TaskRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CorrelationAnchorLost(RuntimeError):
    """Raised when an MCP session re-establishment cannot re-bind a live A2A task's anchor."""
    pass


class TaskAnchor:
    """Task-scoped identity: minted once, immutable for task lifetime."""
    def __init__(self, task_id: str, trace_id: str, span_id: str):
        self.task_id = task_id
        self.trace_id = trace_id
        self.span_id = span_id


class TaskRegistry:
    """Longest-lived carrier: survives every MCP session."""
    def __init__(self):
        self._anchors = {}

    def register(self, anchor: TaskAnchor) -> None:
        self._anchors[anchor.task_id] = anchor

    def get(self, task_id: str):
        return self._anchors.get(task_id)


def on_mcp_reinitialize(new_session_id: str, live_task_id, registry: TaskRegistry) -> dict:
    """
    Called on every MCP initialize (client reconnect OR server renegotiation).
    Must re-bind the live task's anchor into the new session, or fail closed.
    """
    if live_task_id is None:
        return {"session": new_session_id}  # no live task; fresh context is fine

    anchor = registry.get(live_task_id)
    if anchor is None:
        # Live task exists but its anchor is unreachable from task-scoped state.
        # Do NOT mint a new trace parent. Do NOT drop the task id. Halt.
        raise CorrelationAnchorLost(
            f"session {new_session_id} cannot re-bind anchor for live task "
            f"{live_task_id}: anchor missing from task-scoped registry. "
            f"Proceeding would mis-parent spans and emit a phantom task record."
        )

    # Re-inject the *anchor* trace parent, not the currently active span.
    return {
        "session": new_session_id,
        "a2a-task-id": anchor.task_id,
        "traceparent": f"00-{anchor.trace_id}-{anchor.span_id}-01",
    }


def assert_terminal_event_keyed_on_anchor(task_id: str, registry: TaskRegistry) -> TaskAnchor:
    anchor = registry.get(task_id)
    if anchor is None:
        raise CorrelationAnchorLost(
            f"terminal A2A event for {task_id} has no anchor; "
            f"refusing to emit under a synthetic key."
        )
    return anchor
