# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-span-parentage-across-asynchronous-observability-exporters-before-trusting-a-reconstructed-deci.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-span-parentage-across-asynchronous-observability-exporters-before-trusting-a-reconstructed-deci.warrant.json
# Markdown SHA-256:   0376ab016f728957128750ec2f7588ec13b8bb85e03c9f6740fc92505b0e2916
# Code AST SHA-256:   9a941277c358b15bddd92f3d36faee56bf5777ec24ffaa3437ae6f7f3d0d1e7d
# Verified Classes:   ParentageIncoherenceError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ParentageIncoherenceError(RuntimeError):
    """Raised when a reconstructed span graph contradicts immutable provenance attributes."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    step: int
    consumed_ids: frozenset[str] = field(default_factory=frozenset)   # immutable, set at creation
    produced_ids: frozenset[str] = field(default_factory=frozenset)   # immutable, set at close


def validate_trace(spans: list[Span]) -> dict[str, str]:
    """Re-derive parentage from provenance attributes; raise on any incoherent edge.

    Returns a mapping of span_id -> resolved_parent_span_id for the coherent subtree.
    """
    by_id = {s.span_id: s for s in spans}
    resolved: dict[str, str] = {}

    for span in spans:
        if span.parent_span_id is None:
            continue
        parent = by_id.get(span.parent_span_id)
        if parent is None:
            raise ParentageIncoherenceError(
                f"span {span.span_id} references missing parent {span.parent_span_id}"
            )

        # Invariant 1: parentage-attribute coherence.
        # A child's consumed provenance must be derivable from the parent's outputs.
        if span.consumed_ids and not span.consumed_ids.issubset(parent.produced_ids):
            orphaned = span.consumed_ids - parent.produced_ids
            raise ParentageIncoherenceError(
                f"span {span.span_id} consumed {sorted(orphaned)} not produced by "
                f"declared parent {parent.span_id}; parentage pointer is a backfill artifact"
            )

        # Invariant 2: monotonic step ordering along the edge.
        if span.step <= parent.step:
            raise ParentageIncoherenceError(
                f"span {span.span_id} step {span.step} not greater than parent "
                f"{parent.span_id} step {parent.step}; non-monotonic causal path"
            )

        resolved[span.span_id] = parent.span_id

    return resolved


def audit_decision_trace(spans: list[Span], cited_doc_id: str) -> bool:
    """Verify a citation against the repaired causal graph, not the raw parent pointer."""
    try:
        resolved = validate_trace(spans)
    except ParentageIncoherenceError as exc:
        # Quarantine: do not silently repair; surface for runtime fix.
        raise ParentageIncoherenceError(
            f"trace rejected for citation audit; root cause must be fixed at span creation: {exc}"
        ) from exc

    synthesizer = next((s for s in spans if s.consumed_ids), None)
    if synthesizer is None:
        raise ParentageIncoherenceError("no span carries consumed-provenance attributes")

    true_parent = resolved.get(synthesizer.span_id)
    if true_parent is None:
        raise ParentageIncoherenceError(
            f"synthesizer {synthesizer.span_id} has no coherent parent edge"
        )

    parent_span = next(s for s in spans if s.span_id == true_parent)
    return cited_doc_id in parent_span.produced_ids
