# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-replay-divergence-in-non-deterministic-agent-traces-when-decision-attribution-is-reconstructed-from-partial-sp.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-replay-divergence-in-non-deterministic-agent-traces-when-decision-attribution-is-reconstructed-from-partial-sp.warrant.json
# Markdown SHA-256:   e6455531363612447b6402783fb45d73a1826a5e9d2556985762b367b955e09f
# Code AST SHA-256:   6bd07b1958433b3588ae3882bdda356588ac60291ad6fd9b29f3edfa4f4c73e1
# Verified Classes:   AttributionIndeterminateError, SampledStep
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class AttributionIndeterminateError(RuntimeError):
    """Raised when a decision cannot be causally attributed to an upstream span.

    Signals that the replay reproduced the span graph but not the
    decision-relevant conditioning set, so any emitted causal edge would be
    spurious.
    """


@dataclass(frozen=True)
class SampledStep:
    span_id: str
    top1_logit: float
    top2_logit: float
    temperature: float
    recorded_context_hash: str
    replayed_context_hash: str
    recorded_context_order: tuple[str, ...]
    replayed_context_order: tuple[str, ...]


def decision_margin(step: SampledStep) -> float:
    """Normalized top-1 vs top-2 logit gap, shrunk by sampling temperature."""
    raw_gap = step.top1_logit - step.top2_logit
    # Higher temperature widens the noise band, shrinking effective margin.
    return raw_gap / max(step.temperature, 1e-6)


def conditioning_delta(step: SampledStep) -> int:
    """Exact count of decision-relevant conditioning differences.

    Membership hash equality is insufficient: ordering and truncation matter.
    """
    delta = 0
    if step.recorded_context_hash != step.replayed_context_hash:
        delta += 1
    if step.recorded_context_order != step.replayed_context_order:
        delta += 1
    return delta


def attribute_decision(step: SampledStep, noise_band: float = 1.5) -> str:
    """Return the upstream span_id iff attribution is causally sound.

    Raises AttributionIndeterminateError when the margin sits inside the
    sampling noise band and the conditioning set was not reproduced exactly.
    """
    margin = decision_margin(step)
    delta = conditioning_delta(step)

    inside_noise = margin < noise_band
    conditioning_changed = delta != 0

    if inside_noise and conditioning_changed:
        raise AttributionIndeterminateError(
            f"span={step.span_id} margin={margin:.3f} < noise_band={noise_band} "
            f"and conditioning_delta={delta}: replay reproduced the span graph "
            f"but not the decision-relevant conditioning set; causal edge is "
            f"spurious and must be marked indeterminate."
        )

    if inside_noise and not conditioning_changed:
        # Reproduced exactly, but decision is within sampling noise: mark as
        # correlated-only rather than asserting a causal edge.
        return f"{step.span_id}:correlated"

    return f"{step.span_id}:causal"


def replay_and_attribute(steps: list[SampledStep]) -> dict[str, str]:
    results: dict[str, str] = {}
    for step in steps:
        results[step.span_id] = attribute_decision(step)
    return results
