# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-privacy-budget-exhaustion-against-trace-completeness-in-federated-agent-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-privacy-budget-exhaustion-against-trace-completeness-in-federated-agent-observability.warrant.json
# Markdown SHA-256:   38ad80497a7d15aed6b2e005b3b3da9a6e9f98dddf6031c314aa92e508742d24
# Code AST SHA-256:   52b9117034ba087bc74be01655bd48154f7cc1e2b24a1d1d428968e2ff9c9797
# Verified Classes:   TraceCompletenessError, ParticipantAttestation, StratumCoverage, TraceReport
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class TraceCompletenessError(RuntimeError):
    """Raised when a federated trace cannot be reconciled against budget state."""


@dataclass
class ParticipantAttestation:
    participant_id: str
    spent_epsilon: float
    epsilon_ceiling: float
    mode: str  # "noise" or "suppress"
    k: int = 1


@dataclass
class StratumCoverage:
    stratum: str
    observed: int
    expected: int

    @property
    def coverage(self) -> float:
        if self.expected <= 0:
            return 1.0
        return self.observed / self.expected


@dataclass
class TraceReport:
    topology_complete: bool
    strata: Mapping[str, StratumCoverage] = field(default_factory=dict)


def reconcile(
    report: TraceReport,
    attestations: Mapping[str, ParticipantAttestation],
    min_stratum_coverage: float = 0.90,
) -> str:
    """
    Return one of "accept", "degrade", "refuse".

    The decision keys on the JOINT condition of per-stratum coverage and
    participant budget attestation, never on aggregate completeness alone.
    """
    if not report.topology_complete:
        # A broken parent chain is an unaccounted loss, not suppression.
        raise TraceCompletenessError(
            "topology incomplete: parent_span_id chain broken; "
            "cannot attribute loss to privacy suppression"
        )

    suppressing = {
        pid: att
        for pid, att in attestations.items()
        if att.mode == "suppress"
    }

    under_covered = [
        s for s in report.strata.values()
        if s.coverage < min_stratum_coverage
    ]

    if not under_covered:
        return "accept"

    # Under-covered strata exist. Suppression can explain it; a partition cannot.
    if suppressing:
        # Guard against a participant claiming noise mode while coverage
        # collapses in the suppress-below-k shape.
        for att in suppressing:
            if att.spent_epsilon < att.epsilon_ceiling * 0.5:
                raise TraceCompletenessError(
                    f"participant {att} attests suppress mode at "
                    f"epsilon={att.spent_epsilon}/{att.epsilon_ceiling}; "
                    "suppression without budget pressure is inconsistent "
                    "and must not be accepted as privacy-driven loss"
                )
        return "degrade"

    # Under-covered, topology intact, and nobody claims suppression:
    # this is an unaccounted loss. Refuse rather than estimate.
    raise TraceCompletenessError(
        "stratum coverage below threshold with no suppression attestation: "
        f"under-covered={[s.stratum for s in under_covered]}; "
        "loss is unaccounted (partition, dedup bug, or dishonest attestation)"
    )
