# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-convention-drift-in-nested-agent-hierarchies-span-parent-rebinding-under-mid-task-subagent-re-parenting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-convention-drift-in-nested-agent-hierarchies-span-parent-rebinding-under-mid-task-subagent-re-parenting.warrant.json
# Markdown SHA-256:   230bd57e969da0eaa72269d3f20c14e425238a761942df697839cce58c82aa9f
# Code AST SHA-256:   151c2b06bcb63e4f671be64d8e41a22debb668a4053df80b4f14d4f1b0d73f00
# Verified Classes:   TraceCorrelationDrift, SpanContext, Ownership, SpanEmitter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class TraceCorrelationDrift(RuntimeError):
    """Raised when a span's parent edge disagrees with the authoritative ownership ledger."""
    pass

@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]

@dataclass(frozen=True)
class Ownership:
    child_agent: str
    owner_agent: str
    owner_span_id: str
    delegation_time: float
    warrant_signer: str

class SpanEmitter:
    def __init__(self, ledger: dict[str, Ownership]):
        self._ledger = ledger

    def start_span(self, agent: str, trace_id: str, now: float,
                   intended_parent: SpanContext) -> SpanContext:
        own = self._ledger.get(agent)
        if own is None:
            raise TraceCorrelationDrift(
                f"no ownership record for agent {agent!r}; cannot derive parent"
            )
        # Invariant: parent must be the span minted by the CURRENT owner,
        # not the request-scoped context forwarded from spawn time.
        if own.owner_span_id != intended_parent.span_id:
            raise TraceCorrelationDrift(
                f"re-parenting detected for {agent!r}: intended parent "
                f"{intended_parent.span_id} != current owner span "
                f"{own.owner_span_id} (owner={own.owner_agent!r}). "
                f"Rebind or emit span link; do not forward stale traceparent."
            )
        return SpanContext(
            trace_id=trace_id,
            span_id=f"{agent}-{now}",
            parent_span_id=own.owner_span_id,
        )

# Usage demonstrating the failure:
ledger = {
    "W": Ownership("W", "S", "a1", 100.0, "S"),  # re-tasked to S at t=100
}
emitter = SpanEmitter(ledger)
stale_parent = SpanContext("t0", "b1", "a0")  # W's spawn-time parent was C.plan (b1)
try:
    emitter.start_span("W", "t0", 101.0, stale_parent)
except TraceCorrelationDrift as e:
    print(f"guardrail fired: {e}")
