# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-attribute-span-latency-to-the-wrong-agent-step-when-async-tool-callbacks-outlive-their-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-attribute-span-latency-to-the-wrong-agent-step-when-async-tool-callbacks-outlive-their-parent-span.warrant.json
# Markdown SHA-256:   1ee0662ce5d920d7b3ebcbcde60a5e039432e74742abc33394fd7c4480807ad3
# Code AST SHA-256:   f8c421245e07adee38077c4413523fa79db4919038190d2d4d8bf2821a827c2d
# Verified Classes:   AttributionInvariantError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class AttributionInvariantError(RuntimeError):
    """Raised when span parentage or cost reconciliation is violated."""
    pass

@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    agent_id: str
    dispatched_at_ms: int
    closed_at_ms: Optional[int] = None
    frozen_parent_id: Optional[str] = None
    detached_reason: Optional[str] = None
    children: list = field(default_factory=list)

def close_step_span(
    step: Span,
    outstanding: list[Span],
    now_ms: int,
    tool_deadline_ms: int,
    trace_root_id: str,
) -> None:
    # Freeze parentage at dispatch: any child dispatched while this step was
    # open is irrevocably owned by this step, regardless of completion time.
    for child in outstanding:
        if child.frozen_parent_id is None:
            child.frozen_parent_id = step.span_id
        # If a child was already re-parented by ambient context, that is the bug.
        if child.parent_id is not None and child.parent_id != step.span_id:
            raise AttributionInvariantError(
                f"child {child.span_id} parented to {child.parent_id} "
                f"but dispatched under {step.span_id} (agent {child.agent_id})"
            )
        overdue = (now_ms - child.dispatched_at_ms) > tool_deadline_ms
        if overdue and child.closed_at_ms is None:
            # Past deadline: detach to trace root, never to ambient current span.
            child.frozen_parent_id = trace_root_id
            child.detached_reason = "tool_deadline_exceeded"
    step.closed_at_ms = now_ms

def reconcile_trace(spans: list[Span], trace_total_cost: float) -> None:
    by_parent: dict[str, float] = {}
    for s in spans:
        if s.closed_at_ms is not None and s.frozen_parent_id is not None:
            dur = s.closed_at_ms - s.dispatched_at_ms
            by_parent[s.frozen_parent_id] = by_parent.get(s.frozen_parent_id, 0.0) + dur
    for parent in spans:
        if parent.closed_at_ms is None:
            continue
        wall = parent.closed_at_ms - parent.dispatched_at_ms
        child_sum = by_parent.get(parent.span_id, 0.0)
        if child_sum > wall + 1:  # 1ms tolerance for clock granularity
            raise AttributionInvariantError(
                f"span {parent.span_id} (agent {parent.agent_id}): "
                f"children sum {child_sum}ms exceeds wall {wall}ms — "
                f"late callback re-parented onto wrong step"
            )
