# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-samples-its-own-trace-spans-under-a-federated-cost-ceiling-attribution-drift-at-the-sampling-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-samples-its-own-trace-spans-under-a-federated-cost-ceiling-attribution-drift-at-the-sampling-boundary.warrant.json
# Markdown SHA-256:   4ab12305abf2c7a9b57cb19e458764fbea56473011818e2d1076781b632d4fc5
# Code AST SHA-256:   f7153790ee5679c5f77d8c582b5686a7471dfed37d3183f985e8f5e7b3548961
# Verified Classes:   AttributionDriftError, CostWindow, FederatedBudgetController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class AttributionDriftError(RuntimeError):
    """Raised when sampled trace cost diverges from unsampled accounting beyond tolerance."""


@dataclass(frozen=True)
class CostWindow:
    instance_id: str
    observed_usd: float          # sum over spans that reached the collector
    incurred_usd: float          # unsampled accounting ledger
    sampling_probability: float | None  # None => tail-based / unexportable
    accounting_stale_s: float


class FederatedBudgetController:
    def __init__(self, ceiling_usd: float, drift_tolerance: float = 0.02,
                 max_staleness_s: float = 30.0) -> None:
        self.ceiling_usd = ceiling_usd
        self.drift_tolerance = drift_tolerance
        self.max_staleness_s = max_staleness_s

    def reconcile(self, windows: Mapping[str, CostWindow]) -> float:
        total_incurred = 0.0
        for inst, w in windows.items():
            if w.accounting_stale_s > self.max_staleness_s:
                # Fail closed: never zero-fill missing accounting.
                raise AttributionDriftError(
                    f"instance {inst} accounting stale {w.accounting_stale_s:.1f}s; "
                    "refusing to enforce ceiling against sampled data"
                )
            if w.sampling_probability is None:
                raise AttributionDriftError(
                    f"instance {inst} uses tail-based sampling with no exported "
                    "inclusion probability; observed cost is unusable for billing"
                )
            # Horvitz-Thompson reweight of the observed sample.
            reweighted = w.observed_usd / w.sampling_probability
            drift = abs(reweighted - w.incurred_usd) / max(w.incurred_usd, 1e-9)
            if drift > self.drift_tolerance:
                raise AttributionDriftError(
                    f"instance {inst} attribution drift {drift:.1%} exceeds "
                    f"tolerance {self.drift_tolerance:.1%}"
                )
            total_incurred += w.incurred_usd
        return total_incurred

    def admit(self, windows: Mapping[str, CostWindow], next_job_usd: float) -> bool:
        spent = self.reconcile(windows)
        if spent + next_job_usd > self.ceiling_usd:
            return False
        return True
