# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-corruption-when-opentelemetry-genai-spans-cross-agent-handoff-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-corruption-when-opentelemetry-genai-spans-cross-agent-handoff-boundaries.warrant.json
# Markdown SHA-256:   d5411fc58be38be33c5a30e2d61bb22359c545d99b6671dd869ed9b09fa794d0
# Code AST SHA-256:   e0526538bcba135b1253cbfc6419123ed9e5a8c4be71b5289a2fe43fdf374dbe
# Verified Classes:   CausalTraceIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalTraceIntegrityError(RuntimeError):
    """Raised when a GenAI trace asserts a causal edge that the span store cannot substantiate."""
    pass


def validate_causal_chain(spans: list[dict], trace_id: str) -> None:
    """
    Reject traces where any span's parent-id does not resolve to an exported
    span in the same trace. Re-parented traces (backend-synthesized edges) are
    treated as integrity failures, not benign gaps, because downstream latency
    and audit consumers depend on tree shape.

    spans: raw span records from the store, each with keys
           'span_id', 'parent_id', 'trace_id', 'name', 'start', 'end',
           and optionally 'gen_ai.operation.name'.
    """
    by_id = {s["span_id"]: s for s in spans if s["trace_id"] == trace_id}

    if not by_id:
        raise CausalTraceIntegrityError(
            f"no spans found for trace_id={trace_id}; cannot validate causality"
        )

    unresolved: list[tuple[str, str]] = []
    for span in by_id.values():
        parent = span.get("parent_id")
        if parent is None:
            continue  # root span
        if parent not in by_id:
            unresolved.append((span["span_id"], parent))

    if unresolved:
        detail = ", ".join(f"{child}->{parent}" for child, parent in unresolved)
        raise CausalTraceIntegrityError(
            f"trace {trace_id} contains {len(unresolved)} span(s) whose parent "
            f"is not exported: {detail}. Backend re-parenting would fabricate a "
            f"causal edge; exclude this trace from latency and audit consumers."
        )

    # Payload continuity check: every non-root span must declare an inbound
    # digest that matches a declared outbound digest on its parent.
    for span in by_id.values():
        parent_id = span.get("parent_id")
        if parent_id is None:
            continue
        inbound = span.get("gen_ai.agent.inbound_digest")
        parent_outbound = by_id[parent_id].get("gen_ai.agent.outbound_digest")
        if inbound is not None and parent_outbound is not None and inbound != parent_outbound:
            raise CausalTraceIntegrityError(
                f"payload discontinuity on edge {parent_id}->{span['span_id']}: "
                f"child inbound digest {inbound} != parent outbound digest "
                f"{parent_outbound}. The recorded causal edge is false."
            )


def aggregate_span_latency(spans: list[dict], trace_id: str) -> dict[str, float]:
    """Per-span wall-clock latency, safe against re-parenting because it uses
    span-local start/end deltas rather than parent-relative durations."""
    validate_causal_chain(spans, trace_id)
    return {
        s["span_id"]: s["end"] - s["start"]
        for s in spans
        if s["trace_id"] == trace_id and "end" in s and "start" in s
    }
