# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-parent-child-token-attribution-when-an-agent-span-ends-before-its-async-tool-call-spans-report-usage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-parent-child-token-attribution-when-an-agent-span-ends-before-its-async-tool-call-spans-report-usage.warrant.json
# Markdown SHA-256:   33ca3d6aa4c1a4e718363c65b93b8e3b37778e1f4d324ea556f0e00b0162d12e
# Code AST SHA-256:   90be0ea6c459854bda00a2b063d4a2d56b50181b457caa091092ee5943ea092e
# Verified Classes:   UnreconciledUsageError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconciledUsageError(RuntimeError):
    """Raised when a trace's token usage cannot be attributed to a closed span tree."""
    pass


def reconcile_usage(spans: list[dict], assembly_window_s: float) -> dict:
    """
    Sum gen_ai.usage.* across a trace, refusing to zero-fill unreported spans
    and refusing to trust a tree whose children outlived the root.
    """
    root_ids = {s["span_id"] for s in spans if "parent_span_id" not in s}
    if len(root_ids) != 1:
        raise UnreconciledUsageError(
            f"expected exactly one root, found {len(root_ids)}; "
            "likely orphaned tool spans from a closed agent span"
        )

    input_tokens = 0
    output_tokens = 0
    for s in spans:
        if s.get("gen_ai.usage.reported") is False:
            # Unknown, not zero. Excluding is correct; zero-filling is a silent undercount.
            continue
        if s.get("end_time_s", 0) - s.get("start_time_s", 0) > assembly_window_s:
            raise UnreconciledUsageError(
                f"span {s['span_id']} exceeded assembly window "
                f"({assembly_window_s}s); its usage may have been dropped"
            )
        input_tokens += s.get("gen_ai.usage.input_tokens", 0)
        output_tokens += s.get("gen_ai.usage.output_tokens", 0)

    return {"input_tokens": input_tokens, "output_tokens": output_tokens}
