# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-tree-collapse-when-memory-read-spans-are-reparented-across-async-agent-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-tree-collapse-when-memory-read-spans-are-reparented-across-async-agent-turns.warrant.json
# Markdown SHA-256:   5130a68f2d74aa8e47fffd0943f30c23972d581b114b0ecd95033f18763c9f94
# Code AST SHA-256:   656ebc6a71e157da3b0b7fd4937f3975c9118dbdc0c3e1dc78c89a4166d7e2d4
# Verified Classes:   SpanAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpanAttributionError(RuntimeError):
    """Raised when a span's tree parent disagrees with its logical-parent witness,
    or when subtree cost conservation is violated — i.e. the trace is causally degraded."""
    pass


def reconcile_turn(turn_span, children, epsilon=0.05):
    """
    turn_span: dict with keys 'span_id', 'turn_index', 'duration', 'prompt_tokens'
    children:  list of span dicts, each with 'logical_parent_id', 'turn_index',
               'duration', 'injected_context_tokens'
    Returns a dict of reconciled metrics, or raises SpanAttributionError.
    """
    quarantined = []
    for c in children:
        # Independent witness: call-site turn_index vs tree-parent turn_index.
        if c.get("turn_index") != turn_span["turn_index"]:
            quarantined.append(c)
            continue
        # Logical parent must match the tree parent it was attached under.
        if c.get("logical_parent_id") != turn_span["span_id"]:
            quarantined.append(c)

    if quarantined:
        raise SpanAttributionError(
            f"turn {turn_span['turn_index']} has {len(quarantined)} mis-parented "
            f"span(s); tree parent disagrees with logical-parent witness. "
            f"Trace is causally degraded; quarantining from cost aggregation."
        )

    child_dur = sum(c["duration"] for c in children)
    if child_dur > turn_span["duration"] * (1 + epsilon):
        raise SpanAttributionError(
            f"turn {turn_span['turn_index']} subtree cost non-conservation: "
            f"children sum to {child_dur:.3f}s > parent {turn_span['duration']:.3f}s "
            f"(epsilon={epsilon}). At least one child is foreign to this turn."
        )

    injected = sum(c.get("injected_context_tokens", 0) for c in children)
    if injected > turn_span["prompt_tokens"]:
        raise SpanAttributionError(
            f"turn {turn_span['turn_index']} injected context ({injected} tok) "
            f"exceeds rendered prompt ({turn_span['prompt_tokens']} tok): "
            f"impossible ratio indicates a memory span reparented from another turn."
        )

    return {
        "turn_index": turn_span["turn_index"],
        "attributed_child_duration": child_dur,
        "attributed_injected_tokens": injected,
        "status": "clean",
    }
