# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-span-level-latency-attribution-and-reconstruct-the-decision-graph-from-causal-ordering-alone.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-span-level-latency-attribution-and-reconstruct-the-decision-graph-from-causal-ordering-alone.warrant.json
# Markdown SHA-256:   61560a3e3c2ab16931ca1a2a11691581ad092bd1a46f1b03dfca91ae29a4105c
# Code AST SHA-256:   a1e0fce2e557fa19c60c09e159f734891d49955dcf566a9a93d5154a268f7053
# Verified Classes:   AttributionInversionError, ToolSpan, DecisionCost
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class AttributionInversionError(RuntimeError):
    """Raised when a correlator attempts budget-fit selection across a retry group."""
    pass

@dataclass
class ToolSpan:
    decision_node_id: str
    attempt: int
    seq: int                 # per-process monotonic emission sequence
    duration_ms: float
    budget_ms: float
    orphan: bool = False

@dataclass
class DecisionCost:
    decision_node_id: str
    causal_child_seq: int
    total_wall_ms: float
    breached_budget: bool
    retry_group_width: int
    markers: list = field(default_factory=list)

def attribute_decision(node_id: str, spans: list[ToolSpan]) -> DecisionCost:
    if not spans:
        raise AttributionInversionError(f"no spans for decision node {node_id}")

    candidates = [s for s in spans if s.decision_node_id == node_id]
    candidates.sort(key=lambda s: s.seq)

    # Boundary guard: never resolve ambiguity by latency fit.
    if len(candidates) > 1:
        first, last = candidates[0], candidates[-1]
        total = (last.seq - first.seq) and _wall_span(candidates)
        breached = any(s.duration_ms > s.budget_ms for s in candidates)
        return DecisionCost(
            decision_node_id=node_id,
            causal_child_seq=first.seq,
            total_wall_ms=total,
            breached_budget=breached,
            retry_group_width=len(candidates),
            markers=["RetryAmbiguity", "CausalOrderAttribution"],
        )

    only = candidates[0]
    if only.duration_ms > only.budget_ms:
        return DecisionCost(
            decision_node_id=node_id,
            causal_child_seq=only.seq,
            total_wall_ms=only.duration_ms,
            breached_budget=True,
            retry_group_width=1,
            markers=["BudgetBreachPropagated"],
        )
    return DecisionCost(
        decision_node_id=node_id,
        causal_child_seq=only.seq,
        total_wall_ms=only.duration_ms,
        breached_budget=False,
        retry_group_width=1,
    )

def _wall_span(candidates: list[ToolSpan]) -> float:
    # Sum of attempt durations approximates wall-clock when attempts are serial;
    # for parallel attempts, replace with max(seq) - min(seq) mapped to time.
    return sum(s.duration_ms for s in candidates)

def plan_feasibility(costs: list[DecisionCost], ceiling_ms: float) -> bool:
    for c in costs:
        if c.breached_budget:
            # Refuse to certify feasibility on breached data.
            raise AttributionInversionError(
                f"decision {c.decision_node_id} breached budget "
                f"({c.total_wall_ms}ms, width={c.retry_group_width}); "
                f"plan feasibility cannot be certified from stale-healthy graph"
            )
    return sum(c.total_wall_ms for c in costs) <= ceiling_ms
