# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cost-attribution-drift-when-a-retried-tool-call-silently-forks-a-trace-s-causal-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cost-attribution-drift-when-a-retried-tool-call-silently-forks-a-trace-s-causal-chain.warrant.json
# Markdown SHA-256:   68f06cbf893a907a3b0863e68ea4a1bcb49da127489f8d84b79cb8ef75f9348a
# Code AST SHA-256:   6cd1e4bd8606957424dcd6153f5f437d6a1c3beab182ab840268c05b04156669
# Verified Classes:   UnresolvedRetryForkError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnresolvedRetryForkError(RuntimeError):
    """Raised when a parent's cost is about to be committed while a
    descendant span carries an unresolved retry_of edge. Committing
    here produces permanent cost-attribution drift."""
    pass


def attribute_parent_cost(parent_span, child_spans, server_log, window_expired):
    """
    parent_span: dict with 'span_id', 'declared_budget'
    child_spans: list of dicts, each may carry 'retry_of' -> predecessor span_id
    server_log: dict mapping span_id -> 'completed' | 'not_received' | None
    window_expired: bool, True once retry backoff + tool p99 has elapsed
    """
    unresolved = [
        c for c in child_spans
        if c.get("retry_of") and server_log.get(c["retry_of"]) is None
    ]

    if unresolved and not window_expired:
        # Defer: report an interval, never a point estimate.
        known = sum(c["cost"] for c in child_spans if c not in unresolved)
        quarantined = sum(c["cost"] for c in unresolved)
        return {
            "parent": parent_span["span_id"],
            "cost_interval": (known, known + quarantined),
            "committed": False,
            "reason": "unresolved_retry_fork",
        }

    if unresolved and window_expired:
        # Conservative resolution: treat as fork, over-attribute.
        for c in unresolved:
            c["causal_class"] = "fork_assumed"
        total = sum(c["cost"] for c in child_spans)
        return {
            "parent": parent_span["span_id"],
            "cost": total,
            "committed": True,
            "reason": "window_expired_fork_assumed",
        }

    # All retries resolved against server log.
    attributed = 0.0
    max_latency = 0.0
    for c in child_spans:
        pred = c.get("retry_of")
        if pred and server_log.get(pred) == "not_received":
            # repetition: predecessor discarded, count retry only
            attributed += c["cost"]
            max_latency = max(max_latency, c["latency"])
        elif pred and server_log.get(pred) == "completed":
            # true fork: both executions are causally real
            attributed += c["cost"]
            max_latency = max(max_latency, c["latency"])
        else:
            attributed += c["cost"]
            max_latency = max(max_latency, c["latency"])

    if attributed > parent_span["declared_budget"]:
        raise UnresolvedRetryForkError(
            f"parent {parent_span['span_id']} attributed {attributed} "
            f"exceeds declared budget {parent_span['declared_budget']} "
            f"after fork resolution; rollup would over-attribute"
        )

    return {
        "parent": parent_span["span_id"],
        "cost": attributed,
        "latency": max_latency,
        "committed": True,
        "reason": "resolved",
    }
