# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-writes-when-two-agents-commit-to-the-same-shared-workspace-slot-before-either-observes-the-other-s-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-writes-when-two-agents-commit-to-the-same-shared-workspace-slot-before-either-observes-the-other-s-epoch.warrant.json
# Markdown SHA-256:   7cb68d9ea30f2bcd141da99aa73bc8dece37b9d5e0719a51ce0abcd9418661a3
# Code AST SHA-256:   ab92ff60420d64aca1031776f2722f5284692f375f5c7e5136833337a896cb9e
# Verified Classes:   StaleEpochError, Workspace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleEpochError(RuntimeError):
    """Raised when a speculative commit's base epoch no longer matches the slot."""
    def __init__(self, slot: str, expected: int, actual: int):
        self.slot = slot
        self.expected = expected
        self.actual = actual
        super().__init__(
            f"speculative commit on {slot!r} based on epoch {expected} "
            f"rejected: slot is at epoch {actual}; discard buffer and rebase"
        )


class Workspace:
    def __init__(self):
        self._slots: dict[str, tuple[int, object]] = {}

    def read(self, slot: str) -> tuple[int, object]:
        epoch, value = self._slots.get(slot, (0, None))
        return epoch, value

    def commit(self, slot: str, base_epoch: int, value: object) -> int:
        current_epoch, _ = self._slots.get(slot, (0, None))
        if current_epoch != base_epoch:
            # Non-commutative slot: reject, never last-writer-wins.
            raise StaleEpochError(slot, base_epoch, current_epoch)
        new_epoch = current_epoch + 1
        self._slots[slot] = (new_epoch, value)
        return new_epoch


def speculative_commit(ws: Workspace, slot: str, base_epoch: int, value: object,
                       max_rebases: int = 3) -> int:
    """Commit a speculative write, rebasing on epoch collision up to a bound."""
    for attempt in range(max_rebases + 1):
        try:
            return ws.commit(slot, base_epoch, value)
        except StaleEpochError as err:
            if attempt == max_rebases:
                # Bounded abort: escalate to serialization, do not spin.
                raise StaleEpochError(err.slot, base_epoch, err.actual) from err
            # Rebase: re-read the surviving epoch and re-derive before retrying.
            base_epoch, _ = ws.read(slot)
    raise StaleEpochError(slot, base_epoch, -1)  # unreachable guard
