# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-caused-by-non-deterministic-tool-call-ordering-in-agentic-forensic-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-caused-by-non-deterministic-tool-call-ordering-in-agentic-forensic-reconstruction.warrant.json
# Markdown SHA-256:   6b3a51176188e13b6b203a261c1fe1f2c64bc69a70c62ca4a0671551c0745068
# Code AST SHA-256:   ba2c1d54c8853acc77119f7325f3d3ecfb85312753b27b71db410cd05ae41785
# Verified Classes:   ReplayDependencyGapError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ReplayDependencyGapError(RuntimeError):
    """Raised when a session cannot be faithfully replayed because a
    side-effecting tool call lacks recorded happens-before edges."""
    pass


def assert_replay_eligible(session_events):
    # Group side-effecting calls by turn to detect intra-turn concurrency.
    by_turn = {}
    for ev in session_events:
        if ev.get("side_effecting"):
            by_turn.setdefault(ev["turn_id"], []).append(ev)

    for turn_id, calls in by_turn.items():
        if len(calls) <= 1:
            continue  # serialized; ordering is implicit
        for call in calls:
            deps = call.get("depends_on") or []
            if not deps:
                raise ReplayDependencyGapError(
                    f"Turn {turn_id}: concurrent side-effecting call "
                    f"{call['event_id']} ({call['tool']}) has no recorded "
                    f"happens-before edges among {len(calls)} calls; "
                    f"replay would infer order from timestamps and may "
                    f"diverge. Mark session non-replayable or backfill "
                    f"dependency annotations before reconstruction."
                )
    return True


def replay(session_events):
    assert_replay_eligible(session_events)
    # ... deterministic reconstruction proceeds only past the gate ...
    return reconstruct(session_events)
