# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-capability-warrant-invalidation-when-a-sandboxed-tool-call-outlives-the-minting-task-s-lease.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-capability-warrant-invalidation-when-a-sandboxed-tool-call-outlives-the-minting-task-s-lease.warrant.json
# Markdown SHA-256:   716b6e4a10c42143469ce15f45fbdff85110e2c9d27be6bf87aa9367684a9268
# Code AST SHA-256:   3da7515328b0be69fda17ca2b76f9c615275b240701ee6ebc6277e71ec73c317
# Verified Classes:   WarrantRegimeError, Regime, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import os
import errno
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class WarrantRegimeError(RuntimeError):
    """Raised when a tool call would execute under an advisory (non-enforced) warrant."""
    pass


class Regime(Enum):
    FD_LEASE_BOUND = "fd_lease_bound"
    PATH_ALLOCATOR_BOUND = "path_allocator_bound"
    PATH_TTL_ONLY = "path_ttl_only"  # advisory — the failure regime


@dataclass(frozen=True)
class Warrant:
    lease_id: str
    regime: Regime
    fd: Optional[int] = None
    path: Optional[str] = None
    path_generation: Optional[int] = None
    expires_ms: int = 0


def assert_warrant_inheritable(warrant: Warrant, spawns_subprocess: bool) -> None:
    """
    Pre-execution guard. Must be called before any tool call that forks/execs
    or hands a descriptor to another process. Fails closed.
    """
    if not spawns_subprocess:
        return

    if warrant.regime is Regime.PATH_TTL_ONLY:
        # TTL-only path warrants have no kernel-side revocation. A subprocess
        # inheriting this warrant can outlive the lease and write to a path
        # that will be reassigned to a sibling task.
        raise WarrantRegimeError(
            f"warrant {warrant.lease_id} is PATH_TTL_ONLY; revocation is advisory "
            f"and cannot be enforced against inherited descriptors. Refusing to spawn."
        )

    if warrant.regime is Regime.FD_LEASE_BOUND and warrant.fd is None:
        raise WarrantRegimeError(
            f"warrant {warrant.lease_id} claims FD_LEASE_BOUND but carries no fd; "
            f"regime metadata is inconsistent, refusing to spawn."
        )

    if warrant.regime is Regime.PATH_ALLOCATOR_BOUND and warrant.path_generation is None:
        raise WarrantRegimeError(
            f"warrant {warrant.lease_id} claims PATH_ALLOCATOR_BOUND but carries no "
            f"path_generation; allocator invariant cannot be verified, refusing to spawn."
        )


def spawn_worker(warrant: Warrant, argv: list[str]) -> int:
    """Spawn a subprocess only under an inheritable warrant regime."""
    assert_warrant_inheritable(warrant, spawns_subprocess=True)
    pid = os.fork()
    if pid == 0:
        try:
            os.execvp(argv[0], argv)
        finally:
            os._exit(127)
    return pid


def verify_revocation(warrant: Warrant) -> None:
    """
    Post-lease check: confirm the warrant is actually dead at the kernel level,
    not merely marked revoked in the orchestrator's store.
    """
    if warrant.regime is Regime.FD_LEASE_BOUND:
        try:
            os.fstat(warrant.fd)  # type: ignore[arg-type]
        except OSError as e:
            if e.errno == errno.EBADF:
                return  # correctly revoked
            raise WarrantRegimeError(f"unexpected fstat error: {e}") from e
        raise WarrantRegimeError(
            f"warrant {warrant.lease_id} marked revoked but fd {warrant.fd} is still live; "
            f"revocation was advisory, not enforced."
        )
    raise WarrantRegimeError(
        f"warrant {warrant.lease_id} regime {warrant.regime.value} has no kernel-level "
        f"revocation check available; cannot verify."
    )
