# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-optimistic-cross-org-delegation-from-committing-a-speculative-sub-task-whose-parent-warrant-was-revoked-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-optimistic-cross-org-delegation-from-committing-a-speculative-sub-task-whose-parent-warrant-was-revoked-mid-flight.warrant.json
# Markdown SHA-256:   8d55484d07de4348e25fe5ea5042a9a652b54b4fa03a9d0bd3af53a727ae31db
# Code AST SHA-256:   f217507a88e948ea8714b7d97a956c3634b976f313559bd598a541ed4a7401f9
# Verified Classes:   RevocationFenceViolation, Warrant, EffectSink
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class RevocationFenceViolation(RuntimeError):
    """Raised when a commit is authorized against a revocation state
    causally older than the delegation point, or when the sink cannot
    prove causal consistency between delegation epoch and commit epoch."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    authority: str
    delegation_epoch: int          # epoch of `authority` observed at delegation
    expires_at: float


@dataclass
class EffectSink:
    # per-authority monotonic revocation epoch
    authority_epoch: Dict[str, int] = field(default_factory=dict)
    # staged effects keyed by (warrant_id, digest)
    staged: Dict[str, bytes] = field(default_factory=dict)
    applied: Dict[str, bytes] = field(default_factory=dict)

    def current_epoch(self, authority: str) -> int:
        return self.authority_epoch.get(authority, 0)

    def bump_epoch(self, authority: str) -> int:
        self.authority_epoch[authority] = self.current_epoch(authority) + 1
        return self.authority_epoch[authority]

    def stage(self, w: Warrant, digest: str, payload: bytes) -> None:
        if time.time() > w.expires_at:
            raise RevocationFenceViolation(
                f"warrant {w.warrant_id} expired before staging")
        # fence: staging is allowed only if the sink's epoch for the
        # authority has not advanced past the delegation epoch
        if self.current_epoch(w.authority) > w.delegation_epoch:
            raise RevocationFenceViolation(
                f"staging refused: authority {w.authority} epoch "
                f"{self.current_epoch(w.authority)} > delegation epoch "
                f"{w.delegation_epoch} for warrant {w.warrant_id}")
        self.staged[digest] = payload

    def commit(self, w: Warrant, digest: str) -> None:
        if digest not in self.staged:
            raise RevocationFenceViolation(
                f"commit of unstaged digest {digest} for {w.warrant_id}")
        # THE INVARIANT: the sink's epoch must not have advanced past the
        # delegation epoch. If it has, an ancestor revocation may have
        # occurred between delegation and commit; the staged effect is
        # causally unsafe and must be compensated, not applied.
        sink_epoch = self.current_epoch(w.authority)
        if sink_epoch > w.delegation_epoch:
            # reject and emit compensation directive naming staged effects
            self.staged.pop(digest, None)
            raise RevocationFenceViolation(
                f"commit refused for {w.warrant_id}: sink epoch "
                f"{sink_epoch} supersedes delegation epoch "
                f"{w.delegation_epoch}; staged effect {digest} compensated")
        self.applied[digest] = self.staged.pop(digest)


def run_optimistic_delegation(sink: EffectSink, w: Warrant,
                              digest: str, payload: bytes,
                              revoke_parent_midflight: bool) -> str:
    """Simulate the race: stage, then (optionally) revoke the parent
    authority mid-flight, then attempt commit."""
    sink.stage(w, digest, payload)
    if revoke_parent_midflight:
        # revocation applied at the parent authority; propagates to sink
        sink.bump_epoch(w.authority)
    try:
        sink.commit(w, digest)
    except RevocationFenceViolation as e:
        return f"COMPENSATED: {e}"
    return "COMMITTED"


# Demonstration of the fenced protocol under the observed race.
sink = EffectSink()
w = Warrant(warrant_id="W-sub-7", parent_id="W-parent-3",
            authority="org-a", delegation_epoch=4,
            expires_at=time.time() + 60)

print(run_optimistic_delegation(sink, w, "d1", b"effects", False))
print(run_optimistic_delegation(sink, w, "d2", b"effects", True))

# Without the epoch fence (list-membership only), the second call would
# have committed. The fence converts an undetectable divergence into a
# detectable compensation.
if "d2" in sink.applied:
    raise RevocationFenceViolation(
        "invariant broken: revoked sub-task committed under stale epoch")
