# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-link-corruption-when-an-observability-plane-re-parents-agent-spans-across-a-mid-execution-context-compact.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-link-corruption-when-an-observability-plane-re-parents-agent-spans-across-a-mid-execution-context-compact.warrant.json
# Markdown SHA-256:   af2b25f13f21444823efeb321be459db2e0da148a3d75c17ed5141f7193d053a
# Code AST SHA-256:   9f16e288fce1aeab73be8c70a9832bb36fba317e463caf3399592dcacb0dd258
# Verified Classes:   CausalInversionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalInversionError(RuntimeError):
    """Raised when a trace's span tree is structurally valid but causally inverted."""
    pass


TRANSFORM_KINDS = {"compact", "summarize", "truncate", "embed"}
COST_INVERSION_FACTOR = 5.0


def assert_causal_soundness(spans: list[dict]) -> None:
    """
    spans: each dict has keys:
      span_id, parent_id, kind, start_ns, end_ns, token_count
    Validates that transform spans are not inverted parents of overlapping
    reasoning spans, and that cost mass does not migrate onto transforms.
    """
    by_id = {s["span_id"]: s for s in spans}

    # Build subtree cost by walking parent links.
    subtree_cost = {sid: s["token_count"] for sid, s in by_id.items()}
    for s in sorted(spans, key=lambda x: x["start_ns"], reverse=True):
        pid = s["parent_id"]
        if pid in subtree_cost:
            subtree_cost[pid] += subtree_cost[s["span_id"]]

    reasoning_costs = [
        subtree_cost[s["span_id"]]
        for s in spans
        if s["kind"] not in TRANSFORM_KINDS
    ]
    if not reasoning_costs:
        return
    reasoning_median = sorted(reasoning_costs)[len(reasoning_costs) // 2]
    max_reasoning = max(reasoning_costs)

    for s in spans:
        if s["kind"] not in TRANSFORM_KINDS:
            continue

        # Signature 1: transform overlaps one of its own descendants.
        for child in spans:
            if child["parent_id"] != s["span_id"]:
                continue
            overlaps = (
                child["start_ns"] < s["end_ns"]
                and child["end_ns"] > s["start_ns"]
            )
            if overlaps:
                raise CausalInversionError(
                    f"transform span {s['span_id']} ({s['kind']}) is parent of "
                    f"overlapping span {child['span_id']} ({child['kind']}); "
                    f"parentage was inferred from adjacency, not causation"
                )

        # Signature 2: transform owns cost mass disproportionate to semantic work.
        cost = subtree_cost[s["span_id"]]
        if cost > COST_INVERSION_FACTOR * max_reasoning:
            raise CausalInversionError(
                f"transform span {s['span_id']} ({s['kind']}) owns subtree cost "
                f"{cost} vs max reasoning subtree {max_reasoning} "
                f"(median {reasoning_median}); cost attribution is inverted"
            )


def assert_evidence_ancestry(spans: list[dict], flag_span_id: str, evidence_span_id: str) -> None:
    """Hallucination evidence must be an ancestor of the flagging span."""
    by_id = {s["span_id"]: s for s in spans}
    cur = by_id.get(flag_span_id)
    while cur is not None:
        if cur["span_id"] == evidence_span_id:
            return
        pid = cur["parent_id"]
        cur = by_id.get(pid) if pid else None
    raise CausalInversionError(
        f"hallucination evidence {evidence_span_id} is not an ancestor of "
        f"flag span {flag_span_id}; evidence link is unreplayable"
    )
