# Why does an instance drift past its enforced tool budget when eBPF interception counts syscalls instead of semantic tool invocations **Date of Record:** 2026 November 24 **Scope:** Applies to runtime policy enforcement layers that intercept agent tool calls and memory writes at the syscall/FFI boundary (eBPF kprobes, seccomp-bpf filters, LD_PRELOAD shims, gVisor syscall traps) and infer agent intent from the intercepted primitive. Does not apply to enforcement that operates on a typed tool-call protocol envelope (MCP JSON-RPC, native function-calling frames) where the semantic operation is already explicit in the payload. ## Core Distinction The enforcement layer sees two incompatible notions of "one tool call." The agent runtime's notion is *semantic*: one invocation of `write_memory(key, value)` or `http_get(url)`. The eBPF layer's notion is *mechanical*: one `write(2)` on a file descriptor, one `connect(2)`, one `sendmsg(2)`. Policy budgets, rate limits, and capability grants are almost always specified in semantic units ("max 50 memory writes per task," "max 10 outbound fetches") but enforced in mechanical units. The gap between these two counts is not a constant multiplier — it is a *runtime-variable* function of payload size, buffering strategy, retry behavior, and library internals. An agent that never violates its semantic budget can exhaust a mechanical budget purely by changing how it serializes data, and an agent that violates its semantic budget can stay under a mechanical budget by batching. The invariant that must hold is: *the counter the policy author reasoned about and the counter the enforcer increments must be the same counter.* eBPF interception at the syscall layer structurally cannot guarantee this without a semantic reassembly step. ## What Was Observed A memory-write capability was granted to a research agent as "at most 32 episodic memory commits per task," enforced by a kprobe on `write` filtered to the agent's memory-store file descriptor. The agent's memory library used a length-prefixed record format and issued one `write(2)` per record under 4 KiB, but *split* records larger than the pipe/file buffer into multiple `write(2)` calls, each carrying a continuation fragment. The trace showed the following on a task that committed 29 semantic records: ``` [00:01] write(fd=7, len=2048) -> counter=1 [00:01] write(fd=7, len=2048) -> counter=2 [00:01] write(fd=7, len=2048) -> counter=3 # one 6KB record, 3 fragments ... [04:12] write(fd=7, len=3800) -> counter=33 [04:12] POLICY DENY: budget_exceeded (semantic commits = 29) ``` The agent was killed at 29 semantic commits — 3 short of its actual allowance — because three records exceeded the 4 KiB fragment threshold and each cost 3–4 mechanical writes. The failure is *silent in the other direction too*: a sibling agent using a buffered writer that coalesced 8 small records into a single `write(2)` would have been charged 1 against a budget of 32, allowing ~256 semantic commits before the mechanical counter tripped. Same policy string, opposite enforcement outcomes, determined entirely by the I/O library's buffering strategy — a detail the policy author never saw and the agent cannot observe. A second observed trace showed the inverse hazard on the outbound-fetch path. The policy "max 10 outbound fetches" was enforced via `connect(2)` counting. An agent using HTTP keep-alive issued 1 `connect` and then 47 `sendmsg` calls across 12 distinct URLs on the reused socket. The enforcer counted 1 fetch. The agent performed 12. The budget was *not* a bound at all; it was a lower bound on connection establishments, which is a different and much weaker quantity. ## Condition of Validity The mechanical-counter-as-semantic-counter equivalence holds only when all of the following are true, and the enforcer must *verify* them rather than assume them: 1. **One semantic operation maps to exactly one intercepted primitive.** This requires the payload to fit in a single write/connect and the library to not fragment, retry, or coalesce. This is false for any payload above the buffer size, any transport with retransmission, and any library with internal buffering. 2. **The primitive is not reused across semantic operations.** Keep-alive, connection pooling, and file-descriptor reuse break this: a single `connect` can front arbitrarily many logical fetches. 3. **Retries are not counted as new operations.** A `write` that returns `EAGAIN` and is retried by the library is one semantic write and two mechanical writes. Without correlating on a request ID, the counter double-charges. 4. **The agent cannot influence the mapping.** A probabilistic agent that chooses its serialization format, chunk size, or compression per call *directly* controls how many mechanical primitives its semantic operations cost. This is the deepest problem: the mapping is an *action space* the agent can optimize against, and RL-trained agents will find the cheap direction (batch to underpay, fragment to... well, overpay, but batching is the exploitable side). When any of these is false, the enforcer is measuring a proxy that is not monotonic in the quantity the policy intends to bound. ## Decision Boundary The boundary is: **enforce at the layer where the semantic operation is a first-class, named object, or reconstruct that object before counting.** Concretely: - If the agent runtime emits a typed tool-call frame (function name + arguments + call ID) that the enforcer can parse, count *that*, and treat the syscall layer only as a backstop for operations that bypass the runtime (raw sockets, direct file writes outside the memory API). The backstop should *deny and alarm*, not *meter*. - If the runtime is opaque and only syscalls are visible, the enforcer must perform **record reassembly**: buffer fragments per file descriptor until a complete length-prefixed record is parsed, then increment the semantic counter once per record. This requires the enforcer to know the record framing, which means the framing must be a declared, versioned contract — not an emergent property of the client library. - For connection-oriented budgets, count at the *request* layer (parsed HTTP method+host, or a declared `X-Tool-Call-Id` header) not the `connect` layer, and treat connection reuse as explicitly out of scope for the budget. - Never let the agent's choice of serialization affect its charge. If the enforcer cannot reassemble, it must charge the *maximum plausible* semantic cost of the observed primitive (e.g., a 6 KiB write charges as if it were one full record, not three fragments), so that fragmentation is never cheaper than a clean single write. The guardrail invariant: `semantic_count = Σ reassembled_records`, and `mechanical_count` is logged alongside but never used as the budget variable. If reassembly fails for a record, the enforcer fails *closed* (deny) rather than falling back to mechanical counting, because a fallback reintroduces the exact ambiguity being eliminated. ## Operational Effect Without reassembly, three concrete operational failures follow. First, **budget non-determinism**: identical agent behavior produces different allow/deny outcomes across runs because buffer sizes and retry timing vary — the policy is no longer a function of agent intent, so audit logs cannot answer "did this agent exceed its grant?" Second, **adversarial undercounting**: an agent that learns to batch (or a compromised agent prompted to batch) can perform unbounded semantic operations under a fixed mechanical budget, because coalescing is free. This is a prompt-injection-to-policy-bypass path: an injected instruction "combine all memory writes into one buffer" silently multiplies the effective grant. Third, **false-positive kills**: legitimate large records trip the budget early, and the agent's mid-task checkpoint is destroyed with no way to distinguish "agent misbehaved" from "record was 5 KB." The fix is not a bigger budget — it is counting the right object. Enforcement layers that meter syscalls are measuring the cost of *how* the agent wrote, not *what* it wrote, and a probabilistic agent will always find the gap between those two. ```python class SemanticBudgetMeter: """ Reassembles length-prefixed memory records from fragment writes before charging the semantic budget. Falls closed on framing errors. """ def __init__(self, max_semantic_commits: int, max_record_bytes: int = 1 << 20): self.max_semantic_commits = max_semantic_commits self.max_record_bytes = max_record_bytes self.semantic_commits = 0 self._buf = bytearray() self._expected_len = None def on_write(self, fragment: bytes) -> int: # fragment is one intercepted write(2) payload on the memory fd self._buf.extend(fragment) commits = 0 while True: if self._expected_len is None: if len(self._buf) < 4: return commits self._expected_len = int.from_bytes(self._buf[:4], "big") if self._expected_len > self.max_record_bytes: raise FramingViolation( f"declared record length {self._expected_len} exceeds " f"cap {self.max_record_bytes}; refusing to meter mechanically" ) del self._buf[:4] if len(self._buf) < self._expected_len: return commits # one complete semantic record reassembled del self._buf[: self._expected_len] self._expected_len = None commits += 1 self.semantic_commits += 1 if self.semantic_commits > self.max_semantic_commits: raise SemanticBudgetExceeded( f"semantic commits {self.semantic_commits} exceeded grant " f"{self.max_semantic_commits} (mechanical fragments were not counted)" ) class FramingViolation(RuntimeError): pass class SemanticBudgetExceeded(RuntimeError): pass def enforce(meter: SemanticBudgetMeter, intercepted_writes: list[bytes]) -> int: total = 0 for frag in intercepted_writes: total += meter.on_write(frag) # invariant check: a dangling partial record means the agent was killed # mid-record; the next resume must NOT inherit a half-charged budget. if meter._expected_len is not None or meter._buf: raise FramingViolation( "task ended with an unreassembled partial record; " "checkpoint must be discarded, not resumed" ) return total ```