# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-causal-traces-before-committing-a-handoff-receipt-and-why-span-join-on-trace-id-alone-silently-corrupts-the.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-divergent-causal-traces-before-committing-a-handoff-receipt-and-why-span-join-on-trace-id-alone-silently-corrupts-the.warrant.json
# Markdown SHA-256:   86c27ad47e14a1c3f80ea9e9edba93f7f8c040254c64f68897c1af8ccbf93d46
# Code AST SHA-256:   9d5fddc2175a53ee9964800a97fc9e04f78a848531646fb5bd5e2ade8966f8b5
# Verified Classes:   CausalTraceDivergence, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalTraceDivergence(RuntimeError):
    """Raised when a handoff receipt would be committed over a causally unsound trace."""
    pass


@dataclass
class Span:
    instance_id: str
    generation: int
    emit_seq: int
    parent_span_id: Optional[str]
    tool_name: Optional[str]
    args_hash: Optional[str]
    exec_started_at: float
    emitted_at: float
    late_flush: bool = False

    def logical_key(self) -> tuple:
        return (self.tool_name, self.args_hash, self.generation)


def reconstruct_causal_dag(spans: list[Span], flush_interval: float) -> dict:
    """Join spans under a parent, deduplicating by (instance, generation, emit_seq)
    and refusing to flatten across generations without an explicit resume edge."""
    by_parent: dict[str, list[Span]] = {}
    seen: set[tuple] = set()
    for s in spans:
        key = (s.instance_id, s.generation, s.emit_seq)
        if key in seen:
            continue  # duplicate emission; higher emit_seq already won
        seen.add(key)
        if s.emitted_at - s.exec_started_at > flush_interval:
            s.late_flush = True
        by_parent.setdefault(s.parent_span_id or "root", []).append(s)
    return by_parent


def verify_handoff_receipt(
    spans: list[Span],
    executor_logical_count: int,
    flush_interval: float,
) -> None:
    dag = reconstruct_causal_dag(spans, flush_interval)

    # Invariant 1: no span may straddle a generation boundary while late-flushed.
    for parent, children in dag.items():
        gens = {c.generation for c in children}
        if len(gens) > 1:
            resume_edges = [c for c in children if c.tool_name == "resume"]
            if not resume_edges:
                raise CausalTraceDivergence(
                    f"parent {parent!r} has spans across generations {sorted(gens)} "
                    f"with no explicit resume edge; join would flatten re-execution"
                )

    # Invariant 2: late-flushed spans from a prior generation must not be
    # ordered by emitted_at against post-checkpoint spans.
    for parent, children in dag.items():
        for c in children:
            if c.late_flush and c.generation < max(x.generation for x in children):
                raise CausalTraceDivergence(
                    f"span {c.instance_id}/{c.emit_seq} late-flushed from generation "
                    f"{c.generation} into a generation-{max(x.generation for x in children)} join"
                )

    # Invariant 3: logical call count must match executor's own deduplicated count.
    logical = {c.logical_key() for c in spans if c.tool_name not in (None, "resume")}
    if len(logical) != executor_logical_count:
        raise CausalTraceDivergence(
            f"reconstructed logical calls={len(logical)} != executor count="
            f"{executor_logical_count}; audit chain would diverge silently"
        )
