# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-distributed-trace-linkage-when-a-subagent-re-emits-its-parent-s-span-context-after-a-context-window-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-distributed-trace-linkage-when-a-subagent-re-emits-its-parent-s-span-context-after-a-context-window-compaction.warrant.json
# Markdown SHA-256:   b2d1794a1aa76d4212306d34694d7260f4cedf0101e1c55ebde4d366a3331042
# Code AST SHA-256:   101b4f5380f5c5325b46c5f2382a59481aa9ff34290018dae66517ac18293546
# Verified Classes:   SpanLinkageError, SpanContext, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass

class SpanLinkageError(RuntimeError):
    """Raised when a child span's parent reference or flags violate the linkage invariant."""
    pass

@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    trace_flags: int          # 0x01 = sampled
    checksum: str             # sha256 of trace_id|span_id|trace_flags

    @staticmethod
    def make(trace_id: str, span_id: str, trace_flags: int) -> "SpanContext":
        raw = f"{trace_id}|{span_id}|{trace_flags}".encode()
        return SpanContext(trace_id, span_id, trace_flags,
                           hashlib.sha256(raw).hexdigest())

    def verify(self) -> None:
        raw = f"{self.trace_id}|{self.span_id}|{self.trace_flags}".encode()
        if hashlib.sha256(raw).hexdigest() != self.checksum:
            raise SpanLinkageError(
                f"span context checksum mismatch for trace {self.trace_id}: "
                "context was paraphrased or mutated across the compaction boundary"
            )

@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    trace_flags: int
    start_ns: int
    end_ns: int | None = None

def emit_child_span(parent: Span, ctx: SpanContext) -> Span:
    """Emit a child span, enforcing the linkage invariant at resume time."""
    ctx.verify()  # reject paraphrased tokens outright

    if ctx.trace_flags != parent.trace_flags:
        raise SpanLinkageError(
            f"trace_flags divergence: parent 0x{parent.trace_flags:02x} "
            f"vs child 0x{ctx.trace_flags:02x} on trace {ctx.trace_id}; "
            "child sampler overrode parent sampling decision"
        )

    if parent.end_ns is not None and parent.end_ns < time.time_ns():
        # Parent is closed; a child edge would dangle. Convert to link,
        # do not fabricate a parent-child relationship.
        raise SpanLinkageError(
            f"parent span {parent.span_id} closed at {parent.end_ns} "
            f"before child emission; emit as span link, not child"
        )

    return Span(
        trace_id=ctx.trace_id,
        span_id=f"child-{ctx.span_id[-6:]}",
        parent_span_id=ctx.span_id,
        trace_flags=ctx.trace_flags,
        start_ns=time.time_ns(),
    )
