# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-parent-span-s-token-ledger-before-emitting-a-child-span-or-per-node-cost-attribution-silently-double-counts-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-parent-span-s-token-ledger-before-emitting-a-child-span-or-per-node-cost-attribution-silently-double-counts-cache.warrant.json
# Markdown SHA-256:   0809bee67a062fdc09918ea70cc81b349221c8c92552ecb61663fae4b1f5666a
# Code AST SHA-256:   0299178feeec76af882cb48538ffca7190311676675a9fff044f618af0fbbba6
# Verified Classes:   AttributionReconciliationError, SpanUsage, SubtreeLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class AttributionReconciliationError(RuntimeError):
    """Raised when a child span claims cached-prefix tokens whose origin span
    is not registered in the trace, or when a fresh-token owner is ambiguous."""
    pass

@dataclass
class SpanUsage:
    span_id: str
    parent_id: str | None
    start_ns: int
    prompt_tokens_total: int
    prompt_tokens_cached: int
    completion_tokens: int
    prefix_hash: str

@dataclass
class SubtreeLedger:
    fresh_by_prefix: dict[str, str] = field(default_factory=dict)  # hash -> owning span_id
    fresh_tokens: int = 0
    cache_referenced_tokens: int = 0
    completion_tokens: int = 0

def reconcile_subtree(spans: list[SpanUsage]) -> SubtreeLedger:
    """Reconcile a closed subtree. First span (by start_ns) presenting a
    prefix_hash owns its fresh tokens; later spans with the same hash
    contribute only cache-referenced tokens."""
    ledger = SubtreeLedger()
    for s in sorted(spans, key=lambda x: x.start_ns):
        fresh = s.prompt_tokens_total - s.prompt_tokens_cached
        if s.prompt_tokens_cached > 0:
            owner = ledger.fresh_by_prefix.get(s.prefix_hash)
            if owner is None:
                # Cache hit with no known materialization in this subtree:
                # the origin span is missing or out of trace scope.
                raise AttributionReconciliationError(
                    f"span {s.span_id} reports {s.prompt_tokens_cached} cached "
                    f"tokens for prefix {s.prefix_hash[:8]} but no ancestor span "
                    f"materialized that prefix; refusing to attribute."
                )
            if owner == s.span_id:
                raise AttributionReconciliationError(
                    f"span {s.span_id} is both origin and cache-referencer for "
                    f"prefix {s.prefix_hash[:8]}; prefix_hash collision."
                )
            ledger.cache_referenced_tokens += s.prompt_tokens_cached
        else:
            # This span materialized the prefix; it owns the fresh tokens.
            if s.prefix_hash in ledger.fresh_by_prefix:
                raise AttributionReconciliationError(
                    f"two spans claim fresh materialization of prefix "
                    f"{s.prefix_hash[:8]}: {ledger.fresh_by_prefix[s.prefix_hash]} "
                    f"and {s.span_id}; cannot partition cost."
                )
            ledger.fresh_by_prefix[s.prefix_hash] = s.span_id
            ledger.fresh_tokens += fresh
        ledger.completion_tokens += s.completion_tokens
    return ledger

def prefix_hash(system_prompt: str, task: str) -> str:
    return hashlib.sha256((system_prompt + "\x00" + task).encode()).hexdigest()
