# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-sandboxes-from-leaking-state-across-syscall-level-isolation-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-sandboxes-from-leaking-state-across-syscall-level-isolation-boundaries.warrant.json
# Markdown SHA-256:   fdf0669b5ae04f6c90ea6f57181e1f19d84b912960246a2e9d29591530d8b6d8
# Code AST SHA-256:   4f8936e0b8cb6b5e734a27cc0655f372eeff4614683e2d9632d958d9d60ba514
# Verified Classes:   SandboxIsolationViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SandboxIsolationViolation(RuntimeError):
    """Raised when a process-group reuse would expose a stateful syscall surface
    to a tool that did not declare it, or when egress is evaluated pre-resolution."""
    pass


STATEFUL_SYSCALLS = {"socket", "bind", "connect", "memfd_create", "shm_open", "sendmsg"}


def plan_sandbox_group(tools: list[dict]) -> dict:
    """
    tools: [{"name": str, "syscalls": set[str], "egress": list[str], "resolver": str}]
    Returns a plan with either 'reuse' or 'rebuild_per_invocation'.
    """
    if not tools:
        return {"mode": "reuse", "shared_syscalls": set(), "shared_egress": []}

    # Invariant 1: shared syscall surface is the intersection, not the union.
    shared = set.intersection(*(set(t["syscalls"]) for t in tools))
    stateful_shared = shared & STATEFUL_SYSCALLS

    # Invariant 2: egress must be evaluated post-resolution.
    for t in tools:
        if t["egress"] and t.get("resolver") == "local_socket":
            raise SandboxIsolationViolation(
                f"tool {t['name']!r} declares hostname egress but resolves via "
                f"local socket; egress cannot be enforced on resolved endpoint"
            )

    # A stateful syscall shared across tools means one tool can reach a resource
    # the other bound, because neither manifest named it as shared.
    if stateful_shared:
        return {
            "mode": "rebuild_per_invocation",
            "reason": f"stateful syscalls shared across tools: {sorted(stateful_shared)}",
            "shared_syscalls": shared,
            "shared_egress": [],
        }

    # Safe to reuse: shared surface has no stateful side effects.
    shared_egress = sorted(set.intersection(*(set(t["egress"]) for t in tools))) if tools else []
    return {
        "mode": "reuse",
        "shared_syscalls": shared,
        "shared_egress": shared_egress,
    }


def admit_invocation(group_plan: dict, tool: dict) -> None:
    """Called at each tool invocation. Enforces the plan's mode."""
    if group_plan["mode"] == "reuse":
        leaked = (set(tool["syscalls"]) & STATEFUL_SYSCALLS) - group_plan["shared_syscalls"]
        if leaked:
            # Tool declares a stateful syscall the group does not share; reusing
            # the group would expose it to peers. Must rebuild.
            raise SandboxIsolationViolation(
                f"tool {tool['name']!r} requires {sorted(leaked)} not in shared "
                f"surface; group must be rebuilt, not reused"
            )
    # rebuild mode: no check needed, namespace is fresh
