# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-supervisor-s-re-dispatch-after-a-partial-batch-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-supervisor-s-re-dispatch-after-a-partial-batch-failure.warrant.json
# Markdown SHA-256:   087554d00edc7b1cc694dee82dfefbc0b9914c214e05ce8c9e537ac0ff706697
# Code AST SHA-256:   9a72e732c623cfea91ab4769c3b01a88cdbb44df9041c99b2661bd95cd11b79c
# Verified Classes:   ContinuityViolation, AttemptState, Attempt, AttemptLedger, Worker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ContinuityViolation(RuntimeError):
    """Raised when a worker is asked to execute an item whose prior attempt
    may have reached a non-idempotent effect and cannot be proven otherwise."""
    pass


class AttemptState(Enum):
    PRE_EFFECT = "pre_effect"
    POST_EFFECT = "post_effect"
    UNKNOWN_EFFECT = "unknown_effect"


@dataclass
class Attempt:
    attempt_id: str
    item_id: str
    state: AttemptState
    started_at: float


class AttemptLedger:
    """Shared, worker-readable ledger. Must be reachable to authorize execution."""

    def __init__(self) -> None:
        self._attempts: dict[str, list[Attempt]] = {}
        self._reachable = True

    def set_reachable(self, reachable: bool) -> None:
        self._reachable = reachable

    def prior_attempts(self, item_id: str) -> list[Attempt]:
        if not self._reachable:
            raise ContinuityViolation(
                f"ledger unreachable while checking item {item_id!r}; "
                "refusing to authorize execution (fail closed)"
            )
        return list(self._attempts.get(item_id, []))

    def record(self, attempt: Attempt) -> None:
        if not self._reachable:
            raise ContinuityViolation(
                f"ledger unreachable while recording attempt {attempt.attempt_id!r}"
            )
        self._attempts.setdefault(attempt.item_id, []).append(attempt)


class Worker:
    def __init__(self, worker_id: str, ledger: AttemptLedger) -> None:
        self.worker_id = worker_id
        self.ledger = ledger

    def _authorize(self, item_id: str) -> Optional[str]:
        """Return a fresh attempt_id if execution is authorized, else raise."""
        priors = self.ledger.prior_attempts(item_id)
        for prior in priors:
            if prior.state in (AttemptState.POST_EFFECT, AttemptState.UNKNOWN_EFFECT):
                raise ContinuityViolation(
                    f"item {item_id!r} has prior attempt {prior.attempt_id!r} in state "
                    f"{prior.state.value}; re-dispatch refused, escalate to reconciliation"
                )
        # No prior attempt reached effect. Pre-effect retries are safe.
        return f"{self.worker_id}:{item_id}:{int(time.time() * 1000)}"

    def execute(self, item_id: str, payload: dict) -> str:
        attempt_id = self._authorize(item_id)
        attempt = Attempt(
            attempt_id=attempt_id,
            item_id=item_id,
            state=AttemptState.PRE_EFFECT,
            started_at=time.time(),
        )
        self.ledger.record(attempt)

        # Non-idempotent effect begins here. Mark intent before the effect so a
        # crash mid-effect is recorded as UNKNOWN_EFFECT, not PRE_EFFECT.
        try:
            version_id = self._write_versioned(item_id, payload)
            attempt.state = AttemptState.POST_EFFECT
        except Exception:
            attempt.state = AttemptState.UNKNOWN_EFFECT
            raise
        finally:
            # Re-record the terminal state; ledger is append-only per attempt.
            self.ledger.record(attempt)

        return version_id

    def _write_versioned(self, item_id: str, payload: dict) -> str:
        # Placeholder for the versioned-store write. The key point is that the
        # effect is non-idempotent unless the store dedupes on item_id.
        return f"v-{item_id}-{int(time.time() * 1000)}"


def supervisor_redispatch(worker: Worker, item_id: str, payload: dict) -> str:
    """Supervisor-side re-dispatch. The worker is the authorizing party."""
    return worker.execute(item_id, payload)


if __name__ == "__main__":
    ledger = AttemptLedger()
    worker = Worker("w1", ledger)

    # Normal path: first attempt, no priors, executes.
    supervisor_redispatch(worker, "item-17", {"body": "x"})

    # Simulate a prior attempt that reached effect (post-timeout commit).
    ledger.record(Attempt(
        attempt_id="w1:item-17:earlier",
        item_id="item-17",
        state=AttemptState.POST_EFFECT,
        started_at=time.time() - 60,
    ))

    # Supervisor re-dispatches the "failed" item. Worker must refuse.
    try:
        supervisor_redispatch(worker, "item-17", {"body": "x"})
    except ContinuityViolation as exc:
        print(f"refused: {exc}")

    # Ledger outage: worker must also refuse, not "try anyway".
    ledger.set_reachable(False)
    try:
        supervisor_redispatch(worker, "item-18", {"body": "y"})
    except ContinuityViolation as exc:
        print(f"refused (ledger down): {exc}")
