FORENSIC LEDGER · POSTGRESQL 15–19 · RUST · ZERO DAEMON

Every row changed. Proven in Postgres.

Auditstream is an open-source audit trail engine in Rust. Adapters attach the actor as a trailing sqlcommenter tag, generated triggers record before and after in auditstream.changes, and the CLI exports on demand with a lossless xid8 cursor.

Postgres
15 – 19
24/7 Daemon
None (0)
TypeScript ESM
Prisma 7 · Drizzle · Node
01 · Trailing sqlcommenter tag (base64url)
NO EXPLICIT TX
1UPDATE invoice
2SET status = $1
3WHERE id = $2
4/*auditstream='eyJ0eXBlIjoidXNlciIsImlkIjoidXNyXzQyIn0'*/
Unpadded base64url can never contain */ or inject SQL. IDs only — no names, emails, or IPs leak into pg_stat_activity.
decoded: user:usr_42 · 10.4 ns cached tag NO EXTRA TX
LIVE PROTOCOL SIMULATOR · SPEC v0.1

Try the wire protocol live.

Pick a scenario or type any actor.id — even */ DROP TABLE -- — to watch real unpadded base64url encoding, byte-cap enforcement, and PostgreSQL trigger capture in action.

86 / 512 B
OUTBOUND SQL STATEMENT SAFE · ZERO */ BREAKOUT
 
POSTGRESQL CAPTURE RESULT 1 ROW COMMITTED
 
§01 · ATTRIBUTION & CONTRACT

Author in a trailing comment, not a pinned session.

Application code never writes audit rows itself. audit.as() awaits your writes inside AsyncLocalStorage.run() and appends an unpadded base64url sqlcommenter tag — supporting humans, API keys, services, and AI agents acting onBehalfOf a user.

Because comments stay on the statement, standalone Prisma 7 queries need no explicit transaction and never pin connections on RDS Proxy. Malformed payloads never abort your write.

Trailing comment (default)
10.4 ns cached tag · Pool-safe
set_config (fallback)
9.3 ns cached JSON · Explicit tx
ACTOR PRECEDENCE: 1. set_config → 2. /*auditstream='…'*/ → 3. request.jwt.claims (Supabase) → 4. session_user
1import { PrismaClient } from "@prisma/client";
2import { audit } from "@auditstream/node";
3import { auditstream } from "@auditstream/prisma";
4
5const db = new PrismaClient({
6  comments: [auditstream()],
7});
8
9await audit.as(
10  {
11    type: "ai_agent",
12    id: "billing-agent",
13    onBehalfOf: { type: "user", id: "usr_42" },
14    tenant: "org_acme",
15  },
16  async () => {
17    await db.invoice.update({
18      where: { id: "inv_901" },
19      data: { status: "paid" },
20    });
21  }
22);
@auditstream/prisma · auditstream() SQL comments plugin ESM only · spec 0.1
§02 · AUDITSTREAM.CHANGES

The history table is the product.

auditstream.changes is partitioned by month on occurred_at, owned by a dedicated NOLOGIN role, and written exclusively through SECURITY DEFINER triggers. Your application role receives SELECT only — its INSERT, UPDATE, and DELETE tamper attempts are rejected by Postgres itself.

INSERT and DELETE fire once per statement via transition tables (REFERENCING NEW/OLD TABLE); UPDATE stays row-level with WHEN (OLD.* IS DISTINCT FROM NEW.*) so no-op and excluded-column writes record nothing. Lookups use a partial HASH index on record_id alongside a monthly BRIN on occurred_at.

public.invoice · pk: inv_901 · changed: [status, paid_at] excluded: password_hash stripped
− BEFORE (OLD)jsonb
1{
2 "id": "inv_901",
3 "amount_cents": 4900,
4− "status": "open",
5− "paid_at": null
6}
+ AFTER (NEW)jsonb
1{
2 "id": "inv_901",
3 "amount_cents": 4900,
4+ "status": "paid",
5+ "paid_at": "2026-11-24T04:11Z"
6}
actor: ai_agent:billing-agent (onBehalfOf usr_42)
Test as app_role:
xact_id = 48291044 · role: app_user (SELECT only) · owner: auditstream_owner TAMPER-PROOF
§03 · LOSSLESS EXPORT · xid8 WINDOW

Export anywhere, without a 24/7 consumer.

