# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sampled-decision-trace-as-non-attributable-when-span-level-cost-aggregation-crosses-a-retried-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sampled-decision-trace-as-non-attributable-when-span-level-cost-aggregation-crosses-a-retried-tool-call.warrant.json
# Markdown SHA-256:   ccde6a2378baa75d2e1486915f66f12b03ae2569d70c5e1e6b033faf86be1163
# Code AST SHA-256:   a6c051f7501ed853892fb4fabbaf8ac0106ebb0061a4cfda0fb3e80382f9293e
# Verified Classes:   TraceAttributionError, AttemptRecord, TraceAggregation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TraceAttributionError(RuntimeError):
    """Raised when a sampled trace cannot be safely used as an accounting or eval record."""


@dataclass
class AttemptRecord:
    logical_op_id: str
    attempt_index: int
    tokens_in: int
    tokens_out: int
    retained_in_trace: bool
    produced_scored_output: bool = False


@dataclass
class TraceAggregation:
    trace_id: str
    attempts: list[AttemptRecord] = field(default_factory=list)


def compute_logical_op_id(tool_name: str, normalized_args: str, parent_reasoning_node: str) -> str:
    h = hashlib.sha256()
    h.update(tool_name.encode())
    h.update(b"\x00")
    h.update(normalized_args.encode())
    h.update(b"\x00")
    h.update(parent_reasoning_node.encode())
    return h.hexdigest()


def aggregate_cost_and_eval(
    agg: TraceAggregation,
    executor_attempt_counts: dict[str, int],
) -> dict:
    """
    executor_attempt_counts is the durable ground truth written by the executor,
    keyed by logical_op_id -> total attempts issued (regardless of sampling).
    """
    by_op: dict[str, list[AttemptRecord]] = {}
    for a in agg.attempts:
        by_op.setdefault(a.logical_op_id, []).append(a)

    per_op_cost: dict[str, int] = {}
    unattributable_ops: list[str] = []

    for op_id, recs in by_op.items():
        retained = [r for r in recs if r.retained_in_trace]
        truth = executor_attempt_counts.get(op_id)
        if truth is None:
            raise TraceAttributionError(
                f"logical_op_id {op_id} present in trace but absent from executor "
                f"durable counter; cannot validate attempt-set completeness"
            )
        if len(retained) > truth:
            raise TraceAttributionError(
                f"logical_op_id {op_id}: retained {len(retained)} attempts exceeds "
                f"executor truth {truth}; trace is corrupt or double-exported"
            )
        if len(retained) < truth:
            # partial sample: cost is a lower bound, eval may be unattributable
            unattributable_ops.append(op_id)
        per_op_cost[op_id] = sum(r.tokens_in + r.tokens_out for r in retained)

    scored = [a for a in agg.attempts if a.produced_scored_output]
    for s in scored:
        if not s.retained_in_trace:
            # score produced by an attempt the sampler dropped
            unattributable_ops.append(s.logical_op_id)

    if unattributable_ops:
        return {
            "trace_id": agg.trace_id,
            "attributable": False,
            "cost_lower_bound_tokens": per_op_cost,
            "unattributable_logical_ops": sorted(set(unattributable_ops)),
            "note": "partial sample: do not report cost as exact; do not attach "
                    "eval score to surviving sibling attempts",
        }
    return {
        "trace_id": agg.trace_id,
        "attributable": True,
        "cost_tokens": per_op_cost,
        "unattributable_logical_ops": [],
    }


def assert_attributable(result: dict) -> None:
    if not result.get("attributable", False):
        raise TraceAttributionError(
            f"trace {result['trace_id']} is a partial sample over logical ops "
            f"{result['unattributable_logical_ops']}; refusing to emit exact cost "
            f"or attach eval scores to surviving attempts"
        )
