# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-during-resumption-and-how-to-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-http-session-has-silently-forked-during-resumption-and-how-to-bound-it.warrant.json
# Markdown SHA-256:   e92980f02ad0abf15c2511e45c0d89b0bafc59667068f5028c2a6c30528848ca
# Code AST SHA-256:   67d5cb07c57858e4b3c238af210e294d65692805165b9dd691d53becd55d0164
# Verified Classes:   ForkedSessionError, EffectLedger, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ForkedSessionError(RuntimeError):
    """Raised when a resumed MCP streamable-HTTP session cannot be proven
    continuous with the pre-drop logical session."""
    pass


@dataclass
class EffectLedger:
    # idempotency_key -> terminal status ("done" | "failed")
    entries: dict = field(default_factory=dict)
    ttl_seconds: float = 3600.0
    written_at: dict = field(default_factory=dict)

    def record(self, key: str, status: str) -> None:
        self.entries[key] = status
        self.written_at[key] = time.time()

    def lookup(self, key: str) -> Optional[str]:
        ts = self.written_at.get(key)
        if ts is None:
            return None
        if time.time() - ts > self.ttl_seconds:
            return None  # expired: treat as miss
        return self.entries.get(key)


@dataclass
class ResumeState:
    last_ack_event_id: int
    last_seen_event_id: int
    in_flight_keys: list
    resume_cursor_owner: str          # consumer id that last advanced cursor
    this_consumer: str


def reconcile_on_resume(state: ResumeState, ledger: EffectLedger,
                        max_reconcile_deadline: float) -> dict:
    """
    Gate executed before the agent loop may re-plan after a stream resume.
    Returns reconstructed results for in-flight calls that actually executed.
    Raises ForkedSessionError when continuity cannot be established.
    """
    deadline = time.time() + max_reconcile_deadline
    reconstructed = {}

    # 1. Fencing: another consumer advanced the cursor.
    if state.resume_cursor_owner != state.this_consumer:
        raise ForkedSessionError(
            f"session forked: cursor owned by {state.resume_cursor_owner!r}, "
            f"resumed by {state.this_consumer!r}; fence required"
        )

    # 2. Gap detection: events were skipped between ack and last seen.
    gap = state.last_seen_event_id > state.last_ack_event_id + len(state.in_flight_keys)
    if not gap and not state.in_flight_keys:
        return reconstructed  # clean resume

    # 3. Reconcile every in-flight call against the effect ledger.
    for key in state.in_flight_keys:
        if time.time() > deadline:
            raise ForkedSessionError(
                f"reconciliation deadline exceeded for key {key!r}"
            )
        status = ledger.lookup(key)
        if status is None:
            # Effect never executed: safe to re-issue with the SAME key.
            reconstructed[key] = {"action": "reissue", "key": key}
        elif status == "done":
            reconstructed[key] = {"action": "reconstruct", "key": key,
                                  "result": "from_ledger"}
        else:
            raise ForkedSessionError(
                f"in-flight key {key!r} terminated as {status!r}; "
                f"agent must not re-plan blindly"
            )

    if gap and not reconstructed:
        raise ForkedSessionError(
            "event gap with empty ledger: continuity unprovable"
        )
    return reconstructed
