# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-resumption-offsets-against-a-backpressured-mcp-streamable-session-before-it-may-replay-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-resumption-offsets-against-a-backpressured-mcp-streamable-session-before-it-may-replay-tool-calls.warrant.json
# Markdown SHA-256:   a93cd183b166be09971577117275a6cdd75fd6eaaf18a6aabe0dad7ce0ae7bfc
# Code AST SHA-256:   d6565d9cc6207bcbadbad352cf5e363e94c023c5a10f3a888b41c45badba712a
# Verified Classes:   ResumptionGapError, SessionEventLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when Last-Event-ID precedes the server's retention floor."""
    pass


class SessionEventLog:
    def __init__(self, retention_floor: int, write_cursor: int):
        self.retention_floor = retention_floor  # oldest retained seq
        self.write_cursor = write_cursor        # highest emitted seq

    def resume_from(self, last_event_id: int) -> int:
        # Contract: resume only if the client's watermark is contiguous
        # with retained history. A gap must be surfaced, never bridged.
        if last_event_id < self.retention_floor - 1:
            raise ResumptionGapError(
                f"Last-Event-ID {last_event_id} precedes retention floor "
                f"{self.retention_floor}; events "
                f"{last_event_id + 1}..{self.retention_floor - 1} were shed. "
                f"Outcome of in-flight tool calls in this range is UNKNOWN; "
                f"do not reissue non-idempotent calls without a status read."
            )
        return last_event_id + 1


def handle_resume(log: SessionEventLog, last_event_id: int, pending_calls: dict) -> int:
    try:
        return log.resume_from(last_event_id)
    except ResumptionGapError:
        # Mark every pending call whose result could be in the shed window
        # as outcome-unknown rather than failed.
        for call_id, meta in pending_calls.items():
            if not meta.get("idempotent", False):
                meta["outcome"] = "unknown"
                meta["requires_status_read"] = True
        raise
