One of the things I like most about running agents inside the database (it’s the whole idea behind pg-synapse, my open-source project for in-database agents) is what you inherit for free. Roles, grants, row-level security, audit, transactions. Thirty years of boring, battle-tested controls apply to an agent the same way they apply to any other workload in Postgres, and that is a lot more governance than most agent frameworks ship with.
There is one problem that doesn’t map cleanly onto any of it, and it has been rattling around my head for a couple of months. Agents write code. Sometimes you ask them to, sometimes a tool needs a quick transform, and sometimes the model just decides Python is the answer. Nobody reads that code before it runs, and the model writing it may have just read a web page that told it to do something rude.
The industry has mostly settled on an answer: run untrusted code in an isolated sandbox, trust nothing it tells you, and keep it far away from anything you care about. The hosted code-execution services spin up a microVM or a gVisor sandbox per session, and they are good at it. The trouble is that last clause. If your agent lives next to your data, the whole point is that its code runs next to your data. Shipping rows off to somebody else’s VM so it can compute a moving average kind of defeats the purpose.
So I’ve been building and testing a sandbox that lives with the database. It’s a lab project and it’s early. Here is the thinking so far.
The backend is the worst place to run this#
Start with what not to do. PL/Python only exists as an untrusted language (that’s the “u” in plpython3u), and the Postgres docs say plainly that it offers no way to restrict what a user does with it. The trusted languages that do exist, like PL/v8 and PL/Rust or anything built on the pg_tle framework, restrict the language, but the code still runs inside the backend process.
A backend is about the most sensitive place on the box. It sits on shared buffers and locks and can read anything its role can. If one backend segfaults, the postmaster restarts every connection to protect shared memory, so one bad PDF parsed in the wrong place takes the whole server down for everybody. I have been on the receiving end of enough 3 a.m. pages to know that “the database restarted because an LLM got creative” is not a postmortem I want to write.
Postgres also has no per-function resource limits. statement_timeout depends on the running code checking for interrupts, so extension code that never checks keeps burning a core long after the timeout fires. And nothing in Postgres stops C or untrusted-language code from opening a socket. So rule one became simple: untrusted bytes never get parsed inside the database process, and untrusted code never runs there.
The process model turns out to be a gift#
This is the part that surprised me. Any database can start a helper process, so that alone isn’t the interesting bit. What Postgres’s process-per-connection model gives you is a natural owner for that helper. Each helper belongs to exactly one backend, which is its parent and the only thing that talks to it. When Postgres cancels a query or terminates a session, the signal already goes to the backend’s whole process group, so most of the cleanup rides on plumbing Postgres already has.
So for each call, the backend starts a fresh helper binary with a cleared environment, pipes and no shell. It’s a new program, not a fork of the backend, so it carries none of the backend’s shared memory. Before it reads a single byte of input, the helper locks itself down in a fixed order: close every inherited file descriptor, set hard limits on memory and CPU, set no_new_privs, unshare namespaces and apply Landlock with zero filesystem rights where the kernel allows them, and finally install a seccomp filter whose default action is to kill the process. Then it says READY.
It does one job, hands back an answer and gets thrown away. There’s no pool, because a round trip costs about half a millisecond, which is cheap enough that sharing state between calls isn’t worth the risk. A helper that crashes or runs out of memory now costs one SQL error instead of a cluster restart. By default the helper runs as the postgres OS user. A small, optional setuid launcher can run it as a separate user, but the design assumes that launcher might not be installed, so the other layers have to hold on their own.
Don’t take the sandbox’s word for it#
If I had to put one lesson on a sticky note, it would be this one. Early versions believed the helper when it reported it was sandboxed. A compromised helper, or a fake one, can report anything it likes.
Now the backend asks the kernel. After READY and before any input crosses, the backend reads /proc/<pid>/status and /proc/<pid>/limits itself and checks:
- seccomp mode 2, with more filters than the backend has (a container’s inherited profile also shows mode 2, so the mode alone can lie)
no_new_privsset, the expected uid in all four fields, and zero capabilities- exactly the memory and CPU limits the backend asked for
- one thread, no children, and the right binary
If anything is off, the helper is stopped and never sees the input. The whole check costs 17 to 29 microseconds.
The obvious objection is that the helper could pass the check and change afterward. It can’t, because everything checked only goes one way. A seccomp filter can’t be removed, no_new_privs can’t be cleared, hard limits can’t be raised without a capability the helper doesn’t have, and the filter kills any attempt to create a thread. The pid can’t be recycled under the backend either, because the backend hasn’t reaped its child yet.
The same attitude applies on the way out. An answer counts only if the helper exited cleanly; an answer followed by a sandbox kill gets discarded, so an exploit can’t reply and then die quietly. The answer is never handed straight to jsonb_in, either. It is rebuilt against a closed schema with sizes derived from the input: no floats, and integers capped at 2^53.
Two walls for code the model writes#
For the database’s own parsers, that’s a reasonable setup. The code is fixed and the attacker only controls input bytes, so an escape needs a parser bug first and a kernel bug second. It’s the same pattern browsers use to isolate their renderers.
Model-written code is a different animal, because the attacker writes the program. There is no step one: the code can call every allowed syscall from its first instruction. Every layer I just described is enforced by the same kernel, so a single kernel bug beats them all at once, and stacking more shared-kernel layers doesn’t change that math.
The textbook answer is a second kernel, meaning gVisor or a microVM. I wanted to see how far I could get without adding infrastructure first, so I put a second wall inside the helper instead. CPython is compiled to WebAssembly (the WASI build, a tier 2 CPython platform since 3.13) and runs under wasmi, a pure interpreter. No JIT means no executable memory, which means the seccomp filter can keep killing any attempt to map executable pages. The guest is snapshotted with Wizer after the standard library loads, so nothing is read from disk at run time, and the helper checks the guest file’s SHA-256 on every call.
The Python code inside reaches the outside world through about fifteen host functions: read the request, write the result, write a capped log, get random bytes, exit, and read a clock that doesn’t advance. Paths and sockets just answer “not supported.” After lockdown, the helper running that guest was observed making eight distinct syscalls (brk, exit_group, getrandom, mmap, mremap, munmap, read, write); the filter allows a few more so that a failed allocation can end in a clean abort. An escape now needs a CPython bug, then a wasmi bug, then a kernel bug reachable through that short list.
The frozen clock does more work than it looks like, because it takes away the easy high-resolution timer that timing side-channel tricks lean on. As for getting data out, there’s no network, no file system and no database connection. The code only sees the rows the backend chose to pass in, and its answer is reshaped by a declared schema before anything reads it. When a call fails, the caller gets the exception type and line (ValueError (line 12)) but never the message, so a hostile script can’t smuggle text into the logs or the model’s context through an error.
Where that leaves things#
Here’s the honest scorecard. This default wall is weaker against a kernel bug than any hosted microVM sandbox. There’s still one shared kernel at the bottom, and on a database host a kernel compromise reaches the data files, the WAL and the backups. I’m not going to pretend otherwise.
What it buys is different. The data never leaves the host, and the database verifies the executor itself before it hands over a single byte, which you don’t get when the sandbox is somebody else’s service. And there is nothing extra to deploy: one extension and one helper binary. My current view is that stronger walls (gVisor, a microVM, a sandbox service on your own network) should be a setting a deployer turns on when their platform allows it, not a prerequisite for getting started.
In Part 2: what I measured, what broke, and the testing habits that ended up mattering more than any single layer.
This is part 1 of 3. Next: Part 2, what does it take to trust a sandbox?
