# What happens when an instance's eBPF tool-hook policy is keyed on process identity but the agent runtime multiplexes concurrent tool calls through one long-lived worker **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that enforce per-invocation tool and egress policy via kernel-level hooks (eBPF/LSM on `execve`, `connect`, `sendmsg`) keyed on PID/TGID or cgroup identity, where a single worker process services multiple concurrent agent invocations. Does not apply to runtimes that fork one process per tool call or that enforce policy purely in userspace at the dispatch layer. ## Core Distinction There are two distinct things an enforcement hook can be keyed on: the *invocation* (the logical agent task with its own warrant, capability set, and egress allowlist) and the *execution context* (the OS-level process, thread, or cgroup that the kernel actually sees). eBPF hooks only see the execution context. When the runtime maps many invocations onto one long-lived worker — the standard pattern for amortizing interpreter and model-client warmup — the mapping from invocation to process is many-to-one, and the hook's identity key silently collapses. The failure is not that the policy is wrong. The policy attached to *each invocation* is correct. The failure is that the kernel hook cannot distinguish which invocation a given `connect()` or `execve()` belongs to, so it applies the policy of whichever invocation the runtime most recently registered against that PID — or, worse, the union, intersection, or last-writer-wins of several. This is a *key-aliasing* failure: the enforcement substrate's identity dimension is coarser than the security domain's identity dimension. ## What Was Observed A runtime enforced egress allowlists per invocation by writing a BPF map entry keyed on `pid` at invocation start and deleting it at invocation end. The hook on `connect()` looked up `bpf_get_current_pid_tgid() >> 32` and consulted the entry's allowlist. Under single-invocation load this behaved correctly for thousands of calls. Under concurrency, three distinct anomalies appeared: 1. **Cross-invocation egress leakage.** Invocation A (allowlist: `api.vendor-a.com:443`) and invocation B (allowlist: `api.vendor-b.com:443`) ran concurrently on the same worker via `asyncio`. B's `connect()` to `api.vendor-b.com` succeeded while A's map entry was live, because the hook resolved the PID to A's entry and A's entry had not yet been overwritten. The egress was permitted by the wrong invocation's grant. The audit log attributed the connection to A. Neither the policy nor the connection was individually malformed; the attribution and the authorization were both aliased. 2. **Warrant downgrade on overwrite.** When B registered second, its map write replaced A's entry (same PID key). A's subsequent `connect()` to `api.vendor-a.com` was now evaluated against B's allowlist and denied. The agent observed a spurious `EACCES` mid-task, retried, and — because the retry logic treated `EACCES` as a transient sandbox fault — re-issued the call after B finished, at which point the entry had been deleted and the hook fell through to its default-deny, producing a second, differently-attributed failure. The agent's error-compounding loop was triggered by an enforcement artifact, not by a real capability deficit. 3. **Orphaned grants on worker crash.** A worker killed mid-invocation left its map entry in place (no `atexit`, no cleanup on `SIGKILL`). The next invocation scheduled onto a recycled PID inherited the dead invocation's allowlist until its own registration overwrote it. In the window between PID reuse and registration, a freshly spawned invocation ran with a *previous tenant's* egress rights. This is the most dangerous variant because it is silent and the inherited grant may be broader than the new invocation's. The tell across all three: the hook's decision was a function of *scheduling order and PID reuse*, not of the invocation's declared warrant. Replaying the same invocation sequence with different concurrency interleavings produced different permit/deny outcomes for identical calls. ## Condition of Validity The per-PID keying invariant holds only when the following conjunction is true: - **Injectivity:** at most one live invocation is bound to any PID/TGID at any instant (one-process-per-invocation, or a worker that is exclusively leased for the invocation's duration). - **Atomic bind/unbind:** the map entry is written before the first tool call and removed before the worker is released, with no window in which the worker executes agent-controlled code while unbound or bound to a stale entry. - **PID non-reuse across tenants:** a recycled PID never carries a prior invocation's entry into a new invocation's execution. In the observed runtime all three were false under concurrency: the worker was shared (violates injectivity), registration was racy with the first `await` (violates atomicity), and cleanup was best-effort (violates non-reuse). Any one violation is sufficient to break the invariant; the concurrency pattern violated all three simultaneously, which is why the anomalies were intermittent rather than constant. ## Decision Boundary The architectural choice is between two enforcement substrates, and the boundary is sharp: - **If the runtime multiplexes invocations onto shared workers**, the hook key *must* be an invocation-scoped identifier that the kernel can recover at syscall time. In practice this means either (a) a per-invocation cgroup or `BPF` cookie propagated via a thread-local that the runtime sets and the hook reads through a map keyed on `(tgid, invocation_nonce)`, or (b) a per-invocation file descriptor / socket token minted by the runtime and validated by an LSM hook on `socket_connect` against the token rather than the PID. PID alone is not admissible. - **If the runtime cannot supply an invocation-scoped key**, it must serialize invocations per worker (lease the worker exclusively) and accept the throughput cost. There is no correct configuration in which a shared worker enforces per-invocation egress policy keyed on PID. The boundary is crossed the moment two invocations with *different* policy sets share a PID. Below that line (identical policy sets) the aliasing is unobservable because the alias is behaviorally equivalent — which is exactly why the bug survives staging tests that use a single tenant. ## Operational Effect The practical consequences are: - **Audit integrity is lost before enforcement integrity is.** Even when the hook's decision happens to match the correct invocation's policy (because the policies coincided), the *attribution* is wrong. Forensic replay of the audit log reconstructs a history that did not happen. This is worse than a plain denial because it corrupts the evidence used to detect the denial. - **Agents mis-attribute enforcement failures to capability deficits.** A spurious `EACCES` from a warrant overwrite looks identical to a genuine missing grant. Agents that retry on `EACCES` amplify the error; agents that escalate on `EACCES` generate false escalation storms. The observed retry loop is the canonical error-compounding signature of an enforcement artifact masquerading as a policy decision. - **The failure is load-dependent and non-deterministic.** It does not reproduce under serialized test loads. It appears only when concurrency exceeds one and policy sets diverge, which is precisely the production regime the runtime was built for. - **PID reuse converts a correctness bug into a privilege-escalation bug.** The orphaned-grant variant is not a denial or a misattribution; it is a window in which a new invocation executes with a dead invocation's rights. The window is bounded by scheduling, not by policy, and is therefore unbounded in the worst case. The guardrail is a single invariant: *the enforcement key must be at least as fine-grained as the policy domain.* If the policy is per-invocation, the key must be per-invocation, and the kernel must be able to recover it at syscall time without trusting agent-controlled state. Anything coarser is an aliasing bug waiting for concurrency. ```python class EgressWarrantAliasingError(RuntimeError): """Raised when an eBPF tool/egress hook cannot resolve a syscall to a unique invocation-scoped warrant, i.e. the enforcement key (PID/TGID) is coarser than the policy domain (invocation).""" pass class InvocationWarrant: def __init__(self, invocation_id: str, allowlist: frozenset[str]): self.invocation_id = invocation_id self.allowlist = allowlist def bind_worker_to_invocation(worker_pid: int, warrant: InvocationWarrant, live_bindings: dict[int, str]) -> None: """Register an invocation's warrant against a worker PID. Refuses to bind if the PID already carries a live binding for a *different* invocation with a *different* allowlist. This is the guardrail: it converts a silent key-aliasing bug into a loud refusal at registration time, before any tool call executes. """ existing = live_bindings.get(worker_pid) if existing is not None and existing != warrant.invocation_id: raise EgressWarrantAliasingError( f"worker pid {worker_pid} already bound to invocation " f"{existing!r}; refusing to alias invocation " f"{warrant.invocation_id!r} onto the same enforcement key. " f"Lease the worker exclusively or key the hook on an " f"invocation nonce." ) live_bindings[worker_pid] = warrant.invocation_id def authorize_egress(worker_pid: int, dest: str, warrants: dict[str, InvocationWarrant], live_bindings: dict[int, str]) -> bool: """Hook-side decision. Fails closed if the binding is missing or if the resolved warrant does not cover the destination.""" invocation_id = live_bindings.get(worker_pid) if invocation_id is None: # Orphaned or unbound worker: default-deny, never default-allow. return False warrant = warrants.get(invocation_id) if warrant is None: raise EgressWarrantAliasingError( f"binding for pid {worker_pid} references unknown invocation " f"{invocation_id!r}; warrant table and binding table diverged." ) return dest in warrant.allowlist def unbind_worker(worker_pid: int, live_bindings: dict[int, str]) -> None: """Must run on every exit path including SIGKILL-adjacent cleanup; orphaned entries are the privilege-escalation vector on PID reuse.""" live_bindings.pop(worker_pid, None) ```