PostgreSQL Copy-On-Write for AI agent workspace isolation
agent-cow-postgresql is a PostgreSQL-focused downstream fork of Trail's
MIT-licensed
agent-cow-python. The
original agent-cow project and core copy-on-write design were created by
Trail. This fork preserves that history and attribution while independently
maintaining and hardening the PostgreSQL implementation.
Upstream project: https://github.com/trail-ml/agent-cow-python
agent-cow-postgresql isolates application database writes in a PostgreSQL
copy-on-write layer until a separate reviewer accepts or discards them.
The downstream recommended path is:
trusted application
-> hardened runtime role
-> asyncpg pool
-> asyncpg_cow_session(...)
-> server-owned session UUID
-> controlled CRUD through COW views
Start with the PostgreSQL guide, then use the
security model to configure separate
setup, runtime, and reviewer roles. agent-cow-postgresql does not
authenticate external users or capabilities. The application must select the
session UUID after authorization.
Read the full article: Copy-on-Write in Agentic Systems
Without copy-on-write: With agent-cow-postgresql:
┌───────┐ ┌──────────┐ ┌───────┐ ┌──────┐ ┌──────────┐
│ Agent │──────>│ Database │ │ Agent │────>│ COW │────>│ Database │
└───────┘ └──────────┘ └───────┘ │ View │ └──────────┘
writes directly └──────┘
to production writes go to changes table
reads merge base + changes
user reviews, then commits or discards
Install the maintained 0.2.0 release from PyPI with:
python -m pip install agent-cow-postgresql- Repository:
https://github.com/jpers1/agent-cow-postgresql - Distribution:
agent-cow-postgresql - Imports:
agentcowandagentcow.postgres
Alternatively, install the tagged Git revision with:
python -m pip install \
"agent-cow-postgresql @ git+https://github.com/jpers1/agent-cow-postgresql.git@v0.2.0"The GitHub Release provides the same wheel and source distribution submitted to PyPI, plus their SHA-256 checksums.
The verified downstream PostgreSQL range is Python 3.10–3.14 and PostgreSQL 14–18. See the support matrix for exact evidence.
- Renames your table from
userstousers_base - Creates a changes table
users_changesto store session-specific modifications - Creates a COW view named
usersthat merges base + changes - Your code doesn't change — queries still target
users(now a view)
The recommended session API applies server-selected transaction-local context, routes writes into the changes table, and merges those changes into reads for that session. Other sessions and canonical readers see only base data.
Why Copy-on-Write for agents?
Alignment is an open problem in AI safety, and misalignment during agent execution may not always be obvious. At best, a misaligned agent is annoying (i.e. if the agent does something other than what the user wants it to do) and at worst, dangerous (i.e. leading to sensitive data loss, tool misuse, and other harms). Rather than tackling the alignment problem directly, this repo focuses on minimizing potential harm a misaligned agent can cause.
- Changes can be reviewed at the end of a session, rather than needing to repeatedly 'accept' each action as it is executed. This minimizes the direct human supervision required while improving the safeguards in place.
- Mistakes are less consequential, since the agent can't write directly to the main/production data. If some changes are good but others aren't, users can cherry-pick operations they wish to keep.
- Misalignment patterns become more visible. When reviewing changes at the end of a session, users can clearly identify where the agent deviated from intended behavior and adjust the system prompt or agent configuration accordingly to prevent similar issues in future sessions.
- Multiple agents or agent sessions can run simultaneously on isolated copies without interfering with each other.
PostgreSQL is the single maintained backend. See the
agentcow.postgres guide for deployment, role
hardening, runtime sessions, conflict review, and atomic promotion.
import asyncpg
from agentcow.postgres import asyncpg_cow_session
# Authorization and capability lookup are application responsibilities.
trusted_session_id = await application_session_store.resolve(external_capability)
runtime_pool = await asyncpg.create_pool(RUNTIME_DATABASE_URL)
try:
async with asyncpg_cow_session(
runtime_pool,
session_id=trusted_session_id,
) as cow:
await cow.execute("INSERT INTO content.pages (id, title) VALUES (1, 'Draft')")
finally:
await runtime_pool.close()The pool authenticates as the hardened runtime role. Setup and promotion use separate roles and controlled APIs. See the PostgreSQL docs for the complete deployment, runtime, and reviewer example.
deploy_cow_functions(executor)— Deploy COW SQL functions (one-time setup)enable_cow(executor, table_name)— Enable COW on a tableenable_cow_schema(executor)— Enable COW on all tables in a schemaharden_cow_schema(executor, ...)— Apply setup/runtime/reviewer boundariesvalidate_cow_schema_privileges(executor, ...)— Validate effective privilegesdisable_cow(executor, table_name)— Disable COW and restore original tabledisable_cow_schema(executor)— Disable COW on all tables in a schemacommit_cow_session(executor, table_name, session_id)— Commit all session changesdiscard_cow_session(executor, table_name, session_id)— Discard all session changesget_cow_status(executor)— Get COW status for a schema
apply_cow_variables(executor, session_id, operation_id)— Advanced low-level caller-managed transaction helperget_session_operations(executor, session_id)— List all operations in a sessionget_operation_dependencies(executor, session_id)— Get operation dependency graphcommit_cow_operations(executor, table_name, session_id, operation_ids)— Commit specific operationsdiscard_cow_operations(executor, table_name, session_id, operation_ids)— Discard specific operationsget_cow_conflicts(executor, session_id)— Inspect first-touch conflicts
asyncpg_cow_session(connection_or_pool, session_id=...)— Recommended transaction-owning asyncpg request scopesqlalchemy_cow_session(engine_or_session, session_id=...)— Equivalent optional SQLAlchemy async scopeCowSession— Active high-level runtime transaction objectasyncpg_cow_reviewer(connection_or_pool)— Recommended atomic asyncpg promotion/discard scopesqlalchemy_cow_reviewer(engine_or_session)— Equivalent optional SQLAlchemy reviewer scopeCowReviewer— Active high-level reviewer transaction objectCowConflictError— Stable Python promotion-conflict exceptionCowPostgresConfig— Dataclass for COW configurationbuild_cow_variable_statements(session_id, operation_id)— Build low-level transaction-local context statements
Low-level helpers require caller-managed connection, explicit transaction, context validation, cancellation, and pool-cleanup safety. They are not the recommended request integration.
git clone https://github.com/jpers1/agent-cow-postgresql.git
cd agent-cow-postgresql
uv sync --frozen --group dev
uv run python scripts/check_dependency_policy.py
uv run pytest agentcow/postgres/tests/ -vThe supported development group covers the complete maintained package and uses a permissive-only Python dependency set. Ruff is the formatter/checker; package builds use Setuptools. See the dependency policy and inventory.
For downstream questions, bug reports, or feature requests, use this fork's issue tracker.
MIT License.
Originally created by Trail. This downstream fork is maintained by Janez Perš while preserving upstream history and attribution.