# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-non-monotonic-token-accounting-when-genai-spans-are-emitted-from-resumed-and-retried-agent-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-non-monotonic-token-accounting-when-genai-spans-are-emitted-from-resumed-and-retried-agent-turns.warrant.json
# Markdown SHA-256:   8c5eee3c2dcef7f300c352d12e9ec92bb27bdc95d40646d0979294a97d39b71c
# Code AST SHA-256:   6efee9f5808825485cc632812fff32e1283dbf18f7242590cb8a6cc2a37f2dad
# Verified Classes:   TurnAccountingReconciliationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TurnAccountingReconciliationError(RuntimeError):
    """Raised when a resumed agent turn cannot be reconciled against a persisted turn ID."""


def resume_turn(checkpoint: dict, emitted_spans: list[dict]) -> dict:
    turn_id = checkpoint.get("agent.turn.id")
    if turn_id is None:
        # Cannot safely attribute spans; do not mint a fresh ID silently.
        raise TurnAccountingReconciliationError(
            "checkpoint missing agent.turn.id; refusing to resume with derived trace-rooted ID"
        )

    retried = [s for s in emitted_spans if s.get("agent.tool.retry") is True]
    billable = [s for s in emitted_spans if s.get("agent.tool.retry") is not True]

    for span in billable:
        if span.get("agent.turn.id") != turn_id:
            raise TurnAccountingReconciliationError(
                f"span {span.get('span_id')} carries turn {span.get('agent.turn.id')!r}, "
                f"expected {turn_id!r}; delta-mode sum would be unsound"
            )
        if span.get("gen_ai.usage.cumulative") is True:
            raise TurnAccountingReconciliationError(
                f"span {span.get('span_id')} reports cumulative usage; "
                "delta-mode aggregation would double-count across retries"
            )

    turn_total = sum(
        s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0)
        for s in billable
    )
    retry_tax = sum(
        s.get("gen_ai.usage.input_tokens", 0) + s.get("gen_ai.usage.output_tokens", 0)
        for s in retried
    )
    return {"turn_id": turn_id, "billable_total": turn_total, "resume_tax": retry_tax}
