# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-has-already-acknowledged-the-audit-commitment-ordering-hazard-in-cross-org-multi-agent-fe.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-has-already-acknowledged-the-audit-commitment-ordering-hazard-in-cross-org-multi-agent-fe.warrant.json
# Markdown SHA-256:   907e567d5a5b35a6774d8cf7289c6b2ebce86a802942bc3fb1ae91e173fefdd6
# Code AST SHA-256:   6c5099eb11f18afb2f4653827e397aa17c63f7b6d51f483ebb23ad2d285d8037
# Verified Classes:   AuditCommitError, GrantNotCommittedError, GrantState, FederatedGrant, FederationRuntime
# 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 AuditCommitError(RuntimeError):
    """Raised when a local audit record cannot be durably committed."""
    pass


class GrantNotCommittedError(RuntimeError):
    """Raised when a grant is exercised before its audit record is durable."""
    pass


class GrantState(Enum):
    PROPOSED = "proposed"
    ACKED_UNCOMMITTED = "acked_uncommitted"
    ACTIVE = "active"
    REVOKED = "revoked"


@dataclass
class FederatedGrant:
    nonce: str
    capability: str
    peer_org: str
    state: GrantState = GrantState.PROPOSED
    acked_at: Optional[float] = None
    committed_at: Optional[float] = None
    retracted_at: Optional[float] = None
    grace_seconds: float = 2.0


class FederationRuntime:
    def __init__(self, audit_store, fallback_sink, retract_fn, circuit_breaker):
        self.audit_store = audit_store
        self.fallback_sink = fallback_sink
        self.retract_fn = retract_fn
        self.circuit_breaker = circuit_breaker
        self.grants = {}

    def on_grant_ack(self, grant: FederatedGrant) -> None:
        # Peer has acknowledged; local audit is NOT yet durable.
        grant.state = GrantState.ACKED_UNCOMMITTED
        grant.acked_at = time.monotonic()
        self.grants[grant.nonce] = grant

        try:
            self.audit_store.commit(
                kind="GrantAcknowledged",
                nonce=grant.nonce,
                capability=grant.capability,
                peer_org=grant.peer_org,
            )
        except AuditCommitError as exc:
            # Cannot prove the promise: retract rather than serve.
            self._retract(grant, reason=f"audit_commit_failed: {exc}")
            raise GrantNotCommittedError(
                f"grant {grant.nonce} acked by peer but local audit failed; retracted"
            ) from exc

        grant.committed_at = time.monotonic()
        grant.state = GrantState.ACTIVE

    def _retract(self, grant: FederatedGrant, reason: str) -> None:
        grant.state = GrantState.REVOKED
        grant.retracted_at = time.monotonic()
        # Fallback sink must fsync; it is the only trustworthy record right now.
        self.fallback_sink.record(
            kind="GrantRetracted",
            nonce=grant.nonce,
            reason=reason,
        )
        self.retract_fn(grant.nonce)
        self.circuit_breaker.trip(reason=reason)

    def on_invocation(self, nonce: str, payload: bytes) -> bytes:
        grant = self.grants.get(nonce)
        if grant is None:
            raise GrantNotCommittedError(f"unknown grant {nonce}")

        if grant.state is GrantState.ACTIVE:
            self.audit_store.commit(kind="InvocationUnderGrant", nonce=nonce)
            return self._serve(grant, payload)

        if grant.state is GrantState.ACKED_UNCOMMITTED:
            elapsed = time.monotonic() - (grant.acked_at or time.monotonic())
            if elapsed > grant.grace_seconds:
                self._retract(grant, reason="ack_uncommitted_grace_expired")
                raise GrantNotCommittedError(
                    f"grant {nonce} never committed within grace; retracted"
                )
            # Safe-to-serve unaudited path: record to fallback, then serve.
            self.fallback_sink.record(
                kind="InvocationUncommitted",
                nonce=nonce,
                bytes=len(payload),
            )
            return self._serve(grant, payload)

        raise GrantNotCommittedError(f"grant {nonce} is {grant.state.value}")

    def _serve(self, grant: FederatedGrant, payload: bytes) -> bytes:
        # Placeholder for the actual capability execution.
        return b""
