# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-compensated-a2a-task-the-compensation-epoch-invariant-and-the-idempotent-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-compensated-a2a-task-the-compensation-epoch-invariant-and-the-idempotent-retry-boundary.warrant.json
# Markdown SHA-256:   90bcc50d93bbe00d063d80d1827d16f5d6ee35571bef46453fdec1908c8de641
# Code AST SHA-256:   1e84653bf314bc4dbf6a66f511d0eae24a193bc9c54f0e4c82e6f4b2b0438637
# Verified Classes:   TaskState, StaleEpochError, CompensationInFlightError, DedupRecord, Worker
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    COMPENSATING = "compensating"
    COMPENSATED = "compensated"
    FAILED = "failed"


class StaleEpochError(RuntimeError):
    """Raised when a retry carries an idempotency key minted in a
    compensation epoch that has since been superseded. The forward
    effect was reversed; serving the cached body would resurrect it."""


class CompensationInFlightError(RuntimeError):
    """Raised when a retry lands during the compensating window, where
    the outcome is undecided and no cached body is safe to serve."""


@dataclass
class DedupRecord:
    state: TaskState
    body: Optional[dict]
    epoch: int


@dataclass
class Worker:
    # key -> record, scoped by epoch stored inside the record
    dedup: dict[str, DedupRecord] = field(default_factory=dict)
    # lineage -> current compensation epoch
    epoch: dict[str, int] = field(default_factory=dict)

    def handle_send(
        self,
        lineage: str,
        idempotency_key: str,
        compensation_epoch: int,
        payload: dict,
    ) -> dict:
        current_epoch = self.epoch.get(lineage, 0)
        record = self.dedup.get(idempotency_key)

        if record is not None:
            if record.state is TaskState.COMPENSATING:
                # Undecided window: never serve a cached body.
                raise CompensationInFlightError(
                    f"task {lineage} is compensating; retry after "
                    f"compensation deadline"
                )
            if record.epoch != current_epoch or compensation_epoch != current_epoch:
                # Key was minted in a pre-compensation epoch whose effects
                # were reversed. Do NOT dedup to success. Do NOT re-execute.
                raise StaleEpochError(
                    f"idempotency key {idempotency_key} belongs to epoch "
                    f"{record.epoch} but lineage {lineage} is at epoch "
                    f"{current_epoch}; forward effect was compensated"
                )
            # True duplicate within the current epoch: safe to replay.
            return record.body or {}

        # Fresh forward attempt.
        body = self._execute(payload)
        self.dedup[idempotency_key] = DedupRecord(
            state=TaskState.COMPLETED, body=body, epoch=current_epoch
        )
        return body

    def compensate(self, lineage: str, idempotency_key: str) -> None:
        record = self.dedup.get(idempotency_key)
        if record is None or record.state is not TaskState.COMPLETED:
            return
        record.state = TaskState.COMPENSATING
        self._reverse_effects(idempotency_key)
        # Atomic with the reversal in a real store; modeled sequentially here.
        record.state = TaskState.COMPENSATED
        record.body = None  # invalidate cached body
        self.epoch[lineage] = self.epoch.get(lineage, 0) + 1

    def _execute(self, payload: dict) -> dict:
        return {"artifact": f"handle-{payload.get('id', 'x')}"}

    def _reverse_effects(self, idempotency_key: str) -> None:
        pass
