# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconstructs-a-causal-trace-across-an-mcp-a2a-boundary-and-the-parent-span-is-silently-re-parented-by-a-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconstructs-a-causal-trace-across-an-mcp-a2a-boundary-and-the-parent-span-is-silently-re-parented-by-a-retry.warrant.json
# Markdown SHA-256:   b5f7b1447434d27b842139bddf3054f943878238905d7a53ffe3fc67b3d20034
# Code AST SHA-256:   c30a55fa44207583b47cdc1237f5c9a3fd804b59e50af032a71850fb1b430f28
# Verified Classes:   CausalTraceCorruption
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalTraceCorruption(RuntimeError):
    """Raised when a reconstructed causal trace violates the retry-transparency invariant."""
    pass


RETRY_WRAPPER_KIND = "retry_wrapper"
CROSS_BOUNDARY_KINDS = {"mcp.call", "a2a.dispatch", "a2a.response"}


def validate_causal_trace(spans: list[dict]) -> None:
    """
    Enforce: no cross-boundary span may have a retry_wrapper as an ancestor
    on the path to its semantic caller. Raises CausalTraceCorruption on violation.
    """
    by_id = {s["span_id"]: s for s in spans}

    for span in spans:
        if span.get("span.kind") not in CROSS_BOUNDARY_KINDS:
            continue

        # Walk the parent chain; if we hit a retry_wrapper before the semantic
        # caller, the causal edge is corrupted.
        cursor = span.get("parent_span_id")
        hops = 0
        while cursor is not None and hops < 64:
            parent = by_id.get(cursor)
            if parent is None:
                break
            if parent.get("span.kind") == RETRY_WRAPPER_KIND:
                raise CausalTraceCorruption(
                    f"Cross-boundary span {span['span_id']} "
                    f"(kind={span.get('span.kind')}) has retry_wrapper "
                    f"{parent['span_id']} as ancestor. Causal edge is "
                    f"mechanical, not semantic. Re-parent to the original "
                    f"caller and record retry metadata as attributes."
                )
            cursor = parent.get("parent_span_id")
            hops += 1


def reconstruct_causal_chain(spans: list[dict], target_span_id: str) -> list[str]:
    """
    Return the semantic causal chain (root -> target), applying a
    retry-transparent projection. Raises if the trace is corrupt.
    """
    validate_causal_trace(spans)
    by_id = {s["span_id"]: s for s in spans}
    if target_span_id not in by_id:
        raise CausalTraceCorruption(f"Unknown span {target_span_id}")

    chain: list[str] = []
    cursor = target_span_id
    while cursor is not None:
        span = by_id.get(cursor)
        if span is None:
            raise CausalTraceCorruption(
                f"Dangling parent reference at {cursor}; trace is truncated."
            )
        # Retry-transparent projection: skip wrappers, do not include them.
        if span.get("span.kind") != RETRY_WRAPPER_KIND:
            chain.append(cursor)
        cursor = span.get("parent_span_id")

    return list(reversed(chain))
