# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-correlation-collapse-at-the-mcp-to-a2a-handoff-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-correlation-collapse-at-the-mcp-to-a2a-handoff-boundary.warrant.json
# Markdown SHA-256:   6068bbd38b0a10e57daa5b1ce609459bb63f588daa3f9acc27baf1974aff14ad
# Code AST SHA-256:   9f378284a45b87c80825976ca6a799e014d9cc17db3977c2590300f0bb560163
# Verified Classes:   TraceParentLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TraceParentLaunderingError(RuntimeError):
    """Raised when a child span's parent identity was reconstructed from
    ambient tracestate instead of transported as structured data."""
    pass


def assert_parentage(inbound_traceparent: str, dispatch_span_id: str,
                     child_parent_span_id: str, child_trace_id: str) -> None:
    # inbound_traceparent: "00-<trace-id>-<span-id>-<flags>"
    parts = inbound_traceparent.split("-")
    if len(parts) != 4:
        raise TraceParentLaunderingError(
            f"malformed traceparent: {inbound_traceparent!r}")
    trace_id, span_id = parts[1], parts[2]

    if child_trace_id != trace_id:
        raise TraceParentLaunderingError(
            f"trace-id drift: dispatch={trace_id} child={child_trace_id}; "
            "task re-dispatched from stale context")

    if child_parent_span_id != dispatch_span_id:
        raise TraceParentLaunderingError(
            f"parent-span-id mismatch: expected {dispatch_span_id}, "
            f"got {child_parent_span_id}; child was re-parented onto the "
            "retry envelope (span-parent laundering)")


def correlate_hop(inbound_traceparent: str, dispatch_span_id: str,
                  child_span: dict) -> None:
    assert_parentage(
        inbound_traceparent=inbound_traceparent,
        dispatch_span_id=dispatch_span_id,
        child_parent_span_id=child_span["parent_span_id"],
        child_trace_id=child_span["trace_id"],
    )
    # negative-duration clamp is forbidden; surface it
    if child_span["start_ns"] < child_span.get("parent_end_ns", 0):
        raise TraceParentLaunderingError(
            "negative parent-child duration: retry envelope absorbed the "
            "original latency; do not clamp")
