# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-span-boundary-in-genai-observability-cost-attribution-when-per-agent-token-accounting-diverges-from-per-tenan.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-span-boundary-in-genai-observability-cost-attribution-when-per-agent-token-accounting-diverges-from-per-tenan.warrant.json
# Markdown SHA-256:   fc5b8fb6c0db9878690c389b51952373e6346cead3e6f0efa8c0aed8ea8d225d
# Code AST SHA-256:   f5ed36fa85fea7e9ca0bdcec364bdec97e9a14c171f7aa19564bb3f63e586745
# Verified Classes:   OrphanedAttributionError, RollupWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class OrphanedAttributionError(RuntimeError):
    """Raised when per-agent token totals exceed per-tenant totals via a synthetic bucket."""


@dataclass(frozen=True)
class RollupWindow:
    window_id: str
    per_agent_tokens: int
    per_tenant_tokens: int
    synthetic_tenant_tokens: int
    synthetic_tenant_agent_cardinality: int
    total_tokens: int


def reconcile_attribution(
    window: RollupWindow,
    synthetic_ratio_tolerance: float = 0.001,
    cardinality_tolerance: int = 25,
) -> None:
    if window.total_tokens <= 0:
        raise OrphanedAttributionError(
            f"window {window.window_id} has non-positive total_tokens={window.total_tokens}"
        )

    residual = window.per_agent_tokens - window.per_tenant_tokens
    synthetic_ratio = window.synthetic_tenant_tokens / window.total_tokens

    # Benign: no synthetic bucket growth, residual within aggregation-order noise.
    if synthetic_ratio <= synthetic_ratio_tolerance and residual <= 0:
        return

    # Benign: negative residual is genuine loss, not orphaned attribution.
    if residual < 0 and synthetic_ratio <= synthetic_ratio_tolerance:
        return

    if (
        residual > 0
        and synthetic_ratio > synthetic_ratio_tolerance
        and window.synthetic_tenant_agent_cardinality > cardinality_tolerance
    ):
        raise OrphanedAttributionError(
            "orphaned span boundary crossed in window "
            f"{window.window_id}: residual={residual} tokens, "
            f"synthetic_ratio={synthetic_ratio:.4%} (tol {synthetic_ratio_tolerance:.2%}), "
            f"synthetic_agent_cardinality={window.synthetic_tenant_agent_cardinality} "
            f"(tol {cardinality_tolerance}). Suspect mutable-context reset before "
            "async span flush; route to context-propagation owner, not billing."
        )

    # Residual positive but synthetic bucket small: aggregation-order or double-count.
    if residual > 0 and synthetic_ratio <= synthetic_ratio_tolerance:
        raise OrphanedAttributionError(
            f"window {window.window_id}: positive residual={residual} without synthetic "
            "bucket growth — suspect agent-path double-count, not orphaned spans."
        )


def run_reconciliation(windows: list[RollupWindow]) -> list[str]:
    failures: list[str] = []
    for w in windows:
        try:
            reconcile_attribution(w)
        except OrphanedAttributionError as exc:
            failures.append(str(exc))
    return failures
