# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-causal-trace-stitching-when-a-delegated-subtask-s-span-parent-is-a-synthetic-re-entry-point-rather-than-the-original.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-causal-trace-stitching-when-a-delegated-subtask-s-span-parent-is-a-synthetic-re-entry-point-rather-than-the-original.warrant.json
# Markdown SHA-256:   3917dabf6cda807ed7d8e9320b7017484911c0051023be104926a42a63f9c73f
# Code AST SHA-256:   9566b7ac9e233a7d2e960d47f23403c1667f0f76bcf11fed2ef6c395bf7de80c
# Verified Classes:   TraceContinuityError, Checkpoint, HandoffLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceContinuityError(RuntimeError):
    """Raised when a resumed agent cannot re-attach to its causal trace parent."""


@dataclass
class Checkpoint:
    task_id: str
    episodic_state: dict
    # Must be persisted at suspension time; None means the checkpoint is
    # trace-blind and the resume path cannot legally emit child spans.
    last_traceparent: Optional[str] = None  # "00-<trace_id>-<span_id>-<flags>"


@dataclass
class HandoffLog:
    def lookup_traceparent(self, task_id: str) -> Optional[str]:
        # Orchestrator-side record of the handoff span that originated the task.
        return self._entries.get(task_id)

    _entries: dict = None

    def __post_init__(self):
        if self._entries is None:
            self._entries = {}


def resume_agent(checkpoint: Checkpoint, handoff_log: HandoffLog) -> str:
    """
    Return the traceparent that post-resume spans must use as their parent.
    Fails closed rather than minting a synthetic root.
    """
    if checkpoint.last_traceparent is not None:
        # Happy path: checkpoint carried the causal edge.
        return checkpoint.last_traceparent

    # Fallback: consult the orchestrator's handoff log for the originating span.
    recovered = handoff_log.lookup_traceparent(checkpoint.task_id)
    if recovered is not None:
        return recovered

    # Neither the checkpoint nor the handoff log can supply a parent.
    # Minting a synthetic root here would silently rewire the causal DAG.
    raise TraceContinuityError(
        f"cannot re-attach trace for task {checkpoint.task_id!r}: "
        f"checkpoint has no last_traceparent and handoff log has no "
        f"originating span; refusing to fabricate a synthetic root"
    )


def emit_resumed_span(checkpoint: Checkpoint, handoff_log: HandoffLog) -> dict:
    parent = resume_agent(checkpoint, handoff_log)  # raises if unrecoverable
    trace_id, span_id, flags = parent.split("-")[1:]
    return {
        "trace_id": trace_id,
        "parent_span_id": span_id,
        "trace_flags": flags,
        "task_id": checkpoint.task_id,
    }