Logical replication needs an always-on consumer — a stopped slot retains WAL and can fill your disk. Auditstream exports pull-based batches on demand using xact_id >= cursor AND xact_id < pg_snapshot_xmin(), acknowledging the cursor only after the sink flushes.

CONCURRENT COMMITS vs. HORIZON xact_id < 48291042
t0 t1 t2 (Export #1) t3 t4 (Export #2) SAFE EXPORT RANGE xid 48291041 xid 48291042 xid 48291043 xid 48291044 xid 48291045 COMMIT · EXPORTED IN FLIGHT AT t2 — HOLDS xmin COMMITTED · WAITS FOR HORIZON invoice='paid' · WAITS IN FLIGHT AT t4 (NEXT xmin) xmin = 48291042
Proven in testing: A cursor on id > last_id lost a row when xid 42 committed after xid 43 and xid 44.
Lossless xid8 window: Run #1 stops cleanly at xact_id < pg_snapshot_xmin() (48291042). Click Run #2 above to watch xid 42, 43, 44 flush in order with stable event_id deduplication.
01 · CONTRACT (spec/)

Versioned & Tested

Normative RFC 2119 spec with language-neutral conformance fixtures in Rust & TS.

02 · CAPTURE (auditstream-pg)

Hybrid Triggers

Statement-level INSERT/DELETE (3× faster bulk), row-level UPDATE, TRUNCATE trigger.

03 · ENGINE (Rust)

Single Static Binary

Hexagonal Cargo workspace (unsafe_code = forbid). Runs on demand or cron.

04 · EXPORT (auditstream-export)

At-Least-Once Sinks

JSON Lines & CSV in v0.1; Webhooks, S3, SIEM, and MCP (rmcp) later.

§04 · VERIFIED EVIDENCE · POSTGRESQL 15–19

Measured on Postgres 15–19. Honest limits.

Why teams choose Auditstream over pgaudit, Debezium/CDC, or hand-rolled triggers — backed by PostgreSQL 19 durable disk (fsync=on) and tmpfs ceiling suites, PgBouncer 1.26 contention tests, 500k-row CLI scale runs, Node 26 adapter timings, and Neon/Supabase verification. Read the full Evidence log →

Requirement Auditstream (v0.1) pgaudit Debezium / CDC (pgoutput) Hand-rolled / App logging
Structured before / after diffs OLD/NEW jsonb + changed[] SQL log lines only (no diffs) Needs REPLICA IDENTITY FULL Misses direct SQL & migrations
User & AI agent attribution Trailing comment + onBehalfOf DB role (session_user) only Needs explicit tx + emit_message Custom per ORM; leaks under pools
New infra & WAL slots Zero daemon · any PG 15–19 Extension + log shipping pipeline wal_level=logical + 24/7 consumer None (you own schema & ops)
Poolers (PgBouncer / Neon) Pool-safe (0 leaks / 2.4M tx) Safe (no per-user context) Dedicated replication conn Session vars pin RDS Proxy
Drift & partition hygiene auditstream verify --fix in CI Manual log retention rules Slot lag alerts (disk-full risk) Silent drift when tables change
Measured write overhead +3.2% (+5.1 µs) durable UPDATE · 211k/s bulk INSERT Text log I/O overhead Lower write CPU · higher WAL Varies; often row-level slow
Isolated Trigger & Index Overhead · PostgreSQL 19.0 (tmpfs)

pgbench -M prepared -c 8 -j 4 (3-run medians, tmpfs isolates CPU/PLpgSQL cost from disk fsync). Shaded bar = prior baseline; colored segment = current gain.

Single-row INSERT · comment 86,060 tps+23.2% · +7.0 µs
Single-row UPDATE · comment 67,018 tps+23.4% · +9.8 µs
Single-row UPDATE · set_config 38,095 tps+43.4% · +21.2 µs
10,000-row bulk INSERT (lower = better) 49.1 ms−25.7% · +3.6 µs/row
Adapter Overhead · @auditstream/node (Node 26.13)

Process-wide WeakMap caching per immutable audit.as() scope + O(1) trailing-character scan. Shaded = before; emerald = current latency.

encodeScope() · Prisma plugin path 10.4 nsvs 1,395 ns · 134×
setConfigValue() · cached JSON 9.3 nsvs 620 ns · 66.6×
tagSql() inside audit.as() (ai_agent) 240 nsvs 1,531 ns · 6.4×
isTagged() · untagged SQL (>4 KB) 4.8 nsvs 271 ns · 56.9×
Durable Disk Stress · PostgreSQL 19.0 (fsync=on, 16 clients)

With WAL fsync=on, commit latency dominates: single-row UPDATE adds +3.2% (+5.1 µs) and 10k bulk INSERT takes 60.5 ms (+3.8 µs/row). On tmpfs, bulk 100k INSERT hits 211k/s while row-level 10k UPDATE caps honestly at ~15k/s.

Single-row INSERT · durable disk 6,459 tps (−0.2% vs 6,443 base)
Single-row UPDATE · SQL comment 6,377 tps (+3.2% · +5.1 µs)
500k-row export (JSONL + redaction) 28,774 ev/s (vs 29,316 raw · −1.8%)
PgBouncer 1.26 Contention, 500k-Row Scale & Zero-Leak Proof
2,407,659 pooled tx · 0 failed · 0 leaked actors

64 clients over 8 PgBouncer 1.26 transaction-mode slots (8× oversubscribed): comment sustains 42.5k–53.5k tps (1.8×–2.4× faster than set_config), with 272,053 mixed leak-test writes and zero crossover. Across 500,000 rows (348 MB), partial hash lookups execute in 0.101 ms (157k concurrent QPS).

PG 15–19 · 0 regressions post-#130 500k rows · 0.101 ms lookup Bulk UPDATE honest cap: ~15k/s
§05 · DAY-2 OPS & ROADMAP · W1–W4 SHIPPED

Triggers never drift silently.

Run auditstream verify in CI or cron to catch disabled triggers, modified trigger functions, rows stuck in the DEFAULT partition, or missing future monthly partitions — and auto-create upcoming partitions with --fix. Read CLI reference →

CI drift gate · auditstream verify
$auditstream verify --format json
 # [ok]    public.invoice  4 triggers intact
 # [error] public.users    disabled (tgenabled = 'D')
 # [warn]  partitions      <2 future months (--fix)
 # exit 3 -> blocks CI before an audit gap ships
✓
W1 · SHIPPED

Spec v0.1 & CI

Normative spec/, JSON schemas, shared fixtures, Cargo & pnpm CI.

✓
W2 · SHIPPED

Core & @auditstream/node

Domain types, port traits, cached base64url codec passing shared Rust & TS fixtures.

✓
W3 · SHIPPED

Triggers, Export & ORMs

auditstream-pg, JSONL/CSV sinks, Prisma 7, Drizzle 0.45 & 1.x.

✓
W4 · SHIPPED

CLI & App Examples

init, status, verify, history, export + Next.js & Hono apps.

✓
W5 · SHIPPED

Packaging & Channels

Prebuilt binaries via shell/PowerShell installers, Homebrew, npm, and ghcr.io.

POST-v0.1 HORIZON (BEHIND SAME EventSource & Sink TRAITS) S3 · Webhooks · SIEM · MCP (rmcp) · Optional WAL replication via pg_logical_emit_message
  1. 00

    Install the Rust CLI

    Single static binary via shell/PowerShell installer, Homebrew, npm, or Docker (ghcr.io). Need a 60-second Docker walkthrough? See Getting Started →

    terminal · install CLI
    $# macOS / Linux shell installer
     curl --proto '=https' --tlsv1.2 -LsSf https://github.com/auditstream/auditstream/releases/latest/download/auditstream-installer.sh | sh
     # Or: brew install auditstream/tap/auditstream · npm i -g auditstream · ghcr.io/auditstream/auditstream
  2. 01

    Generate migration & triggers

    Writes the monthly-partitioned auditstream.changes table, partial HASH lookup index, and hybrid triggers for Prisma, Drizzle, or plain SQL.

    terminal · auditstream CLI
    $auditstream init --migrations prisma \
       --table public.invoice --table public.users \
       --exclude public.users.password_hash
     # partitioned auditstream.changes + partial HASH idx
  3. 02

    Install the TypeScript adapter

    ESM-only packages for Node 22.12+, Bun, Deno, and Cloudflare Workers.

    terminal · auditstream-js
    $pnpm add @auditstream/node @auditstream/prisma
  4. 03

    Inspect diffs or export on demand

    Query history from the CLI or export JSON Lines / CSV using the commit-safe xid8 cursor.

    terminal · history & export
    $auditstream history --table public.invoice --limit 10
     auditstream export --format jsonl \
       --output audit.jsonl --cursor-file cursor.json
     # xid8 window exported · acked after sink flush