# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-span-attributes-when-an-agent-s-token-accounting-diverges-across-a-mid-task-context-compact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-span-attributes-when-an-agent-s-token-accounting-diverges-across-a-mid-task-context-compact.warrant.json
# Markdown SHA-256:   ee93cdd96ca2b4943f0fe38a74214e7e9f266a5cf5221ed14d8ca431920c61f2
# Code AST SHA-256:   f7d03d51c9dd15bb86323d8c710c53e36a6526e271468cec814afbfdc8bf5695
# Verified Classes:   FrameAmbiguousTrace, Step
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass

class FrameAmbiguousTrace(RuntimeError):
    """Raised when a span tree crosses a compaction boundary without a marker."""
    pass

@dataclass
class Step:
    index: int
    input_tokens: int
    is_compaction: bool = False

def reconcile(agent_span_id: str, steps: list[Step]) -> dict:
    if not steps:
        raise FrameAmbiguousTrace(f"agent {agent_span_id}: empty span tree")

    billed = sum(s.input_tokens for s in steps)
    compaction_steps = [s for s in steps if s.is_compaction]

    drops = [
        (steps[i - 1].input_tokens - steps[i].input_tokens)
        for i in range(1, len(steps))
        if steps[i - 1].input_tokens > 0
    ]
    max_drop_ratio = max((d / steps[i - 1].input_tokens
                          for i, d in enumerate(drops, start=1)), default=0.0)

    if max_drop_ratio > 0.5 and not compaction_steps:
        raise FrameAmbiguousTrace(
            f"agent {agent_span_id}: {max_drop_ratio:.0%} input-token drop "
            f"with no gen_ai.operation.name='compact' marker; refusing to "
            f"aggregate (billed_sum={billed} is not a valid context proxy)"
        )

    last_compaction = max((s.index for s in compaction_steps), default=-1)
    live = sum(s.input_tokens for s in steps if s.index > last_compaction)
    return {
        "agent_span_id": agent_span_id,
        "agent.task.input_tokens_billed": billed,
        "agent.context.tokens_live": live,
        "frame_boundaries": [s.index for s in compaction_steps],
    }
