# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-stream-resumption-against-in-flight-server-push-elicitation-when-mcp-is-carried-over-http-native-bidirectional-channe.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-stream-resumption-against-in-flight-server-push-elicitation-when-mcp-is-carried-over-http-native-bidirectional-channe.warrant.json
# Markdown SHA-256:   7d782817bbf187dd9f8cd359941ddad7a2f5e3f80a4ba5d1116c54c7733d481f
# Code AST SHA-256:   b2ef98eba1248de7c07e2f6cbab83e13fa3b81b1157d1d5fe7cf729f03e3b280
# Verified Classes:   ElicitationResumeDivergence, ElicitationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ElicitationResumeDivergence(RuntimeError):
    """Raised when a resumed stream would re-deliver or orphan an elicitation."""
    pass


@dataclass
class ElicitationLedger:
    # Durable: must be persisted alongside the stream cursor.
    resolved: dict[str, str] = field(default_factory=dict)   # request_id -> response_digest
    outstanding: set[str] = field(default_factory=set)       # pushed, not yet answered

    def record_send(self, request_id: str, response: str) -> None:
        # Log-before-send: write durable state BEFORE the frame hits the wire.
        digest = hashlib.sha256(response.encode()).hexdigest()
        self.resolved[request_id] = digest
        self.outstanding.discard(request_id)

    def reconcile_on_resume(self, server_inflight: set[str]) -> list[str]:
        """Return request IDs the server must re-issue with fresh IDs.

        Raises if the server believes a request is live that we already
        answered (duplicate hazard) AND we cannot prove we answered it,
        or if we hold an outstanding request the server has forgotten
        (orphan/deadlock hazard).
        """
        # Server thinks live, we think resolved -> must NOT replay; tell server to clear.
        cleared = server_inflight & set(self.resolved)
        # Server thinks live, we have no record -> safe to replay (we never answered).
        replayable = server_inflight - set(self.resolved) - self.outstanding
        # We think live, server forgot -> deadlock; cannot proceed.
        orphaned = self.outstanding - server_inflight
        if orphaned:
            raise ElicitationResumeDivergence(
                f"orphaned elicitations {sorted(orphaned)}: client awaiting "
                f"responses the server no longer tracks; resume would deadlock"
            )
        # Duplicate-answer hazard: server has it live but we hold a response digest
        # that was never acknowledged. Re-issue with new ID rather than replay.
        if cleared and not all(self.resolved[rid] for rid in cleared):
            raise ElicitationResumeDivergence(
                f"unprovable resolution for {sorted(cleared)}; refusing replay"
            )
        return sorted(replayable)


def resume_stream(ledger: ElicitationLedger, cursor: int,
                  server_inflight: set[str], replay_frames: list[dict]) -> list[dict]:
    reissue = ledger.reconcile_on_resume(server_inflight)
    applied: list[dict] = []
    for frame in replay_frames:
        if frame.get("method") == "elicitation/create":
            rid = frame["params"]["request_id"]
            if rid in ledger.resolved:
                # Already answered before the drop: suppress, do not re-prompt.
                continue
            if rid not in reissue:
                raise ElicitationResumeDivergence(
                    f"replay of un-reconciled elicitation {rid} at cursor {cursor}"
                )
        applied.append(frame)
    return applied
