# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cross-agent-causal-contamination-when-a-shared-trace-span-is-attributed-to-the-wrong-producer-in-a-multi-agent-handoff-gra.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cross-agent-causal-contamination-when-a-shared-trace-span-is-attributed-to-the-wrong-producer-in-a-multi-agent-handoff-gra.warrant.json
# Markdown SHA-256:   90fe48e642fb9d1364bd1a31f4bb1d72fed729c937671ef563be9547ff711a07
# Code AST SHA-256:   866204b61f53103b7a0c82d3f078c2d60c4d0602b5de9bd2e0529cfe1ac205f6
# Verified Classes:   SharedSpanMisattributionError, Event, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SharedSpanMisattributionError(RuntimeError):
    """Raised when attribution would blame a span-level producer for a failure
    carried by an event owned by a different instance under a shared span."""
    pass


@dataclass
class Event:
    name: str
    producer_instance_id: Optional[str]
    sequence: int
    carries_failure: bool = False


@dataclass
class Span:
    span_id: str
    producer: str                      # span-level producer (the trap)
    events: list = field(default_factory=list)
    children: list = field(default_factory=list)


def attribute_failure(span: Span, path: Optional[list] = None) -> str:
    """Descend-or-abstain attribution. Returns the blamed instance id,
    or 'INDETERMINATE'. Never returns the span-level producer on a shared span."""
    path = path or []

    # Collect every producer that touched this span's events.
    event_producers = {e.producer_instance_id for e in span.events if e.producer_instance_id}
    all_producers = event_producers | {span.producer}
    shared = len(event_producers) > 1 or (event_producers and span.producer not in event_producers)

    failing_events = [e for e in span.events if e.carries_failure]

    if shared:
        if not failing_events:
            # Shared span, no event-level failure marker: cannot descend.
            return "INDETERMINATE"
        # Descend to event level.
        blamed = {e.producer_instance_id for e in failing_events}
        if len(blamed) != 1 or None in blamed:
            return "INDETERMINATE"
        culprit = blamed.pop()
        if culprit == span.producer and culprit not in event_producers:
            raise SharedSpanMisattributionError(
                f"span {span.span_id}: failure event claims producer {culprit} "
                f"but no such event exists under span; topology inconsistent"
            )
        return culprit

    # Not shared: span-level producer is safe.
    if not failing_events and not span.children:
        raise SharedSpanMisattributionError(
            f"span {span.span_id}: no failure signal and no children; "
            f"attribution would be a confident guess"
        )
    return span.producer


# --- reproduction of the observed run ---
retrieve = Span(
    span_id="retrieve.span",
    producer="R",
    events=[
        Event("retrieval.v1", "R", sequence=1, carries_failure=False),
        Event("retrieval.v2", "S", sequence=2, carries_failure=True),  # superseded doc
    ],
)

assert attribute_failure(retrieve) == "S", "must blame S, not span producer R"
print("attributed to:", attribute_failure(retrieve))  # -> S
