# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-discontinuity-at-the-handoff-barrier-when-span-propagation-is-lossy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-discontinuity-at-the-handoff-barrier-when-span-propagation-is-lossy.warrant.json
# Markdown SHA-256:   f7d3cb07266179ec55ea500dc58ae33bd7503cb434f18d13ef9f26da9093a168
# Code AST SHA-256:   4696264c4e652a8eeb82a39db461bdb0e003a0a859bc260542fe21245e71bf76
# Verified Classes:   CausalTraceInvalid, Span, HandoffEnvelope
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field


class CausalTraceInvalid(RuntimeError):
    """Raised when a reconstructed trace is structurally complete but causally inconsistent."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    trace_id: str
    agent: str
    start_mono: float          # monotonic clock stamped at emitting agent
    end_mono: float
    seq: int                   # per-agent monotonic sequence, stamped pre-transport
    inbound_edge_count: int = 0
    outbound_edge_count: int = 0


@dataclass
class HandoffEnvelope:
    trace_id: str
    declared_fields: dict
    undeclared_metadata: dict = field(default_factory=dict)  # survives only if schema declares it


def detect_reparenting(
    spans: dict[str, Span],
    skew_bound: float,
    envelopes: list[HandoffEnvelope],
) -> list[str]:
    """
    Return list of span_ids whose reconstructed causal edges are invalid.
    Raises CausalTraceInvalid if the trace cannot be admitted for causal reasoning.
    """
    violations: list[str] = []

    # Check 1: negative causal gap beyond skew bound.
    # For each parent->child edge, child.start must not precede parent.end by more than skew.
    for sid, child in spans.items():
        if child.parent_span_id is None:
            continue
        parent = spans.get(child.parent_span_id)
        if parent is None:
            # Orphan: detectable by naive validation, handled elsewhere.
            continue
        gap = child.start_mono - parent.end_mono
        if gap < -skew_bound:
            violations.append(sid)

    # Check 2: join arity. A fan-in node must have inbound edges == sum of fan-out outbound.
    for sid, span in spans.items():
        if span.inbound_edge_count > 1 and span.inbound_edge_count < span.outbound_edge_count:
            violations.append(sid)

    # Check 3: schema stripping. If an envelope's undeclared metadata carried a
    # causal_parent that the receiver did not honor, the resulting span is suspect.
    for env in envelopes:
        causal_hint = env.undeclared_metadata.get("causal_parent")
        if causal_hint and causal_hint not in env.declared_fields:
            # Hint existed but was not a declared field: it was stripped at the bridge.
            violations.append(f"envelope:{env.trace_id}")

    if violations:
        raise CausalTraceInvalid(
            f"trace {next(iter(spans.values())).trace_id if spans else '?'} "
            f"failed causal admission: {len(violations)} violation(s) "
            f"({sorted(set(violations))[:5]}...); "
            f"re-parenting detected across handoff barrier — quarantine from attribution/replay."
        )
    return violations
