Skip to content

Tamper evidence

The audit tables are append-only for the application role (see roles), but whoever owns the database, or holds a role that may update the tables, can still change them. With integrity on, such a change is detected: a sealer job hashes the audit rows of finished transactions into blocks chained by hash, and verify() rebuilds every block from the rows and reports every difference.

This makes the log tamper-evident, not tamper-proof. Nothing here stops a change; it makes changes visible to whoever verifies. What it can detect depends on where you keep checkpoints and keys, which the three tiers below describe, and Limitations lists what it does not detect.

How it works

  • At write time, every audit row gets its PostgreSQL transaction id in a new xid column, and a salted SHA-256 commitment for each part that scrubbing may erase (the label, the changes, the payload and the actor's context). Writes take no extra lock and no extra round trip. Audited values must fit the format's fixed limits: at most 4300 digits per number and at most 256 nested levels of arrays and objects. A value beyond them is refused with CanonicalEncodingError, and the sealer and verify() read stored numbers exactly, whatever the host's sys.set_int_max_str_digits().
  • The sealer (audit.maintenance.seal(), run every minute or so) appends a seal block covering the rows of every transaction that has finished since the last block. Each block holds one Merkle root per partition (the tree hash of RFC 6962), and the hash of the block before it. It never updates an audit row.
  • Retention appends a retire block before it drops a partition, so a dropped partition is accounted for.
  • Scrubbing still works: scrub() and scrub_actor() delete the salt of each part they erase and stamp the part with the scrub's own transaction id, which points to the scrub's audit.scrubbed entry. An erasure is therefore attributable: every erased value points to a recorded scrub.
  • verify() walks the chain, recomputes every block it can still read, checks the commitments of values that were not erased and the receipts of those that were, and reports every failure it finds instead of stopping at the first.
  • Checkpoints (export_checkpoint()) are signed statements of the head of the chain, for you to store where the database cannot reach them.

Three tiers

Tier What you run What it catches
1. Verify only the sealer and verify() Edits and deletes of sealed rows, by anyone who cannot also rewrite the block table: a scrubber or maintenance role, a stray UPDATE, a deleted partition
2. Plus checkpoints tier 1, and export_checkpoint() on a schedule, stored off the database host (S3 Object Lock in compliance mode, an RFC 3161 timestamp, another machine that keeps the last head) Also a rewrite of the whole chain by a superuser, a cut-off chain and a restore to an earlier state, up to the newest checkpoint
3. Plus signed blocks tier 2, and a Signer whose key the database host cannot read (a KMS or HSM, or a sealer on another machine) Also a rewrite between two checkpoints: a superuser cannot sign new blocks. Truncation still needs tier 2

Without a checkpoint a report is UNANCHORED: it says the chain is internally consistent, not that nobody rewrote it. A signing key kept on the database host adds attribution only, since whoever controls the host can use it.

Turning it on

Pass Integrity() to every AuditTrail that writes audit entries, and to the ones that run maintenance and verification:

from audit_trail import AuditTrail, Integrity

audit = AuditTrail(engine, events=[BillingEvent], integrity=Integrity())

Install the extra if you use the reference Ed25519 or ECDSA P-256 signers: pip install "sqlalchemy-audit-trail[integrity]". Nothing else needs it.

A new install

build_tables(integrity=True) declares the integrity columns, the (xid, id) indexes and the block table (audit_seal_block), and create_audit_tables() creates them:

tables = build_tables(schema="audit", integrity=True)


def upgrade() -> None:
    migrations.create_audit_tables(op.get_bind(), tables, Level)

Then start the chain once the application runs with Integrity(), as in step 3 below.

An existing install

The upgrade takes three steps, in this order:

  1. Columns. migrations.add_integrity() adds xid and the seal_* columns to both tables, and creates the block table. Existing rows keep xid NULL: they are out of scope.
  2. Indexes. migrations.add_integrity_indexes() builds the (xid, id) indexes and a partial index of the scrubbed rows ((id) WHERE seal_erased IS NOT NULL, for the erasure journal) online, one partition at a time with CREATE INDEX CONCURRENTLY, so it needs an AUTOCOMMIT connection. An install upgraded with an earlier version gets the partial index by running it again; the indexes it has already are left alone.
  3. Genesis. migrations.write_genesis() starts the chain. Run it only after every writer runs with Integrity(): rows written after it must carry commitments, and rows of an old writer fail as COMMITMENT_MISSING. Rows written between steps 1 and 3 are out of scope too (PRE_GENESIS), which gives a rolling deploy a defined order.
from alembic import op

from audit_trail import migrations
from audit_trail.tables import build_tables

tables = build_tables(schema="audit", integrity=True)


def upgrade() -> None:
    migrations.add_integrity(op.get_bind(), tables)
    with op.get_context().autocommit_block():
        migrations.add_integrity_indexes(op.get_bind(), tables)

Deploy the application with Integrity(), then start the chain from a script or a later migration:

with maintenance_engine.begin() as conn:
    migrations.write_genesis(conn, tables)

Calling it again returns the existing genesis block. Change the grants as shown in roles: the application must lose its table-wide INSERT.

A short stall during add_integrity

Each ALTER TABLE takes an ACCESS EXCLUSIVE lock on the parent and its partitions. It rewrites and scans nothing, so the lock itself is held for milliseconds. But while the ALTER waits for open transactions that have used the table, new audit writes queue behind it. add_integrity caps the wait with lock_timeout (2 seconds by default) and retries with a random pause, up to attempts times, so writers stall for at most about that long per attempt. Run it outside peak hours, and keep long transactions off the audit tables while it runs.

Before turning on row state

Upgrade every sealer and verifier to 0.8 before you turn on record_state on a database with integrity. A 0.7 sealer hashes data.state into the entry's leaf, while 0.8 leaves it out (a scrub erases it), so 0.8's verify() reports ROOT_MISMATCH on every block a 0.7 sealer sealed with a state in it, for good, and once a scrub erases that state the block can never verify. That cannot be undone: the block is in the chain. A 0.7 verifier run against 0.8 rows with a state is only a false alarm (ROOT_MISMATCH and COMMITMENT_MISMATCH) that goes away with the upgrade.

Running the sealer

Run seal() every minute, under the sealer role. Each call seals up to max_rows rows (50,000 by default; one transaction is never split) and returns a SealResult; call it again while capped is true, up to a bound:

from audit_trail.integrity import SealRefusedError

sealer = AuditTrail(
    create_engine(
        SEALER_DATABASE_URL,
        connect_args={"options": "-c synchronous_commit=local"},
    ),
    events=[],
    integrity=Integrity(),
)

MAX_CALLS = 20  # about 1 million rows per run


def seal() -> None:
    try:
        for _ in range(MAX_CALLS):
            if not sealer.maintenance.seal(signer=SIGNER).capped:
                return
        logging.warning("the sealer is behind; the next run goes on")
    except SealRefusedError as exc:  # XID_REWIND, NO_GENESIS, ID_FLOOR_VIOLATION
        logging.error("the sealer refused: %s", exc)
        raise

Each call takes a new horizon, so while writers outpace the sealer every call is capped: a loop that waits for the last one would never end. Bound it, and watch health() (below) for a sealer that stays behind. drop_expired() seals only up to the horizon it reads at its start, for the same reason.

A missed run only leaves rows unsealed for longer. Two sealers at once are safe: the second returns with skipped="busy". On a hot standby it returns with skipped="standby", and on a logical replication subscriber of the block table with skipped="subscriber": there the publisher seals, and a block of the subscriber's own would stop the subscription on a duplicate key.

synchronous_commit for the sealer. With synchronous_commit = on (the default) and a synchronous standby that is required but down, the COMMIT of every block waits until the standby is back: replication_timeout does not bound it and statement_timeout does not cancel it. Give the sealer's sessions synchronous_commit = local, as above, and use export_checkpoint(require_replicated=True) (see replication) to learn that a block reached the standbys. The same holds for export_checkpoint(), record_checkpoint() and declare_fork(), which commit their blocks the same way: one that waits holds the sealer's advisory lock, so every seal() meanwhile returns skipped="busy". Run them on the sealer's engine, or another with local.

idle_in_transaction_session_timeout for the sealer role. A seal() call holds the sealer's lock and a REPEATABLE READ snapshot while it hashes the rows on the client. A client that hangs there blocks record_checkpoint(), export_checkpoint() and declare_fork() and holds back vacuum. Set a timeout on the role, longer than a call takes (some seconds per 50,000 rows, see sizing), so that the server ends such a session: ALTER ROLE audit_sealer SET idle_in_transaction_session_timeout = '5min'.

Only finished transactions are sealed. A transaction that has written and is still open holds the seal back, and so does a prepared transaction, until it is committed or rolled back. The horizon is the cluster's, not the database's: any open transaction that has a transaction id holds it back, also one in another database of the same cluster. health() reports this in report.seal:

  • seal_lag: how old the oldest unsealed entry is. Its age counts from the entry's own time (issued_at, created_at), not from its commit, so a transaction that ran longer than max_seal_lag (5 minutes by default) is flagged once it commits, until the next seal;
  • unsealed_rows, sealed_to and last_sealed_at;
  • prepared: prepared transactions older than max_seal_lag, which stall sealing until someone resolves them;
  • problem: the step to run when the chain is not started yet.

report.ok is false while sealing lags, so the health probe covers the sealer too.

Verifying

Run verify() on a schedule, under the read-only verifier role, ideally from another machine:

from audit_trail.integrity import Status
from audit_trail.integrity.ed25519 import Ed25519Verifier

verifier = AuditTrail(
    create_engine(VERIFIER_DATABASE_URL), events=[], integrity=Integrity()
)
report = verifier.maintenance.verify(
    retention=RETENTION,
    checkpoints=load_checkpoints_from_off_the_box(),
    verifier=Ed25519Verifier(PUBLIC_KEYS),
)
if report.status is Status.FAILED:
    for failure in report.failures:
        logging.error("%s: %s", failure.kind, failure.detail)

Use an AuditTrail with the same schema, severities and system_severity as the application: the severity of the audit.scrubbed entries is needed to account for erasures whose receipt was retired. averify() is the async variant. verify() holds no lock and no long snapshot: it reads each partition in short READ ONLY transactions.

Verify on the primary or on a physical standby, never on a logical replication subscriber: its rows carry the publisher's transaction ids and its blocks are the publisher's, so verify() there raises a ValueError that says to verify on the publisher.

The report has a status (VALID, VALID_WITH_NOTES or FAILED), an anchor (ANCHORED when a checkpoint matched), failures and notes, each a Finding with a kind, a detail sentence and the block, partition or row it concerns. A finding never contains a stored value or a salt.

  • Failures (FailureKind) include ROOT_MISMATCH and ROW_COUNT_MISMATCH (sealed rows changed, added or deleted), COMMITMENT_MISMATCH (an erasable value changed), COMMITMENT_MISSING (a row written without Integrity), ERASURE_UNEXPLAINED and SCRUB_COUNT_MISMATCH (an erasure without a matching scrub), SEGMENT_MISSING (a partition gone without a retire block), RETIRED_EARLY (with retention: a partition retired inside its retention), DETACHED_PARTITION, PREV_MISMATCH and HASH_MISMATCH (the chain itself), TRUNCATED and CHAIN_MISMATCH (against a checkpoint), BAD_SIGNATURE, UNKNOWN_KEY, KEY_NOT_VALID and KEY_COMPROMISED (with a key history), MALFORMED_BLOCK and XID_REWIND, and for a bundle MANIFEST_MISMATCH.
  • Notes (NoteKind) do not fail the report: ERASED, ERASED_RECEIPT_RETIRED, SCRUBBED_ROWS_RETIRED, RETIRED, PRE_GENESIS, UNSEALED_TAIL, UNANCHORED_TAIL, FORKED, FORKED_UNSIGNED and ACKNOWLEDGED, and for a bundle OUT_OF_SCOPE and UNANCHORED (see verifying a bundle offline). With a verifier, a fork block that no key it knows signed gets a FORKED_UNSIGNED note next to its FORKED one: anyone who can write the block table can add such a block, so it explains no checkpoint (see restores and forks).

The report also names its head: the last block it checked, as the unsigned statement of a checkpoint of that block. Keep the report (it is a plain dataclass) to prepare a checkpoint from it later, or to catch up from it.

Catching up. A full run reads every row, which takes minutes on a large log. verify(since=report) takes an earlier report without failures and reads only the rows after its head's sealed horizon, comparing them with the seal blocks after the head:

KEYS = Ed25519Verifier(PUBLIC_KEYS)
nightly = verifier.maintenance.verify(retention=RETENTION, verifier=KEYS)
...
report = verifier.maintenance.verify(since=nightly, verifier=KEYS)
assert report.since == nightly.verified_to

Every block of the chain is still checked, and the earlier head must still be in it with its hash, or the run is TRUNCATED or CHAIN_MISMATCH. A row before the head that changed since is not seen, and neither are the scrub counts, which need every row: keep running full verifications on a schedule, and catch up between them. After a fork since the report, the run is a full one, and report.since is None.

Acknowledging a known incident

Some failures are expected once, for example rows of a writer that still ran without Integrity during a deploy. acknowledge() waives them with an ack block in the chain, so later reports show them as ACKNOWLEDGED notes:

maintainer.maintenance.acknowledge(
    FailureKind.COMMITMENT_MISSING,
    {"xid_from": 81234, "xid_to": 81290},
    "a writer ran without Integrity during the 2026-11-30 deploy",
    signer=SIGNER,
)

The scope's xid_to is exclusive, like every range in the chain: to cover xids 81234 to 81289, pass "xid_to": 81290. It runs verify() first and pins exactly what it waives: the rows for a failure about rows, the root and row count for a partition. A failure that is new or changed later in the same scope is reported again. Only failures about rows and partitions can be waived (ACKNOWLEDGEABLE), never a broken chain. An ack that would waive nothing is refused. The reason is stored in clear, and the ack stays visible in the chain and in every later checkpoint: it is accountable, not silent.

Retention

With integrity on, drop_expired() first seals, then, with verify_before_drop=True (the default), verifies the expired partitions, and appends a retire block for each one before it detaches and drops it. A partition that still holds unsealed rows, failed verification or could not be locked is kept and listed in skipped with a reason; the next run tries again:

dropped = maintainer.maintenance.drop_expired(RETENTION, signer=SIGNER)
for kept in dropped.skipped:
    logging.warning("kept %s: %s", kept.partition, kept.detail)
  • The seal, verification and retire blocks run on a second connection from the same engine's pool, while the first stays in AUTOCOMMIT for the detach. Size the pool for it: with no free connection the call raises PartitionError at once, instead of waiting for the pool timeout.
  • The verify runs once, before the drops. A sealed row changed in place after it, and before its partition is dropped, is not seen, and is dropped with the partition.
  • Until write_genesis() has run, drop_expired() drops as it does without integrity.
  • Pass the same retention to verify(retention=...) to catch a partition retired early. A KEEP severity counts as kept forever there.
  • A scrub's audit.scrubbed entry counts every row it stamped, also those of a partition dropped since, whose stamps are gone with it. verify() then accepts fewer stamps than recorded, by at most the rows of the retired partitions of that table that the scrub could have stamped (those sealed before its transaction), with a SCRUBBED_ROWS_RETIRED note per scrub and part. Retire blocks do not record stamps, so this is a bound, not an exact count: anything beyond it is still SCRUB_COUNT_MISMATCH.
  • A KEEP severity is never retired, but the transaction partitions it shares with the other severities are: their retire blocks explain the dropped transaction stream (see severities that are never dropped).

Checkpoints

A checkpoint states which block was the head of the chain at a moment. Kept where whoever can rewrite the database cannot reach it, it lets verify() catch a chain rewritten, cut short or restored to an earlier state since. Export one on a schedule (hourly, daily) and store the text:

from audit_trail.integrity import export_checkpoint
from audit_trail.integrity.ed25519 import Ed25519Signer

SIGNER = Ed25519Signer.from_skey(os.environ["AUDIT_SIGNER_KEY"])

with sealer_engine.connect() as conn:
    checkpoint = export_checkpoint(conn, sealer.tables, signer=SIGNER)
store_off_the_box(checkpoint.to_note())

The text is a C2SP signed note: a two-line statement of the chain id, block number, block hash, sealed horizon, time and incarnation (1 until the first fork, then the number of the newest fork's), followed by one signature line per key, so existing note tooling can check the signatures. It is not a C2SP tlog-checkpoint: the head of the chain is a hash chain, not a Merkle tree over the blocks, so there is no tree size and no consistency proof. Checkpoint.from_note(text) reads one back, and verify(checkpoints=[...]) takes the texts as they are. As the spec asks, lines of keys the verifier does not know are ignored, also when one repeats, and a key name may hold any character but a space and +. Stricter than the spec, and allowed by it: a signature must be canonical base64, every line of a known key is checked, and two lines of one known key are refused as malformed. checkpoint.signed([...]) refuses a key that signed it already, and Ed25519Signer refuses a key name with a control character.

Extension lines. An application can add its own lines to a checkpoint, signed with the rest: export_checkpoint(conn, tables, signer=SIGNER, extensions=["example/assurance: high", "example/previous: <hash>"]). They follow the statement, one per line, and Checkpoint.from_note(text).extensions gives them back; a changed, added or removed line breaks every signature. verify() does not read them, and they are not stored in the block, so keep them with the checkpoint. A line must be at most 1024 bytes of UTF-8 and read as what it says: not empty or only whitespace, without control characters, line breaks, invisible format characters (bidi overrides such as U+202E, zero-width characters), private-use or unassigned code points, or blank-looking letters (the Hangul fillers U+115F, U+1160, U+3164 and U+FFA0, and the braille blank U+2800), and it must not start with sqlalchemy-audit-trail/ in any case, which is reserved for the package; export_checkpoint, prepare_checkpoint and Checkpoint refuse such a line before anything is written. Checkpoints signed by 0.5.0, whose rules were looser, still read and verify. Prefix your lines with a name of your own, as above. The C2SP tlog-checkpoint format calls extension lines NOT RECOMMENDED, because log monitors cannot audit them; this checkpoint is not a tlog-checkpoint, and nothing but your application reads these lines.

The statement is a fixed block of lines, versioned by its first line (sqlalchemy-audit-trail/checkpoint/v1, two lines; sqlalchemy-audit-trail/checkpoint/v2, three lines, when it commits to an erasure journal), and the extension lines come after it. A new field of the package gets a new statement version, never a new line in an old one, and readers accept every earlier version, so checkpoints written by 0.4.0 still read and verify. Checkpoints with extension lines need 0.5.0 or later to read: 0.4.0 refuses a third line.

Storing it is up to you; the database must not be able to change it afterwards:

  • S3 Object Lock in compliance mode, which nobody can lift before the retention date (in governance mode, users with a special permission can delete the object). Object Lock needs a bucket with versioning;
  • an RFC 3161 timestamp from a time-stamping authority, which signs a hash of the text;
  • a verifier on another machine that keeps the newest head it has seen;
  • a printed sheet, for a small log.

Exporting appends a checkpoint block, so the chain itself records that an anchor was taken.

Replication. After an asynchronous failover that lost the newest blocks, a checkpoint naming one of them would look exactly like an attack (TRUNCATED). export_checkpoint(require_replicated=True) returns the checkpoint only once as many synchronous standbys as synchronous_standby_names asks for have flushed its block: n with sync_state sync for FIRST n (or a plain list of names, which means FIRST 1), n with quorum for ANY n. It waits up to replication_timeout (30 seconds by default). It reads pg_stat_replication, whose sync_state and WAL positions only roles with the privileges of pg_read_all_stats (included in pg_monitor) can see: a role that exports with require_replicated needs pg_monitor, or every call fails with NO_SYNC_STANDBY.

The check runs after the commit, so the checkpoint block is in the chain whatever happens; only the checkpoint is withheld. Any error from then on is a ReplicationError with the block's seq and the WAL position it waited for (lsn, empty if reading it failed), and a reason:

  • NO_SYNC_STANDBY: synchronous_standby_names is empty, which fails at once, or fewer standbys of the kind it asks for are listed. A standby that is reconnecting is listed again within moments, so this waits about two seconds (capped by replication_timeout) before it gives up. A role without pg_monitor sees no standby and fails this way too. With ANY n, a standby that was shut down cleanly leaves pg_stat_replication, so it is reported this way, not as NOT_REPLICATED;
  • NOT_REPLICATED: enough standbys are listed, but not enough flushed the block within replication_timeout. A standby is still listed while it hangs or is cut off from the network, until wal_sender_timeout ends its connection;
  • CHECK_FAILED: reading the WAL position or pg_stat_replication failed; the error is chained as the cause.

With synchronous_commit = on, the export's own COMMIT already waits for the synchronous standbys, without a time limit (see the sealer): export with local. If a COMMIT that waits is ended by terminating its backend (pg_terminate_backend), the block is written but the client only sees its connection close; export_checkpoint then raises ReplicationError too, NOT_REPLICATED with seq and lsn, or CHECK_FAILED with seq alone when it cannot read them on a new connection.

In every case, export again once the standbys are back: the next call appends a new checkpoint block.

Keys. Ed25519Signer.generate("audit.example.com/sealer-2027") makes a key; keep its skey secret and give its vkey to the verifiers. Use a new name for each new key, and keep old verifier keys in Ed25519Verifier for as long as blocks and checkpoints signed by them are checked. For tier 3, implement the Signer protocol (key_id, algorithm, sign(message)) against your KMS or HSM.

ECDSA P-256. Many KMSs and HSMs offer P-256 but not Ed25519, so audit_trail.integrity.ecdsa has EcdsaP256Signer and EcdsaP256Verifier: C2SP signature type 0x02, as the transparency-dev note tooling implements it, so its verifiers check the notes. A verifier key is <name>+<key hash>+base64(0x02 || DER SubjectPublicKeyInfo), and unlike Ed25519 the key hash is the first 4 bytes of SHA-256 of the DER public key alone, without the name. A signature is the DER ECDSA-Sig-Value of SHA-256(message), which is what a KMS returns for an ECDSA_SHA_256 key, so a Signer for one sends the message to sign with algorithm = "ecdsa-p256-sha256". There is no secret key text for ECDSA in the note tooling: make a signer from a cryptography key, EcdsaP256Signer.from_pem(name, pem) or EcdsaP256Signer.generate(name). ECDSA signatures are randomized, so two signatures of one checkpoint differ; both verify.

Only P-256 is accepted: a verifier key of P-384 or P-521 is refused. AWS KMS and openssl dgst -sign return DER already. Signers that return the raw r || s form (64 bytes), such as Azure Key Vault and PKCS#11 CKM_ECDSA, need converting in your Signer:

from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature


def sign(self, message: bytes) -> bytes:
    raw = hsm_sign(message)  # 64 bytes, r || s
    return encode_dss_signature(
        int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big")
    )
from audit_trail.integrity.ecdsa import EcdsaP256Signer
from audit_trail.integrity.keys import KeyVerifier

p256 = EcdsaP256Signer.from_pem("audit.example.com/kms-2027", PEM)
checkpoint = export_checkpoint(conn, sealer.tables, signer=SIGNER).signed([p256])
report = verifier.maintenance.verify(
    checkpoints=[checkpoint.to_note()],
    verifier=KeyVerifier([SIGNER.vkey, p256.vkey]),
)

KeyVerifier takes verifier keys of both types, so a chain whose key moved from Ed25519 to P-256, or a checkpoint cosigned by both, is checked in one verify(). It refuses two different keys with one key id, also across types.

Key history

A retired or stolen key still verifies: whoever holds it can sign new blocks and checkpoints. Tell verify() when each key was valid with a KeyHistory, built from your own records of rotations and incidents. A position is a block seq:

from audit_trail.integrity import KeyHistory, KeyWindow

history = KeyHistory(
    {
        OLD.key_id: KeyWindow(valid_from=1, retired_at=5210),
        NEW.key_id: KeyWindow(valid_from=5210, compromised_from=9012),
    }
)
report = verifier.maintenance.verify(verifier=KEYS, key_history=history)

A block signature counts at the block's seq, a checkpoint signature at the seq the checkpoint names. A signature that verifies but falls outside its key's window is a failure: KEY_NOT_VALID before valid_from, from retired_at on, or for a key the history does not name, and KEY_COMPROMISED from compromised_from on. Such a signature counts as none: a fork it signed explains no checkpoint, and a checkpoint it signed anchors nothing. Signatures before compromised_from still count. record_checkpoint(key_history=...) applies the same windows before it stores a note. The SignatureVerifier protocol is unchanged.

One signature outside its window is enough: record_checkpoint() refuses the whole note, and verify(checkpoints=...) does not anchor on it, even when another signature of the note is valid. During a rotation, drop the old key from the verifier you record and check new checkpoints with first: a signature of a key the verifier does not know is ignored, so a note still cosigned by the old key is then anchored by the new one.

retired_at and valid_from are block positions, and blocks are appended by every sealer and recorder. To switch keys at an exact seq while they run, pause the sealers and record_checkpoint() callers, read the last block, set the windows from it, swap the signer, and start them again.

A window limits which blocks a key may attest, not when it signed: nothing in a checkpoint says when it was signed, so whoever holds a retired or stolen key can still sign a statement naming an earlier block inside its window, and it verifies. When a key is compromised, drop it from the verifier you use for newly received checkpoints (and for record_checkpoint), and keep it only in the verifier that checks the checkpoints you already stored.

Signing outside the transaction

export_checkpoint() signs the block inside its own transaction, under the sealer's lock. That is fine for a key in memory or a KMS that answers in milliseconds, but not for a signer that waits, such as a person typing a PIN on a hardware token: every sealer waits with it. Split the export in two:

from audit_trail.integrity import prepare_checkpoint, record_checkpoint

with engine.connect() as conn:
    statement = prepare_checkpoint(conn, tables, verify={"verifier": KEYS})
# No lock and no transaction from here on; take as long as needed.
signed = statement.signed([pin_entry_signer])
with engine.connect() as conn:
    record_checkpoint(conn, tables, signed, verifier=KEYS, key_history=history)
store_off_the_box(signed.to_note())
  • prepare_checkpoint() verifies (with verify=, the keyword arguments of verify()) or takes a stored report (verified=report), refuses with CheckpointRefusedError when it has failures, and returns the unsigned statement of the verified head. With a stored report it also checks that the report's head is still a block of the chain, with its hash, and that no fork came after it, and prepares for that head, not a newer one: a long nightly run can be signed in the morning, or brought up to date first with verify(since=report). It writes nothing, takes no lock, and leaves the connection without a transaction.
  • Sign the statement with any Signer, or with any C2SP note tool over statement.text. Blocks sealed meanwhile are not covered; the next checkpoint covers them.
  • record_checkpoint() checks the signatures (with the key history, if given) and that the statement is the head as the chain holds it, then appends a checkpoint block holding the note. The same note, byte for byte, recorded again returns the block that holds it and writes nothing, so a retry after a lost connection is safe. The same head with other signatures, such as an added cosignature, is another note. signer= signs that block, for a chain verified with require_signatures.
  • A head from before a fork belongs to an earlier incarnation: after declare_fork(), both calls refuse a statement prepared before it (CheckpointRefusedError from prepare_checkpoint(), ValueError from record_checkpoint()), naming the fork block. Prepare a new one.

Retrying a record. Keep the signed note text and retry record_checkpoint() with it; do not sign again. ECDSA signatures are randomized and each has a second valid form (high S), so a note signed or encoded again is a different note, and is stored as a second checkpoint block. That is harmless, verify() stays valid, but it is noise. Ed25519 signatures are deterministic: two signers holding the same key produce the same note for the same head.

The note in the chain lets declare_fork() take its head as the last good checkpoint. It is not an anchor: keep the note off the database, as with export_checkpoint().

Every call has an async form for an AsyncConnection: aexport_checkpoint(), aprepare_checkpoint(), arecord_checkpoint() and adeclare_fork(), next to averify(). aexport_checkpoint() runs its signer on the event loop, so use the two-phase calls for a signer that waits.

Exporting a bundle

export_bundle() writes a range of the chain, and every row it seals, to one zip file that can be checked without the database: for an auditor, a court, or an archive that outlives the cluster. The format is specified, field by field, in the bundle format specification, with vector bundles to test a verifier against.

from datetime import UTC, datetime
from pathlib import Path

from audit_trail.integrity import TimeRange, export_bundle

result = export_bundle(
    engine,
    tables,
    "audit-2026-q1.zip",
    TimeRange(datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 4, 1, tzinfo=UTC)),
    checkpoints=[note],
    key_history=history,
    host_files={"case/request.pdf": Path("request.pdf")},
    signer=ARCHIVE_SIGNER,
)
print(result.first, result.last, result.rows)
  • The scope is a BlockRange(first, last) of block seqs, or a TimeRange(start, end), which takes the blocks written in it (by sealed_at). Rows are sealed shortly after they are written, so a time range may start with a few rows from just before start and leave the last ones before end to the next block. sealed_at is not hashed: a reader can check that the blocks are an unbroken range of the chain, not that they were written in that time range.
  • include="transaction", "activity" or "both" (the default) picks the tables.
  • It reads like verify(): one connection, short READ ONLY transactions, chunk_rows rows at a time, no lock. Rows are written as they are read, so memory does not grow with the range, and a bundle may hold millions of rows. destination is a path or a binary file object, which need not be seekable.
  • It does not verify. Run verify() first, or let the reader find what is wrong with verify_bundle().
  • Before it writes the header, it looks for an activity row in scope with a row state, with one EXISTS query per run of seal blocks. No index serves that query, so it is one extra pass over the activity rows in scope. A bundle with such a row is bundle version 2, which 0.8.0 and later read and a 0.7 verifier refuses (bundle version 2 is not supported, exit code 2). Every other bundle is version 1, as 0.7 wrote it.
  • aexport_bundle() takes an AsyncEngine.

The zip holds JSON Lines files, in this order:

Entry What it holds
header.json bundle_version (1, or 2 when a row in scope has a row state), stream_type ("audit"), the chain id, the scope and the tables included
blocks.jsonl the blocks in scope, of every kind, and the one before them, as stored
retired.jsonl later retire blocks of partitions the scope names, which explain rows that are gone
rows.jsonl every row the seal blocks in scope seal, block by block, in (xid, id) order
scrubs.jsonl the audit.scrubbed records the erasure stamps of those rows point to
checkpoints.jsonl the checkpoints given, and those recorded in the chain that name a block of the bundle
keys.json the key ids that signed something in the bundle, and the key history, if given
host/... the files given as host_files
manifest.note the SHA-256 and size of every entry above, as a C2SP signed note

Each row carries its sealed fields as the exact canonical text its Merkle leaf hashes, and each erasable part that holds a value as the canonical text its commitment hashes, so a verifier in another language hashes bytes and never encodes values itself. nulls lists the erasable keys stored as JSON null, which no part holds, so the erased form of a scrubbed part is checked on the row exactly as stored. An erased part is covered by its commitment, inside the sealed fields, and its stamp. Keys appear by id only: a reader trusts the keys it has from elsewhere, never ones a bundle brings.

signer= signs the manifest. Your own files under host/ are covered by the manifest, but only as far as the manifest itself is anchored: by that signature, with a key the reader trusts, or by the manifest's hash kept or committed somewhere else.

A bundle holds the audit rows as they are stored, with their personal data and the salts of every part not yet scrubbed (see privacy).

Verifying a bundle offline

verify_bundle() checks a bundle without the database, and without SQLAlchemy: on an auditor's laptop, or years later from an archive. The bundle format specification gives its algorithm step by step, for a verifier in another language.

from audit_trail.integrity import Status, verify_bundle
from audit_trail.integrity.keys import KeyVerifier

report = verify_bundle(
    "audit-2026-q1.zip",
    verifier=KeyVerifier(TRUSTED_VKEYS),
    checkpoints=[note],
    key_history=history,
)
assert report.status is not Status.FAILED

It checks the blocks of the bundle as verify() checks the chain, from the block before the scope on, and every row against the seal blocks in scope, and everything inside the scope gets the same findings as from verify(), with the exceptions below. It reads the bundle one entry and one row at a time, so memory does not grow with the rows. A bundle that cannot be read as one (not a zip, an entry missing or out of order, a line that is not JSON of the format) raises BundleError, whose message names the entry and line, never a value.

Trust comes only from the arguments. verifier holds the keys trusted to sign blocks, checkpoints and the manifest; the key ids and the key history in the bundle are never used for trust. A checkpoint in the bundle counts only when a key verifier knows signed it, like one given in checkpoints=. The report is ANCHORED when a trusted checkpoint names a block of the bundle, with its hash, the block before the scope included.

Besides verify()'s findings:

  • MANIFEST_MISMATCH: an entry does not match the manifest (its SHA-256 or size), or the manifest's hash is not the manifest_sha256 given.
  • UNANCHORED note: a host file whose manifest is not anchored. The manifest is anchored when a key verifier knows signed it (inside its window at the scope's last block, given a key_history), or when manifest_sha256= gives its hash, kept off the database or committed in the log when the bundle was written (hashlib.sha256(result.manifest.encode()).hexdigest()). Without an anchor anyone who can write the bundle can change a host file and the manifest together.
  • OUT_OF_SCOPE note, for what the bundle holds but cannot check against its chain: a checkpoint naming a block the bundle does not hold (it is not used, and is not TRUNCATED); an audit.scrubbed record sealed outside the scope or not sealed yet, which is counted but not checked against a root; a scrub whose record counts more rows than carry its stamp in the bundle, beyond what retired partitions explain (SCRUBBED_ROWS_RETIRED, as in verify()), since the others may lie outside the scope (more stamps than recorded still fail with SCRUB_COUNT_MISMATCH); a fork, retire or recorded checkpoint block that names a block before the scope; and a retire block after the scope that no trusted checkpoint names and no trusted key signed, which then explains no missing rows.
  • TRUNCATED: blocks missing from the end of the scope.

What needs the database is not reported: DETACHED_PARTITION (a detached partition's rows are not exported, so its segments are SEGMENT_MISSING), the unsealed tail, and XID_REWIND against the live horizon. A scope that starts after the genesis block knows its incarnation only when the block before it is a genesis or fork block; otherwise the report's head is None.

The same check from the command line, with only this package and cryptography (the [integrity] extra) installed:

python -m audit_trail.integrity verify-bundle audit-2026-q1.zip \
    --keys trusted.keys --checkpoint head.note --key-history key-history.json
  • --keys (required) names a file of verifier keys, one per line, as Ed25519Signer.vkey and EcdsaP256Signer.vkey give them (<name>+<key hash>+<base64>); blank lines and lines starting with # are skipped.
  • --checkpoint names a file holding one checkpoint note; give it once per checkpoint.
  • --key-history names a JSON file {key_id: {"valid_from": n, "retired_at": n or null, "compromised_from": n or null}}, the form of history in a bundle's keys.json. KeyHistory.to_json() writes it, and KeyHistory.from_json() reads it back.
  • --retention SEV=DAYS, once per severity, and --transaction-retention DAYS give the retention drop_expired() runs with, as verify_bundle(retention=..., transaction_retention=...), so that a partition retired inside it fails with RETIRED_EARLY. SEV is the integer severity; DAYS is a number of days (fractions allowed) or, for --retention, KEEP, kept forever as maintenance.KEEP. A severity not given is not checked, and the transaction table expires with the shortest retention given, as in drop_expired(). --transaction-retention alone checks only the transaction table.
  • --manifest-sha256, --system-severity and --require-signatures are verify_bundle()'s arguments; --require-anchor fails a bundle that no trusted checkpoint anchors; --json prints the report as JSON.

It exits with 0 when the bundle verified (VALID or VALID_WITH_NOTES), 1 when it did not (FAILED, or not anchored with --require-anchor), and 2 when it could not be checked: the bundle, a key file or a checkpoint file is malformed or unreadable, or the arguments are wrong.

Without --require-anchor, 0 means only that the bundle is internally consistent: anyone can build such a bundle from scratch, with a chain of their own and unsigned blocks, and the command then prints a warning on stderr. An auditor should pass --require-anchor and --require-signatures, so that 0 also means a trusted checkpoint names a block of the bundle and a trusted key signed every block.

Restores and forks

A restore can make the database disagree with a checkpoint, or reuse transaction ids that the chain has already sealed. What happens depends on how the database came back:

Event Transaction ids What to do
pg_upgrade to a new major version kept nothing
a physical standby promoted kept nothing; with require_replicated, no checkpoint names a lost block
pg_dump / pg_restore into a new cluster rewound: the sealer refuses with XID_REWIND (the horizon is below the sealed one, or restored rows carry ids no transaction has had yet) a fork, below, before any writer starts
point-in-time recovery, or a base backup started as a primary reused silently a fork; only a checkpoint shows the divergence
a logical replication subscriber its own seal() skips there and verify() refuses: seal and verify on the publisher. To make it the primary, see the cutover

declare_fork() starts a new incarnation of the chain. Run it after the restore and before any writer starts, as the sealer role, with the newest checkpoint the restored chain still has: an exported one, or a recorded one whose checkpoint block the restored chain still holds. To find it, try your stored checkpoints newest first: declare_fork() raises ValueError for one that does not match the chain and writes nothing, so the first one it accepts is the one:

from audit_trail.integrity import declare_fork

with sealer_engine.connect() as conn:
    declare_fork(
        conn,
        sealer.tables,
        last_good_checkpoint,
        reason="restored from the 2026-11-30 backup after a disk failure",
        signer=SIGNER,
    )

It first seals what the old incarnation left unsealed, then appends a fork block. verify() reports it as a FORKED note.

Restoring the same backup twice, into two databases or twice into one, gives two sibling branches with the same incarnation number: a checkpoint taken on one branch does not verify on the other.

Nothing refuses to go on sealing into a block table that a point-in-time recovery or pg_resetwal brought back: the transaction ids still move forward, so the sealer cannot tell. Only a checkpoint stored before the restore shows the divergence, so declare the fork yourself after every such restore.

A checkpoint stored before the restore may name a block that the restored chain lost or holds with another hash. Such a checkpoint is a FORKED note instead of a failure only when all of these hold:

  • the fork block is signed by a key the verifier knows, so verify() needs verifier=: without one, no fork explains anything. An unsigned fork gets a FORKED_UNSIGNED note and explains nothing either;
  • the checkpoint is of an earlier incarnation than the one the fork starts (each checkpoint records its incarnation);
  • the checkpoint names a block after the last good checkpoint the fork was declared from.

Otherwise it fails as TRUNCATED or CHAIN_MISMATCH. A checkpoint taken after the fork is never explained by it: the chain it saw already held the fork block, so a divergence since is a rewrite.

Point-in-time recovery, or a base backup started as a primary: transaction ids carry on from the restore point and repeat some ids of the lost blocks, which is harmless because those blocks are gone too. Declare the fork.

pg_dump / pg_restore, self-hosted: move the transaction ids above every stored one before any writer starts. Find the highest stored xid with SELECT max(xid::text::numeric) FROM audit.audit_activity (and the same for audit_transaction); the new epoch n is (highest stored xid >> 32) + 1. Stop the server cleanly (pg_ctl stop -m fast), then, as the operating-system user that owns the data directory:

current=$(pg_controldata "$PGDATA" | sed -n "s/^Latest checkpoint's NextXID: *\([0-9]*\):.*/\1/p")
if [ "$current" -lt "$n" ]; then
    pg_resetwal --epoch="$n" "$PGDATA"
fi

Only ever raise the epoch: a lower one would rewind the ids again. pg_resetwal refuses a server that was not shut down cleanly; do not force it with -f. Start the server and declare the fork. pg_resetwal discards the write-ahead log, so rebuild the replicas afterwards, and read its documentation first.

pg_dump / pg_restore on a managed service, where pg_resetwal is not available: declare_fork() sees the rewound ids and records an id window. The ids count as rewound when the horizon is below the sealed horizon, and also when it is above it but a restored row, one not yet sealed when the backup was taken, has an xid at or above it: a fork without a window would leave that row unsealed while new transactions reuse its id. The window is the highest id of each stream at the fork. From then on the old blocks hold the rows at or below it and the new incarnation the rows above it. This needs the identity sequences restored with the data (a full pg_restore, or a data-only restore that keeps the SEQUENCE SET entries): declare_fork() refuses when a sequence is behind the window, and every later seal refuses with ID_FLOOR_VIOLATION if new rows get ids at or below it (ALTER ... RESTART, for example): when a table's identity sequence is below the window, and, while the sequence is still within the fork's row count of the window, when a stream has more rows at or below the window than the fork counted. The second check weakens as retention drops those rows (see Limitations). id_window= forces the choice either way.

Restore the audit tables and the block table owned by audit_maintenance, as they were: ensure_partitions() and drop_expired() need the owner. Run pg_restore as that role, or, after pg_restore --no-owner as another role, REASSIGN OWNED BY <restoring role> TO audit_maintenance. On PostgreSQL 16 and later, a CREATEROLE role that is not a superuser needs GRANT audit_maintenance TO <restoring role> WITH SET TRUE first. REASSIGN OWNED moves everything the restoring role owns: every object in the current database, and every database it owns, this one included. Restore as a dedicated role that owns nothing else, or the application's tables, and the database, end up owned by audit_maintenance. ALTER DEFAULT PRIVILEGES FOR ROLE audit_maintenance in examples/roles.sql then needs a role that is a member of audit_maintenance. Whether you may grant pg_monitor depends on the provider: some let only their own admin role grant it (on PostgreSQL 18, a CREATEROLE role that is not a superuser could not).

pg_upgrade to PostgreSQL 18: initdb of 18 turns data checksums on by default, and pg_upgrade needs both clusters to match. For an old cluster without checksums, create the new one with initdb --no-data-checksums, or enable them on the old one first with pg_checksums --enable. The transaction ids are kept, so the chain needs nothing.

Point-in-time recovery is detected only against a checkpoint: without tier 2, a restore to an earlier state looks like a consistent, shorter chain.

Erasures across restores

A restore undoes every scrub run after its backup: the erased values and their salts are back, and the scrub's audit.scrubbed entry and stamps are gone with it, so the restored database cannot tell that it ever ran. verify() finds nothing wrong, because there is nothing left to compare. To erase them again, keep an erasure journal with your checkpoints:

from audit_trail.integrity import erasure_journal, export_checkpoint

with sealer_engine.connect() as conn:
    journal = erasure_journal(conn, sealer.tables, since=OLDEST_BACKUP_TAKEN_AT)
    checkpoint = export_checkpoint(conn, sealer.tables, signer=SIGNER, journal=journal)
store_off_the_box(checkpoint.to_note(), journal.to_json())

erasure_journal(since=...) lists the scrubs recorded since a point, one per scrub transaction, built from the audit.scrubbed entries and the rows they stamped. For each row it holds the table, id and xid, the parts erased (state too for an entry with a row state; the journal stays version 2, and one without such rows is what 0.7 wrote), the hash of the row's sealed fields and the seal block that held it, and it states the hash of each such block and of the genesis block. Rows without commitments, which a scrub cannot stamp, it lists apart, in uncommitted (see below). It holds no erased value and no salt. Choose since at or before the oldest backup you keep, such as the time of the checkpoint taken with it; since=None lists every scrub. It reads every row a scrub ever stamped, through the partial index add_integrity_indexes() builds, so run it with the checkpoints, not on every request. to_json() is its canonical form and ErasureJournal.from_json() reads it back.

Given journal=, export_checkpoint() and prepare_checkpoint() write a version 2 statement: the version 1 line, then {"erasure_journal":"<base64>"}, the SHA-256 commitment of the journal's canonical form. They first check that every block the journal states is in the chain, with that hash, at or before the checkpoint's block, and refuse it otherwise. A checkpoint without a journal is the version 1 statement, byte for byte as before. A version 2 checkpoint needs 0.5.0 or later to read.

The journal's own canonical form is versioned too (specification). erasure_journal() writes version 2, which adds the rows without commitments; 0.5.0 cannot read it. A version 1 journal kept with a 0.5.0 checkpoint still reads, keeps its commitment, and re-applies as before.

After a restore, and after declare_fork() when the restore calls for one, re-apply the journal before the database is used again:

from audit_trail.integrity import reapply_erasures

with maintenance_engine.connect() as conn:
    result = reapply_erasures(
        conn, tables, journal_text, checkpoint=checkpoint_note, verifier=KEYS
    )
if result.outside or result.mismatched:
    # These rows still hold the erased values. Keep the database closed
    # until they are dealt with (see below).
    for row in (*result.outside, *result.mismatched):
        logging.error("erased data is back: %s %s", row.table, row.id)
    raise SystemExit(1)

It trusts the journal only through the checkpoint, and refuses with JournalRefusedError, changing nothing, unless:

  • the checkpoint is signed, every signature of a key the verifier knows verifies, and at least one does; with key_history=, each such key is inside its window at the checkpoint's block;
  • the checkpoint commits to exactly this journal, and both are of this chain;
  • the restored chain still holds, with the same hash, at least one block the checkpoint or the journal states (the journal always states the genesis block, so a restore of the same chain passes this). The newest such block is shared_to: a block's hash covers every block before it, so the chain is proven the same up to there. A stated block below it with another hash is refused.

Only rows sealed in a block at or before shared_to, whose sealed fields still give the hash the journal holds, are erased again. The rest are left alone and listed: outside (not sealed when the journal was built, or sealed after shared_to, or without commitments: nothing in the chain proves the row is the one that was erased), missing (gone, such as a dropped partition) and mismatched (changed since; verify() reports it). Seal before you take a backup, so that the rows it holds are sealed.

Rows left alone still hold the erased data. The values and salts the restore brought back stay readable, through the query API too, until something erases them again. By default every row that was not sealed when the backup was taken is in outside. A point-in-time recovery always has such a tail, the rows written after the last seal before the restore point, and so does a pg_dump taken while writers run. Review those rows, then run reapply_erasures() again with include_unproven=True (below), or replay the original scrub() and scrub_actor() calls. Logging them is not enough.

include_unproven=True erases the outside rows too, after checking each one as far as the journal allows: the row is still there with the journal's table, id and xid; its sealed fields, seal_commitments among them, still give the journal's leaf hash; and every part the journal names still holds the value its commitment was made to, with its salt (or is erased and stamped already). The journal holds no value, so that is all it can check: the row matches what the scrub erased, but no block attests that it was in the chain the checkpoint was taken of. A row that fails a check is listed in mismatched and left alone. The rows erased this way are listed in unproven, and their audit.scrubbed entries carry "unproven": true in reapplies.

The rows are erased as the original scrubs erased them, with their salts deleted and their parts stamped, in one transaction, and recorded by audit.scrubbed entries with the reason audit.restore_reapply, the severity of the original entry, and reapplies, the original scrub's transaction id and reasons. A journal taken later lists the original reasons for these entries, so they carry through a second restore. Parts already stamped are left alone, so a second run changes nothing (already_erased counts them). verify() then accounts for the new entries like any scrub. Its role needs what a scrub needs, and SELECT on the block table (see roles). aerasure_journal() and areapply_erasures() are the async forms.

Rows without commitments

A row written before integrity was turned on (an install upgraded from 0.4) or by a writer without Integrity() carries no commitments, so a scrub cannot stamp it. The scrub lists such rows in its audit.scrubbed entry instead, as uncommitted: {"activity": [[id, xid], ...], "transaction": [...]}, with xid null for a row older than the column. The entry grows with them, so a scrub of many such rows writes a large entry. The journal reads the list and names each row in uncommitted, with its table, id, xid and the parts the scrub erased (UncommittedRow).

Nothing proves such a row is the one the scrub erased: no seal block holds it and no commitment covers its values. reapply_erasures() therefore lists them in outside by default, and erases them only with include_uncommitted=True, when the row is still there with the journal's table, id and xid (both null for a row older than the column), and still has no commitments. A row that fails that is listed in mismatched (or missing) and left alone; one already in erased form counts in already_erased. The rows erased this way are listed in uncommitted, and their audit.scrubbed entries carry "uncommitted": true in reapplies and list the rows again, so a journal taken later carries them through the next restore. include_unproven does not cover them: its rows are checked against their leaf hash and commitments, these only by id and xid, so each needs its own decision.

Scrubs run before 0.6.0 did not list these rows, so no journal names them: replay those scrub calls after a restore.

A logical replication cutover

Moving the audit log to a new server by logical replication (publish both audit tables with publish_via_partition_root = true, and audit_seal_block) gives the subscriber its own transaction ids and no identity sequence values. While it subscribes, seal() skips and verify() refuses there. To make it the primary:

  1. Stop the writers on the publisher. Seal until capped is false, and export a checkpoint.
  2. Wait until the subscriber has every row and block (compare max(seq) of audit_seal_block on both).
  3. On the subscriber, DROP SUBSCRIPTION.
  4. Move both identity sequences past the copied rows, since logical replication does not copy them:

    SELECT setval(pg_get_serial_sequence('audit.audit_transaction', 'id'),
                  (SELECT max(id) FROM audit.audit_transaction));
    SELECT setval(pg_get_serial_sequence('audit.audit_activity', 'id'),
                  (SELECT max(id) FROM audit.audit_activity));
    
  5. declare_fork(conn, tables, checkpoint, reason=..., signer=SIGNER, id_window=True) with the checkpoint of step 1, then start the writers on the new primary.

PgBouncer

Behind PgBouncer, choose the pool mode by job:

Job Transaction pooling Session pooling or a direct connection
Audit writes, seal(), verify() / averify(), export_checkpoint(), prepare_checkpoint(), record_checkpoint(), declare_fork() and their async forms, acknowledge(), ensure_partitions() yes yes
drop_expired() no yes

drop_expired() holds a session-level advisory lock and lock_timeout across its statements, in AUTOCOMMIT, because DETACH PARTITION ... CONCURRENTLY cannot run in a transaction. Behind transaction pooling it refuses: it checks that its statements stay on one server connection before it sets anything, before each retire block and before each DDL statement, and otherwise raises PartitionError before writing a retire block or detaching anything. Give the retention job a direct connection or a session-pooled one; see connection poolers. In session mode a pooled connection is held for as long as the client keeps it, so keep the client pool small, or use NullPool, when the bouncer's default_pool_size is small.

Prepared statements: PgBouncer 1.21 and later, with max_prepared_statements above 0 (200 by default since 1.24), handle the drivers' prepared statements in transaction mode. With max_prepared_statements = 0, or an older PgBouncer, turn them off in the driver:

# psycopg 3
engine = create_engine(URL, connect_args={"prepare_threshold": None})

# asyncpg
engine = create_async_engine(
    URL + "?prepared_statement_cache_size=0",
    connect_args={"statement_cache_size": 0},
)

Without that, statements fail with errors such as prepared statement "_pg3_0" already exists. Under on_error="log" (the default) a failed audit write is then only logged on audit_trail.writer and the business transaction goes on, so audit entries are lost without an exception; see events.

Sizing

Measured on PostgreSQL 18 in a container with 4 CPUs and 4 GB, with the client on the same host (PostgreSQL 14 gave the same within noise):

  • Sealing is bound by the sealer's CPU, not by the database: one call of 50,000 rows takes about 3 seconds on an idle host, about 16,000 rows per second, or roughly 2,400 transactions of 6 rows per second for one sealer. It is slower when the sealer shares its CPUs with the writers, so give it a core of its own. Its memory stays at about 70 MB whatever the backlog.
  • One large transaction is sealed whole, in one call: a transaction of 200,000 rows holds that call's REPEATABLE READ snapshot, and with it the vacuum horizon, for as long as hashing it takes (some seconds per 50,000 rows).
  • verify() reads about 10,000 rows per second on an idle host and stays at about 85 MB with the default chunk_rows=2000; a larger chunk_rows is not faster and uses more memory. About a third of its time is reading the rows, a third encoding their leaves, and a third the commitments of their erasable parts.
  • verify_bundle() checks about 13,000 rows per second on one core: it hashes the leaf text the bundle holds instead of encoding the row again.
  • drop_expired() spends almost all its time in verify_before_drop, which verifies the expired partitions: about a minute per 500,000 rows on an idle host, more under write load. The retire blocks and the DETACH / DROP take well under a second, and writers waited at most 10 ms on locks during it.
  • Writes with integrity on: at 500 transactions of 5 entries per second, with the sealer on the same host, the median transaction took 3 to 7 ms longer. Writes take no extra lock or round trip; most of that is the sealer's CPU.

Keep the defaults max_rows=50_000 and chunk_rows=2000: a larger max_rows only lengthens each snapshot.