# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-subcontracting-when-bid-acceptance-and-work-assignment-are-separated-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-subcontracting-when-bid-acceptance-and-work-assignment-are-separated-across-agent-handoffs.warrant.json
# Markdown SHA-256:   4ffd10ac59c5a535bee513dbc68d503c79f32858928b3052f9f89ee5d911c3fb
# Code AST SHA-256:   7cadbca65fcc0550078abf47d79a578fe832420394e7a1f4a08b1658119ad774
# Verified Classes:   DuplicateAssignment, SubtaskState, SubtaskRecord, ExecutorLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class DuplicateAssignment(RuntimeError):
    """Raised when an executor receives a second assignment for a subtask
    that is already in ASSIGNED or COMPLETED state under a different nonce."""


class SubtaskState(Enum):
    BIDDING = "bidding"
    ELECTED = "elected"          # winner chosen, acceptance sent, NOT yet working
    ASSIGNED = "assigned"        # assignment with nonce delivered
    COMPLETED = "completed"
    REVOKED = "revoked"


@dataclass
class SubtaskRecord:
    subtask_id: str
    state: SubtaskState = SubtaskState.BIDDING
    assigned_to: str | None = None
    assignment_nonce: str | None = None


@dataclass
class ExecutorLedger:
    # keyed on (subtask_id, assignment_nonce) -> result
    entries: dict[tuple[str, str], str] = field(default_factory=dict)
    # subtask_id -> nonce currently owning the work
    owner: dict[str, str] = field(default_factory=dict)

    def begin(self, subtask_id: str, nonce: str) -> str | None:
        existing = self.owner.get(subtask_id)
        if existing is not None and existing != nonce:
            raise DuplicateAssignment(
                f"subtask {subtask_id} already owned by nonce {existing}, "
                f"rejecting assignment under nonce {nonce}"
            )
        if (subtask_id, nonce) in self.entries:
            return self.entries[(subtask_id, nonce)]  # idempotent replay
        self.owner[subtask_id] = nonce
        return None

    def complete(self, subtask_id: str, nonce: str, result: str) -> None:
        if self.owner.get(subtask_id) != nonce:
            raise DuplicateAssignment(
                f"completion for {subtask_id} under nonce {nonce} but owner is "
                f"{self.owner.get(subtask_id)}"
            )
        self.entries[(subtask_id, nonce)] = result


def assign(record: SubtaskRecord, executor: str, nonce: str,
           ledger: ExecutorLedger) -> str | None:
    """Contractor-side assignment gated on subtask state, plus executor-side
    nonce check. Rejects re-assignment of an already-ASSIGNED subtask."""
    if record.state in (SubtaskState.ASSIGNED, SubtaskState.COMPLETED):
        if record.assignment_nonce == nonce and record.assigned_to == executor:
            return ledger.begin(record.subtask_id, nonce)  # safe replay
        raise DuplicateAssignment(
            f"subtask {record.subtask_id} already {record.state.value} under "
            f"nonce {record.assignment_nonce} to {record.assigned_to}; "
            f"refusing assignment to {executor} under nonce {nonce}"
        )
    if record.state is not SubtaskState.ELECTED or record.assigned_to != executor:
        raise DuplicateAssignment(
            f"subtask {record.subtask_id} not in ELECTED state for {executor}"
        )
    record.state = SubtaskState.ASSIGNED
    record.assignment_nonce = nonce
    return ledger.begin(record.subtask_id, nonce)
