# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-a2a-streaming-artifact-exchange-when-backpressure-stalls-partial-result-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-a2a-streaming-artifact-exchange-when-backpressure-stalls-partial-result-reconciliation.warrant.json
# Markdown SHA-256:   a99e00688aa54c4c0622e500b1d5691893c646282e77b112a1d4fa982c3ef9b1
# Code AST SHA-256:   eb20b19e8f958ad0550e80ee7d3074bb2a4e327270b06c37526915c627170243
# Verified Classes:   ReconciliationFrontierViolation, Fragment, ConsumerState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReconciliationFrontierViolation(RuntimeError):
    """Raised when a consumer commits a partial result whose raw fragment
    prefix no longer covers the producer's watermark, or when a patch
    targets a region already compacted away."""


@dataclass
class Fragment:
    sequence: int
    append: bool
    last_chunk: bool
    patch_target: int | None = None
    payload: bytes = b""


@dataclass
class ConsumerState:
    ack_frontier: int = 0
    last_applied: int = 0
    credit_window: int = 8
    heartbeat_interval_s: float = 2.0
    raw_buffer: dict[int, Fragment] = field(default_factory=dict)
    compacted_upto: int = 0

    def _raw_prefix_covers(self, lo: int, hi: int) -> bool:
        return all(seq in self.raw_buffer for seq in range(lo, hi + 1))

    def reconcile(self, frag: Fragment, producer_watermark: int) -> None:
        # Guard 1: no silent gaps between applied frontier and incoming frame.
        if frag.sequence != self.last_applied + 1:
            raise ReconciliationFrontierViolation(
                f"out-of-order frame {frag.sequence}; expected {self.last_applied + 1}"
            )

        # Guard 2: patch substrate must be live raw bytes, not a summary.
        if frag.patch_target is not None and frag.patch_target <= self.compacted_upto:
            raise ReconciliationFrontierViolation(
                f"patch target {frag.patch_target} lies in compacted region "
                f"(<= {self.compacted_upto}); raw substrate lost"
            )

        self.raw_buffer[frag.sequence] = frag
        self.last_applied = frag.sequence

        # Guard 3: compaction may only advance up to ack_frontier - lookback.
        safe_compact_upto = self.ack_frontier - self.credit_window
        if safe_compact_upto > self.compacted_upto:
            for seq in range(self.compacted_upto + 1, safe_compact_upto + 1):
                self.raw_buffer.pop(seq, None)
            self.compacted_upto = safe_compact_upto

    def on_backpressure_stall(self, producer_watermark: int, elapsed_s: float) -> str:
        # Distinguish a stall from completion. Never emit `completed` here.
        if producer_watermark > self.last_applied:
            raise ReconciliationFrontierViolation(
                f"producer watermark {producer_watermark} exceeds applied "
                f"{self.last_applied}: frames lost during stall"
            )
        if elapsed_s > 2 * self.heartbeat_interval_s and not self._raw_prefix_covers(
            self.ack_frontier, self.last_applied
        ):
            raise ReconciliationFrontierViolation(
                "stall with non-contiguous raw prefix; cannot resume safely"
            )
        # Safe to resume: shrink window to force serialized replay coverage.
        self.credit_window = 1
        return "input-required"


def resume_from_frontier(state: ConsumerState, producer_watermark: int) -> int:
    if state.last_applied < state.ack_frontier:
        raise ReconciliationFrontierViolation(
            "applied frontier behind ack frontier: inconsistent consumer state"
        )
    if not state._raw_prefix_covers(state.ack_frontier, state.last_applied):
        raise ReconciliationFrontierViolation(
            "replay request would target a gap; abort and request full replay"
        )
    return state.ack_frontier
