# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-reconstruction-across-delegated-sub-agents-as-a-lossy-compression-problem-rather-than-a-replay-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-reconstruction-across-delegated-sub-agents-as-a-lossy-compression-problem-rather-than-a-replay-problem.warrant.json
# Markdown SHA-256:   4c1dcf7c3c6145792b8ee788a3fb04ea43cfa8ced92f3ed4017f3b86076b4566
# Code AST SHA-256:   97f219d4f4dd14f0de7118bc5eaeaad346935b3eaf2e15761db8c8c6bcc18dfe
# Verified Classes:   TraceReconstructionError, Span, DelegationBound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceReconstructionError(RuntimeError):
    """Raised when a merged trace cannot satisfy causal-predecessor integrity."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    runtime_id: str            # which process/agent emitted this span
    start_logical: int         # logical clock, NOT wall time
    end_logical: int
    attributes: dict = field(default_factory=dict)


@dataclass
class DelegationBound:
    child_runtime_id: str
    declared_p99_first_span_latency: int   # in logical ticks
    attempts_reported: int                 # child's self-reported attempt count


def merge_delegated_trace(
    parent_spans: list[Span],
    child_spans: list[Span],
    bound: DelegationBound,
) -> list[Span]:
    """
    Merge child spans into parent trace under compression semantics.

    Rejects the merge if any child span lacks a resolvable causal predecessor
    in the merged set, or if a delegation gap exceeds the child's declared
    first-span latency bound without a matching attempt record.
    """
    merged = {s.span_id: s for s in parent_spans}
    for s in child_spans:
        merged[s.span_id] = s

    # Invariant 1: every span must have a resolvable causal predecessor,
    # or be an explicit root. Flattened forwards violate this.
    for s in child_spans:
        if s.parent_span_id is None:
            if s.attributes.get("root_reason") != "explicit_root":
                raise TraceReconstructionError(
                    f"span {s.span_id} from runtime {s.runtime_id} has no "
                    f"parent pointer and is not an explicit root; "
                    f"delegation hop was likely flattened during forward"
                )
        elif s.parent_span_id not in merged:
            raise TraceReconstructionError(
                f"span {s.span_id} references parent {s.parent_span_id} "
                f"which is absent from merged set; causal chain broken"
            )

    # Invariant 2: delegation gaps must be accounted for by attempt records.
    delegation_spans = [s for s in parent_spans
                        if s.attributes.get("kind") == "delegation"
                        and s.attributes.get("child_runtime") == bound.child_runtime_id]
    for d in delegation_spans:
        child_first = min(
            (s.start_logical for s in child_spans
             if s.runtime_id == bound.child_runtime_id),
            default=None,
        )
        if child_first is None:
            continue
        gap = child_first - d.start_logical
        reported_attempts = sum(
            1 for s in child_spans
            if s.runtime_id == bound.child_runtime_id
            and s.attributes.get("kind") == "tool_call"
        )
        if gap > bound.declared_p99_first_span_latency and reported_attempts < bound.attempts_reported:
            raise TraceReconstructionError(
                f"delegation {d.span_id} shows {gap}-tick gap before first "
                f"child span, exceeding declared p99 "
                f"({bound.declared_p99_first_span_latency}); child reported "
                f"{bound.attempts_reported} attempts but only "
                f"{reported_attempts} spans emitted — suppressed retry or "
                f"unaccounted interval; refusing to attribute latency"
            )

    return list(merged.values())
