# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reconstruct-a-false-causal-order-when-replaying-a-multi-agent-conversation-from-per-agent-logs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reconstruct-a-false-causal-order-when-replaying-a-multi-agent-conversation-from-per-agent-logs.warrant.json
# Markdown SHA-256:   ca915fca936a2c123791a9a0fd2f2ebd7effa34be687d981a5277b89392b36fe
# Code AST SHA-256:   41ac2c0eb011aa9c305ab37a6695749fd5ec9768fc620a37e6aaf81051872a04
# Verified Classes:   CausalOrderViolation, Event
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalOrderViolation(RuntimeError):
    """Raised when a forensic replay would emit an order that contradicts a known message edge."""
    pass


@dataclass(frozen=True)
class Event:
    agent: str
    kind: str
    ts: float                      # wall-clock at flush/handle, NOT trustworthy alone
    edge_id: Optional[str] = None  # message edge this event participates in
    edge_role: Optional[str] = None  # "send" or "recv"


def reconstruct_order(events: list[Event], edge_send_completion: dict[str, float]) -> list[Event]:
    """
    Merge per-agent events into a causal order. Refuses to emit a causal claim
    when a message edge contradicts the wall-clock order.
    """
    by_ts = sorted(events, key=lambda e: e.ts)
    position = {id(e): i for i, e in enumerate(by_ts)}

    for e in events:
        if e.edge_role != "recv" or e.edge_id is None:
            continue
        send_completion = edge_send_completion.get(e.edge_id)
        if send_completion is None:
            raise CausalOrderViolation(
                f"edge {e.edge_id} has no send-completion timestamp; "
                f"cannot validate recv at {e.ts} for agent {e.agent}"
            )
        # Find the matching send event by edge_id.
        send_evt = next(
            (x for x in events if x.edge_id == e.edge_id and x.edge_role == "send"),
            None,
        )
        if send_evt is None:
            raise CausalOrderViolation(
                f"edge {e.edge_id} has recv but no send event; transcript incomplete"
            )
        if position[id(send_evt)] > position[id(e)]:
            # Wall-clock merge put the send AFTER the recv: inversion.
            raise CausalOrderViolation(
                f"causal inversion on edge {e.edge_id}: send(ts={send_evt.ts}) "
                f"ordered after recv(ts={e.ts}); send-completion={send_completion}"
            )
        if send_completion >= e.ts:
            raise CausalOrderViolation(
                f"edge {e.edge_id}: recv(ts={e.ts}) precedes send-completion "
                f"({send_completion}); receiver could not have acted on this message"
            )
    return by_ts
