# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-stitching-has-silently-mis-joined-spans-across-federated-agents-under-semantic-convention-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-stitching-has-silently-mis-joined-spans-across-federated-agents-under-semantic-convention-drift.warrant.json
# Markdown SHA-256:   430d14b6673c700927a9b5761fe25fe27be8cdd5bf2640ccacb39c00f3fe0bb3
# Code AST SHA-256:   8ee637aa616302e5d8bfe92714680ee860e1738c9673581e07b608a65681002d
# Verified Classes:   TraceStitchError, DispatchRecord, ChildSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TraceStitchError(RuntimeError):
    """Raised when a federated span cannot be causally joined without inference."""


@dataclass(frozen=True)
class DispatchRecord:
    subtask_id: str          # dispatcher-minted, opaque, injective over live subtasks
    recipient_agent: str
    payload_hash: str        # sha256 of the exact payload handed to the child


@dataclass(frozen=True)
class ChildSpan:
    span_id: str
    session_id: str
    parent_span_id: str | None
    subtask_id: str | None   # copied verbatim from payload, or None if model regenerated
    received_payload_hash: str


def stitch_child(
    span: ChildSpan,
    dispatch_log: dict[str, DispatchRecord],
) -> str:
    """
    Return the verified parent span id for a child span, or raise.

    Invariant: an edge is admissible only if it keys on a dispatcher-minted
    subtask_id AND the child's received payload hash matches the dispatch
    record. Semantic attributes (task.label, session.id) are never used to
    infer a parent.
    """
    if span.parent_span_id is not None:
        return span.parent_span_id  # explicit causal token, trust it

    if span.subtask_id is None:
        # Child regenerated its identity instead of copying it. We cannot
        # verify the join, so we refuse rather than fuzzy-match on labels.
        raise TraceStitchError(
            f"span {span.span_id} in session {span.session_id} arrived with no "
            f"dispatcher-minted subtask_id; label-based join would be "
            f"unverified inference"
        )

    record = dispatch_log.get(span.subtask_id)
    if record is None:
        raise TraceStitchError(
            f"span {span.span_id} cites subtask_id {span.subtask_id!r} with no "
            f"dispatch record; join is exchange-unverifiable"
        )

    if record.payload_hash != span.received_payload_hash:
        raise TraceStitchError(
            f"span {span.span_id} subtask_id {span.subtask_id!r} payload hash "
            f"mismatch: dispatched {record.payload_hash[:12]} but child received "
            f"{span.received_payload_hash[:12]}; likely session.id collision across "
            f"concurrent branches"
        )

    # Verified: dispatcher minted the id and the child provably received that payload.
    return f"subtask:{span.subtask_id}"


def payload_hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()
