# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-span-identity-divergence-between-the-observability-trace-graph-and-the-security-taint-graph-before-forensic-replay-an.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-span-identity-divergence-between-the-observability-trace-graph-and-the-security-taint-graph-before-forensic-replay-an.warrant.json
# Markdown SHA-256:   8ef9b3a7ecd67c0cef62b942794ba0ea53c738943a2e3de36a7ba3425aba7b1f
# Code AST SHA-256:   3397c61cfff4bf03ba9521852d4156afe3a45dd16c13cbd1b706031da80960ac
# Verified Classes:   ForensicJoinDivergence, Span, TaintLineage
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForensicJoinDivergence(RuntimeError):
    """Raised when a taint lineage cannot be bound to exactly one logical step
    in the trace graph, or is bound only to an errored span with no retry carrier."""
    pass


@dataclass
class Span:
    span_id: str
    agent_instance_id: str
    task_id: str
    logical_step_ordinal: int
    status: str  # "OK" | "ERROR"
    parent_span_id: Optional[str] = None


@dataclass
class TaintLineage:
    lineage_id: str
    source: str            # e.g. "untrusted_external"
    sink: str              # e.g. "memory_write"
    bound_span_id: str     # span minted at tool-invocation time
    provenance_chain: list = field(default_factory=list)


def reconcile_join(
    spans: list[Span],
    lineages: list[TaintLineage],
) -> dict[str, Span]:
    """Re-key each taint lineage onto its logical-step carrier span.
    Fails closed if a lineage cannot be bound to a live carrier."""
    # Index spans by logical execution identity (stable across retry/resume).
    by_logical: dict[tuple[str, str, int], list[Span]] = {}
    by_span_id: dict[str, Span] = {}
    for s in spans:
        by_logical.setdefault(
            (s.agent_instance_id, s.task_id, s.logical_step_ordinal), []
        ).append(s)
        by_span_id[s.span_id] = s

    resolved: dict[str, Span] = {}
    for lin in lineages:
        bound = by_span_id.get(lin.bound_span_id)
        if bound is None:
            raise ForensicJoinDivergence(
                f"lineage {lin.lineage_id} bound to unknown span {lin.bound_span_id}"
            )
        key = (bound.agent_instance_id, bound.task_id, bound.logical_step_ordinal)
        candidates = by_logical.get(key, [])
        if not candidates:
            raise ForensicJoinDivergence(
                f"lineage {lin.lineage_id}: no span for logical step {key}"
            )
        # Prefer a live carrier; an errored span alone is not dispositive.
        live = [s for s in candidates if s.status == "OK"]
        if not live:
            raise ForensicJoinDivergence(
                f"lineage {lin.lineage_id} reaches sink {lin.sink} but logical "
                f"step {key} has only errored spans; retry carrier missing — "
                f"containment verdict would be unsound"
            )
        # If multiple live carriers exist (fan-out), the lineage is ambiguous
        # unless the provenance chain disambiguates by ordinal.
        if len(live) > 1 and len(lin.provenance_chain) > 0:
            last = lin.provenance_chain[-1]
            narrowed = [s for s in live if s.logical_step_ordinal == last]
            if len(narrowed) != 1:
                raise ForensicJoinDivergence(
                    f"lineage {lin.lineage_id}: ambiguous carrier among "
                    f"{[s.span_id for s in live]}"
                )
            live = narrowed
        resolved[lin.lineage_id] = live[-1]

    return resolved
