# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-stream-truncation-against-tool-declared-completeness-when-a-server-sheds-backpressure-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-stream-truncation-against-tool-declared-completeness-when-a-server-sheds-backpressure-mid-tool-call.warrant.json
# Markdown SHA-256:   7613579db54a4d715e4263eff828a14af0dcf656060c68340b7352aa7a30f575
# Code AST SHA-256:   5eef680b6f98287c810933c0d4e15e88cfac5965950214c82035c676105c3d99
# Verified Classes:   StreamCompletenessError, Verdict, ProgressState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class StreamCompletenessError(RuntimeError):
    """Raised when a streamed MCP tool result cannot be proven complete."""


class Verdict(Enum):
    COMPLETE = "complete"
    TRUNCATED_RECOVERABLE = "truncated_recoverable"
    TRUNCATED_UNRECOVERABLE = "truncated_unrecoverable"
    UNVERIFIED = "unverified"


@dataclass
class ProgressState:
    token: str
    total: Optional[int] = None
    max_progress: int = 0
    terminal_frame_received: bool = False
    terminal_payload: Optional[dict] = None

    def observe_progress(self, progress: int, total: Optional[int]) -> None:
        # progress is a high-water mark, not a sequence; gaps are legal (coalescing).
        self.max_progress = max(self.max_progress, progress)
        if total is not None:
            if self.total is not None and total != self.total:
                raise StreamCompletenessError(
                    f"progressToken {self.token!r}: total changed mid-stream "
                    f"{self.total} -> {total}; server contract violated"
                )
            self.total = total

    def observe_terminal(self, payload: dict) -> None:
        self.terminal_frame_received = True
        self.terminal_payload = payload


def classify(state: ProgressState, *, tool_is_idempotent: bool) -> Verdict:
    if not state.terminal_frame_received:
        # Clean close with no terminal frame: the client must NOT synthesize a result.
        if state.total is None:
            return Verdict.UNVERIFIED
        return Verdict.TRUNCATED_UNRECOVERABLE

    if state.total is None:
        # Terminal frame present but no completeness proof declared.
        return Verdict.UNVERIFIED

    if state.max_progress >= state.total:
        return Verdict.COMPLETE

    # Terminal frame arrived but progress says the server intended more.
    if not tool_is_idempotent:
        raise StreamCompletenessError(
            f"progressToken {state.token!r}: terminal frame at progress "
            f"{state.max_progress}/{state.total} on non-idempotent tool; "
            f"refusing to resume — requires auditor reconciliation"
        )
    return Verdict.TRUNCATED_RECOVERABLE


def admit_to_reasoning_state(state: ProgressState, *, tool_is_idempotent: bool) -> dict:
    verdict = classify(state, tool_is_idempotent=tool_is_idempotent)
    if verdict is Verdict.TRUNCATED_UNRECOVERABLE:
        raise StreamCompletenessError(
            f"progressToken {state.token!r}: stream closed with no terminal frame; "
            f"partial result must not enter agent context"
        )
    if verdict is Verdict.UNVERIFIED:
        # Admissible only with an explicit partial annotation the LLM can see.
        payload = dict(state.terminal_payload or {})
        payload["_meta"] = {**payload.get("_meta", {}), "partial": True,
                            "completeness": "unverified"}
        return payload
    if verdict is Verdict.TRUNCATED_RECOVERABLE:
        raise StreamCompletenessError(
            f"progressToken {state.token!r}: {state.max_progress}/{state.total} "
            f"shards delivered; resume from {state.max_progress + 1}"
        )
    return dict(state.terminal_payload or {})
