# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-failure-to-the-wrong-span-causal-credit-misassignment-in-trajectory-level-evaluation-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-failure-to-the-wrong-span-causal-credit-misassignment-in-trajectory-level-evaluation-loops.warrant.json
# Markdown SHA-256:   9ecb9419a973b8b2168395ba763b414e25fbec308db492366878c0d6d1e9cbe5
# Code AST SHA-256:   261ba15781833ed96e897c37e5500ea5e9042c8f02c9b2ab7ee50c83720af7a6
# Verified Classes:   AttributionInvariantError, Span, Trajectory
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when an attribution violates causal-precedence or counterfactual validity."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    start_ts: float
    end_ts: float
    output: str
    flagged: bool = False  # carries an error flag (the "observable" spans)


@dataclass
class Trajectory:
    spans: dict[str, Span] = field(default_factory=dict)

    def ancestry(self, span_id: str) -> set[str]:
        """All strict ancestors of span_id via parent links (not wall-clock)."""
        out, cur = set(), self.spans.get(span_id)
        while cur and cur.parent_id:
            out.add(cur.parent_id)
            cur = self.spans.get(cur.parent_id)
        return out


def attribute_failure(
    traj: Trajectory,
    manifestation_span_id: str,
    candidate_span_id: str,
    counterfactual_prevents: Optional[bool],
) -> str:
    """
    Emit credit for candidate_span_id as the cause of the failure observed at
    manifestation_span_id. Returns the credited span id, or raises to force
    the caller into abstention. Never returns a non-ancestor credit.
    """
    man = traj.spans.get(manifestation_span_id)
    cand = traj.spans.get(candidate_span_id)
    if man is None or cand is None:
        raise AttributionInvariantError(
            f"unknown span in attribution: man={manifestation_span_id} cand={candidate_span_id}"
        )

    # Invariant 1: causal ancestry, not wall-clock proximity.
    if candidate_span_id not in traj.ancestry(manifestation_span_id):
        raise AttributionInvariantError(
            f"candidate {candidate_span_id} is not an ancestor of manifestation "
            f"{manifestation_span_id}; credit would be causally invalid"
        )
    if cand.end_ts > man.start_ts:
        raise AttributionInvariantError(
            f"candidate {candidate_span_id} ends after manifestation begins; "
            f"cannot be its cause"
        )

    # Invariant 2: counterfactual must be checked, not assumed. None means the
    # pipeline could not replay -> must abstain, not guess.
    if counterfactual_prevents is None:
        raise AttributionInvariantError(
            f"no counterfactual available for {candidate_span_id}; "
            f"proximity alone is not admissible evidence"
        )
    if not counterfactual_prevents:
        raise AttributionInvariantError(
            f"correcting {candidate_span_id} would not have prevented the failure "
            f"at {manifestation_span_id}; not a cause"
        )

    # Invariant 3: silent spans are eligible -- we do NOT require cand.flagged.
    return candidate_span_id


def run_eval_loop(traj: Trajectory, man_id: str, candidates: list[str],
                  replay_fn) -> dict:
    """Emit at most one credit; abstain on any invariant violation."""
    for cid in candidates:
        try:
            cf = replay_fn(traj, cid, man_id)  # None if replay unavailable
            credited = attribute_failure(traj, man_id, cid, cf)
            return {"status": "credited", "span": credited}
        except AttributionInvariantError:
            continue
    # No candidate survived: abstain. Do NOT fall back to proximity.
    return {"status": "abstained", "manifestation": man_id}
