# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-attribute-sampled-trace-spans-to-a-parent-agent-when-the-sampling-decision-is-made-downstream-of-the-cost-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-attribute-sampled-trace-spans-to-a-parent-agent-when-the-sampling-decision-is-made-downstream-of-the-cost-boundary.warrant.json
# Markdown SHA-256:   f8c3d57b435e2624c369519eb0c40fd76403043ec3f4e1fd6eff575041c52212
# Code AST SHA-256:   258b19340ddb78711c5db67f009b9264d056562c328ee9a9655b77b4052410bb
# Verified Classes:   AttributionBoundaryError, EmitStage, CostRecord, SamplerConfig
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from uuid import UUID
from enum import Enum


class AttributionBoundaryError(RuntimeError):
    """Raised when an instance is asked to attribute cost to a parent under conditions that violate the sampling-independence invariant."""
    pass


class EmitStage(Enum):
    WORKER = "worker"          # written by the spending agent, pre-sampling
    COLLECTOR = "collector"    # written downstream, post-sampling


@dataclass(frozen=True)
class CostRecord:
    span_id: str
    parent_key: str            # UUID or planner nonce; NOT a per-process counter
    tokens: int
    emit_stage: EmitStage
    key_is_workflow_scoped: bool


@dataclass(frozen=True)
class SamplerConfig:
    retention: float           # 0.0..1.0; <1.0 means spans can be dropped


def attribute_cost(record: CostRecord, sampler: SamplerConfig, quarantine: list) -> str:
    """
    Return the parent key this cost should be attributed to, or raise if the
    boundary conditions (C1-C3) are violated. Quarantined records are appended
    to `quarantine` and counted against total budget but not attributed.
    """
    # C1: cost must be emitted by the worker, before any sampling decision.
    if record.emit_stage is not EmitStage.WORKER and sampler.retention < 1.0:
        quarantine.append(record)
        raise AttributionBoundaryError(
            f"span {record.span_id}: cost emitted at {record.emit_stage.value} "
            f"under retention={sampler.retention}; cannot attribute post-sampling cost"
        )

    # C3: join key must be workflow-scoped, not a per-process counter.
    if not record.key_is_workflow_scoped:
        quarantine.append(record)
        raise AttributionBoundaryError(
            f"span {record.span_id}: parent_key {record.parent_key!r} is not "
            f"workflow-scoped (likely a per-process counter); refusing attribution"
        )

    # C2 holds: worker-emitted record carries parentage regardless of trace drop.
    try:
        UUID(record.parent_key)
    except ValueError:
        # Non-UUID nonce is acceptable only if the planner issued it; we cannot
        # verify issuance here, so require the caller to have set the flag.
        if not record.key_is_workflow_scoped:
            raise AttributionBoundaryError(
                f"span {record.span_id}: unverifiable parent_key {record.parent_key!r}"
            )

    return record.parent_key


def reconcile(records: list[CostRecord], sampler: SamplerConfig) -> dict:
    quarantine: list[CostRecord] = []
    attributed: dict[str, int] = {}
    for rec in records:
        try:
            parent = attribute_cost(rec, sampler, quarantine)
        except AttributionBoundaryError:
            continue  # quarantined; counted in total, excluded from attribution
        attributed[parent] = attributed.get(parent, 0) + rec.tokens

    total = sum(r.tokens for r in records)
    attributed_total = sum(attributed.values())
    quarantined_total = sum(r.tokens for r in quarantine)

    # Invariant: attributed + quarantined == total spent.
    if attributed_total + quarantined_total != total:
        raise AttributionBoundaryError(
            f"ledger invariant violated: attributed={attributed_total} + "
            f"quarantined={quarantined_total} != total={total}"
        )
    return {"attributed": attributed, "quarantined_tokens": quarantined_total}
