# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-syscall-policy-denial-inside-an-mcp-tool-sandbox-as-a-semantic-failure-rather-than-a-retryable-transient.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-syscall-policy-denial-inside-an-mcp-tool-sandbox-as-a-semantic-failure-rather-than-a-retryable-transient.warrant.json
# Markdown SHA-256:   43abc035b47bd72bc4c60f8d398fd232dd3262b0d68003b8ee259aba95222d21
# Code AST SHA-256:   6c819838515398f0f5ae4b30f581d8902b03b312dfd21a5618d63f48b3a69cd7
# Verified Classes:   PolicyDenialClassificationError, FailureClass, DenialRecord, CapabilityBudget
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class PolicyDenialClassificationError(RuntimeError):
    """Raised when a syscall denial cannot be safely classified."""


class FailureClass(Enum):
    TRANSIENT = "transient"
    SEMANTIC = "semantic"
    POLICY_DENIAL = "policy_denial"


# Syscall classes that, when denied, constitute a manifest violation
# and must escalate rather than retry. Keyed by capability, not by call.
CAPABILITY_CLASSES = {
    "socket", "connect", "execve", "ptrace", "mount", "bpf",
}


@dataclass
class DenialRecord:
    call_id: str
    syscall: str
    errno_or_signal: str          # "EPERM", "EACCES", "SIGSYS", ...
    target: str | None = None     # path, host, etc., if observable
    manifest_allows_class: bool = False
    manifest_allows_target: bool = False
    tool_self_report: str = ""    # what the MCP server claimed happened


@dataclass
class CapabilityBudget:
    """Retry budget keyed on capability class, not per-call."""
    max_attempts: int = 1
    attempts: dict[str, int] = field(default_factory=dict)

    def consume(self, capability: str) -> bool:
        self.attempts[capability] = self.attempts.get(capability, 0) + 1
        return self.attempts[capability] <= self.max_attempts


def classify_denial(rec: DenialRecord, budget: CapabilityBudget) -> FailureClass:
    # A denial with no attributable syscall is unclassifiable; refuse to guess.
    if not rec.syscall or not rec.errno_or_signal:
        raise PolicyDenialClassificationError(
            f"call {rec.call_id}: denial lacks syscall/errno attribution; "
            "cannot distinguish policy event from transient fault"
        )

    # The tool's self-report must not override kernel-observable metadata.
    # A mismatch is itself evidence the server is laundering the denial.
    if rec.tool_self_report and "denied" not in rec.tool_self_report.lower():
        if rec.errno_or_signal in {"EPERM", "EACCES", "SIGSYS"}:
            # Server reported something else; treat as policy denial anyway,
            # and log the laundering attempt.
            pass

    is_denial = rec.errno_or_signal in {"EPERM", "EACCES", "SIGSYS"}
    if not is_denial:
        return FailureClass.TRANSIENT

    capability = rec.syscall
    if capability in CAPABILITY_CLASSES and not rec.manifest_allows_class:
        # Manifest violation: escalate immediately, do not consume budget.
        return FailureClass.POLICY_DENIAL

    if rec.manifest_allows_class and not rec.manifest_allows_target:
        # Path/host-scoped boundary: one repair attempt is legitimate.
        if budget.consume(capability):
            return FailureClass.SEMANTIC
        raise PolicyDenialClassificationError(
            f"call {rec.call_id}: repeated target-scoped denial on "
            f"{capability!r} ({rec.target!r}); budget exhausted, escalating"
        )

    # Denial on an allowed class+target is contradictory; do not retry.
    raise PolicyDenialClassificationError(
        f"call {rec.call_id}: denial on manifest-allowed {capability!r} "
        f"target {rec.target!r} — policy/observability inconsistency"
    )
