# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replaying-a-speculative-branch-diverge-from-its-own-committed-log-after-a-sibling-agent-s-tool-result-is-re-injected-out-of-order.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replaying-a-speculative-branch-diverge-from-its-own-committed-log-after-a-sibling-agent-s-tool-result-is-re-injected-out-of-order.warrant.json
# Markdown SHA-256:   00c79914447b32a1d56d5ed19067a2cd6cd2a2445ee921c237f22e110d9887a5
# Code AST SHA-256:   2da1c3dab10b864bda4a191372f3f1b50379a84b9b852e8c31427d0b91ce4c4a
# Verified Classes:   ReplayOrderAmbiguity, ResultEvent, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayOrderAmbiguity(RuntimeError):
    """Raised when replay cannot reconstruct the agent's consumption order."""
    pass


@dataclass
class ResultEvent:
    commit_seq: int
    arrival_ord: Optional[int]   # per-agent consumption order within a step
    agent_id: str
    value: object
    flattened_from_parent: bool = False


@dataclass
class Checkpoint:
    seq: int
    agent_id: str
    in_flight: set = field(default_factory=set)  # speculative calls not yet committed


def reconstruct_consumption_order(
    checkpoint: Checkpoint,
    events: list[ResultEvent],
) -> list[ResultEvent]:
    # C2: refuse to replay from a checkpoint with in-flight speculation
    if checkpoint.in_flight:
        raise ReplayOrderAmbiguity(
            f"checkpoint seq={checkpoint.seq} for {checkpoint.agent_id} "
            f"has in-flight speculation {sorted(checkpoint.in_flight)}; "
            f"arrival order of pending results is unrecoverable"
        )

    relevant = [e for e in events if e.agent_id == checkpoint.agent_id]

    # C3: refuse if any sibling sub-event was flattened (grouping lost)
    if any(e.flattened_from_parent for e in relevant):
        raise ReplayOrderAmbiguity(
            "sibling sub-event was flattened into total order; "
            "parent-child grouping the agent observed cannot be reconstructed"
        )

    # C1: arrival ordinal must exist for every consumed result
    missing = [e for e in relevant if e.arrival_ord is None]
    if missing:
        raise ReplayOrderAmbiguity(
            f"{len(missing)} result event(s) lack arrival_ord; "
            f"commit_seq alone is insufficient for order-sensitive consumption"
        )

    # Reconstruct the order the agent actually consumed results in.
    return sorted(relevant, key=lambda e: e.arrival_ord)


def detect_divergence(
    checkpoint: Checkpoint,
    events: list[ResultEvent],
    recorded_trace: list,
    replay_fn,
) -> bool:
    try:
        ordered = reconstruct_consumption_order(checkpoint, events)
    except ReplayOrderAmbiguity:
        # Downgrade to inconclusive rather than quarantining the branch.
        return False

    replayed_trace = replay_fn(checkpoint, ordered)
    return replayed_trace != recorded_trace
