# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-replay-clock-diverges-from-its-persisted-causal-watermark-in-multi-agent-incident-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-replay-clock-diverges-from-its-persisted-causal-watermark-in-multi-agent-incident-reconstruction.warrant.json
# Markdown SHA-256:   6e081374097aea91b8f4a3e3d758e11bfff12e4d80d65be7db7fad9541b17ab6
# Code AST SHA-256:   59a674b5b6fbf65ba94a87960063bcd9335ce6710531ee242efd5a9601038f1f
# Verified Classes:   CausalDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalDriftError(RuntimeError):
    """Raised when a reconstructed emission clock is not dominated by the persisted causal watermark."""
    pass


def validate_replay_event(event_id, reconstructed_clock, watermark_frontier):
    """
    reconstructed_clock: int, logical time re-derived by the replay harness.
    watermark_frontier: dict[str, int], persisted causal frontier observed before emission.
    """
    if not watermark_frontier:
        # No durable causal record: cannot validate; must not claim total order.
        raise CausalDriftError(
            f"event {event_id}: empty watermark frontier, causal domination unverifiable"
        )

    max_observed = max(watermark_frontier.values())
    if reconstructed_clock > max_observed:
        raise CausalDriftError(
            f"event {event_id}: reconstructed clock {reconstructed_clock} exceeds "
            f"persisted watermark {max_observed} (frontier={watermark_frontier}); "
            f"timeline must downgrade to partial order"
        )
    return True


def order_timeline(events):
    """
    events: list of dicts with keys id, clock, watermark.
    Returns ('total', ordered_ids) or ('partial', watermark_ordered_ids).
    """
    try:
        for ev in events:
            validate_replay_event(ev["id"], ev["clock"], ev["watermark"])
    except CausalDriftError:
        # Fall back to watermark-only partial order; never clamp the clock.
        partial = sorted(events, key=lambda e: max(e["watermark"].values()) if e["watermark"] else -1)
        return ("partial", [e["id"] for e in partial])

    total = sorted(events, key=lambda e: e["clock"])
    return ("total", [e["id"] for e in total])
