Skip to main content

agent-cow-postgresql

PostgreSQL Copy-On-Write for AI agent workspace isolation

License: MIT

Downstream fork

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.

Hardened PostgreSQL integration

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

Installation

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: agentcow and agentcow.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.

How It Works

  1. Renames your table from users to users_base
  2. Creates a changes table users_changes to store session-specific modifications
  3. Creates a COW view named users that merges base + changes
  4. 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 backend

PostgreSQL is the single maintained backend. See the agentcow.postgres guide for deployment, role hardening, runtime sessions, conflict review, and atomic promotion.

Quick Example (PostgreSQL)

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.

API Reference

Core Functions

  • deploy_cow_functions(executor) — Deploy COW SQL functions (one-time setup)
  • enable_cow(executor, table_name) — Enable COW on a table
  • enable_cow_schema(executor) — Enable COW on all tables in a schema
  • harden_cow_schema(executor, ...) — Apply setup/runtime/reviewer boundaries
  • validate_cow_schema_privileges(executor, ...) — Validate effective privileges
  • disable_cow(executor, table_name) — Disable COW and restore original table
  • disable_cow_schema(executor) — Disable COW on all tables in a schema
  • commit_cow_session(executor, table_name, session_id) — Commit all session changes
  • discard_cow_session(executor, table_name, session_id) — Discard all session changes
  • get_cow_status(executor) — Get COW status for a schema

Advanced and review functions

  • apply_cow_variables(executor, session_id, operation_id) — Advanced low-level caller-managed transaction helper
  • get_session_operations(executor, session_id) — List all operations in a session
  • get_operation_dependencies(executor, session_id) — Get operation dependency graph
  • commit_cow_operations(executor, table_name, session_id, operation_ids) — Commit specific operations
  • discard_cow_operations(executor, table_name, session_id, operation_ids) — Discard specific operations
  • get_cow_conflicts(executor, session_id) — Inspect first-touch conflicts

Session Management

  • asyncpg_cow_session(connection_or_pool, session_id=...) — Recommended transaction-owning asyncpg request scope
  • sqlalchemy_cow_session(engine_or_session, session_id=...) — Equivalent optional SQLAlchemy async scope
  • CowSession — Active high-level runtime transaction object
  • asyncpg_cow_reviewer(connection_or_pool) — Recommended atomic asyncpg promotion/discard scope
  • sqlalchemy_cow_reviewer(engine_or_session) — Equivalent optional SQLAlchemy reviewer scope
  • CowReviewer — Active high-level reviewer transaction object
  • CowConflictError — Stable Python promotion-conflict exception
  • CowPostgresConfig — Dataclass for COW configuration
  • build_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.

Development

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/ -v

The 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.

Contributing

For downstream questions, bug reports, or feature requests, use this fork's issue tracker.

License

MIT License.

Credits

Originally created by Trail. This downstream fork is maintained by Janez Perš while preserving upstream history and attribution.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agent_cow_postgresql-0.2.0.tar.gz (108.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agent_cow_postgresql-0.2.0-py3-none-any.whl (106.3 kB view details)

Uploaded Python 3

File details

Details for the file agent_cow_postgresql-0.2.0.tar.gz.

File metadata

  • Download URL: agent_cow_postgresql-0.2.0.tar.gz
  • Upload date:
  • Size: 108.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for agent_cow_postgresql-0.2.0.tar.gz
Algorithm Hash digest
SHA256 eae8d434d2fc03c4faa08b44b4863fc8f8efb44ee33eaad3adc22e7eb96a062c
MD5 c6ca071e8b07da9f12d3d29b7f5e232c
BLAKE2b-256 9d8a12ab11db290a00e3d5c9d5c096e3a40ac1d3b731f5eb9aba9e4f760ca97f

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_cow_postgresql-0.2.0.tar.gz:

Publisher: publish-pypi.yml on jpers1/agent-cow-postgresql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file agent_cow_postgresql-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agent_cow_postgresql-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c469d24700fabb93a58f464d3539a32e936097f93035a95f193062859546f5b1
MD5 4abe8d85df68add53af21b964140d1a6
BLAKE2b-256 7180c16b27ee22112ce51c4198a67f07513a1c73bd5231f94356da563419d9f0

See more details on using hashes here.

Provenance

The following attestation bundles were made for agent_cow_postgresql-0.2.0-py3-none-any.whl:

Publisher: publish-pypi.yml on jpers1/agent-cow-postgresql

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page