# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-cost-attribution-silently-collapse-when-a-retried-tool-call-is-re-tagged-under-a-new-span-id.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-cost-attribution-silently-collapse-when-a-retried-tool-call-is-re-tagged-under-a-new-span-id.warrant.json
# Markdown SHA-256:   b21545c8c194548a025e40bd79b56bc1b48f4127926b680fad2aa66e96d96dc9
# Code AST SHA-256:   d3c02c67ca082058675290694b1a03c6c47aeafe67a4f48de93549da93e6e02f
# Verified Classes:   AttributionLineageError, AttemptStatus, ToolSpan, WorkUnit, WorkUnitLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class AttributionLineageError(RuntimeError):
    """Raised when a span cannot be safely attributed to a logical work unit."""
    pass


class AttemptStatus(Enum):
    OK = "OK"
    ERROR_TIMEOUT = "ERROR_TIMEOUT"
    ERROR_OTHER = "ERROR_OTHER"
    CANCELLED_BEFORE_START = "CANCELLED_BEFORE_START"


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    task_execution_id: str
    step_id: Optional[str]          # runtime-supplied; may be None if runtime regenerates
    tool_name: str
    args: dict
    status: AttemptStatus
    duration_ms: int
    token_cost: float


@dataclass
class WorkUnit:
    key: str
    attempts: list = field(default_factory=list)

    def add_attempt(self, span: ToolSpan) -> None:
        self.attempts.append(span)

    def token_cost(self) -> float:
        # sum-once: charge the first attempt that actually consumed tokens
        for a in self.attempts:
            if a.status is AttemptStatus.OK and a.token_cost > 0:
                return a.token_cost
        return 0.0

    def wall_clock_wait_ms(self) -> int:
        # physical: every attempt is real wait the user experienced
        return sum(a.duration_ms for a in self.attempts)

    def slo_population(self) -> list:
        # physical attempts, excluding only pre-start cancellations
        return [a for a in self.attempts if a.status is not AttemptStatus.CANCELLED_BEFORE_START]

    def taxonomy_tag(self) -> str:
        seq = [a.status for a in self.attempts]
        if all(s is AttemptStatus.ERROR_TIMEOUT for s in seq):
            return "RETRY_EXHAUSTION_TOTAL_FAILURE"
        if seq[-1] is AttemptStatus.OK and len(seq) > 1:
            return "RETRY_EXHAUSTION_NEAR_MISS"
        if seq[-1] is AttemptStatus.OK:
            return "SUCCESS"
        return "FAILURE_OTHER"


def args_hash(args: dict) -> str:
    return hashlib.sha256(
        repr(sorted(args.items())).encode()
    ).hexdigest()[:16]


class WorkUnitLedger:
    def __init__(self) -> None:
        self._units: dict = {}

    def ingest(self, span: ToolSpan) -> WorkUnit:
        if span.step_id is None:
            raise AttributionLineageError(
                f"span {span.span_id} has no stable step_id; cannot deduplicate "
                f"retries for task {span.task_execution_id}. Runtime must emit "
                f"step_id or idempotency_key across retry attempts."
            )
        key = f"{span.task_execution_id}:{span.step_id}:{span.tool_name}:{args_hash(span.args)}"
        unit = self._units.get(key)
        if unit is None:
            unit = WorkUnit(key=key)
            self._units[key] = unit
        unit.add_attempt(span)
        return unit

    def task_rollup(self, task_execution_id: str) -> dict:
        units = [u for u in self._units.values() if u.key.startswith(task_execution_id + ":")]
        if not units:
            raise AttributionLineageError(
                f"no work units found for task {task_execution_id}; "
                f"attribution would be silently zero"
            )
        return {
            "task_execution_id": task_execution_id,
            "total_token_cost": sum(u.token_cost() for u in units),
            "total_wall_clock_ms": sum(u.wall_clock_wait_ms() for u in units),
            "taxonomy": [u.taxonomy_tag() for u in units],
            "near_miss": any(u.taxonomy_tag() == "RETRY_EXHAUSTION_NEAR_MISS" for u in units),
        }
