Evidence ledger¶
audit_trail.ledger is an append-only log of entries your application writes explicitly: a document received, a consent given, a decision made, a file handed over. Each entry is sealed in the writer's own transaction, numbered without gaps, and hashed into a Merkle tree, so a writer gets a receipt for its entry when its transaction commits, and anyone can later prove that the entry is in the log and that the log only grew.
It is tamper-evident, not tamper-proof, like integrity: the application role cannot change, reorder or delete an entry, but the owner of the tables or a superuser can, and only a signed checkpoint kept off the database shows it. The format is specified in the ledger format spec, with test vectors.
When to use it¶
| You want | Use |
|---|---|
| Every change to your models, and the domain events you declare, with who, where and how, queryable and partitioned by severity | the row audit (AuditTrail) |
| Proof that nobody edited or deleted those audit rows | integrity on top of the row audit |
| Records that must hold up as evidence on their own: numbered without gaps, a receipt per entry at write time, inclusion and consistency proofs for a third party, erasable payload with a receipt, and restores recorded in the log | the ledger |
The ledger needs no AuditTrail and no extra; only the reference signers for checkpoints need the [integrity] extra (cryptography). It lives in its own five tables, which can share a schema and a transaction with the row audit. Entries are not partitioned and are never retired: a chain holds everything appended to it, and only the payload of an entry can be erased.
How it works¶
- A ledger holds named chains. Each chain is a log of entries numbered by
seq, gapless from 1. - An entry has a
type, attributes that are never erased, an optional payload of named groups that can be erased later, anactor, adeclared_attime and anentry_id. The payload is stored apart, salted, and the entry's body holds only a commitment to each group, so erasing it later leaves the tree unchanged. - Appending goes through a
SECURITY DEFINERfunction. It takes the chain's lock, gives each entry the nextseq, reads the append time, computes the RFC 6962 leaf hash and the new tree root, and returns aHeadper entry. The application role may call it and read the tables, but not write them. - A head
(size, root)states the whole chain up tosize. Inclusion and consistency proofs are served from stored nodes and checked against a head you trust. - Checkpoints are signed heads, in the C2SP tlog-checkpoint format, for you to keep where the database cannot reach them.
- Each chain stores the identity of the cluster it runs on, and every append checks it first: a restore of the database starts a new incarnation of the chain, recorded in the chain itself.
verify()rebuilds every leaf, node and root from the stored rows;export_bundle()writes a range of a chain to one file thatverify_bundle()checks without the database.
Setting up¶
Tables and functions¶
build_ledger_tables() declares the tables, and create_ledger_tables() creates them with their functions. In an Alembic migration, run as the role that will own the ledger:
from alembic import op
from audit_trail import ledger
tables = ledger.build_ledger_tables(schema="audit")
def upgrade() -> None:
ledger.create_ledger_tables(op.get_bind(), tables)
for statement in ledger.ledger_grant_statements(tables, "app_user"):
op.execute(statement)
def downgrade() -> None:
ledger.drop_ledger_tables(op.get_bind(), tables)
Every statement is idempotent: running create_ledger_tables() again, after an upgrade of the package, replaces the functions with the new version's and keeps the tables and their rows. create_ledger_statements() and create_ledger_sql() give the same DDL as a list or a script, for a migration tool other than Alembic.
The tables are audit_ledger_state (one row per chain: its size, root, frontier, incarnation and cluster identity), audit_ledger_entry (one row per entry: the body bytes as written, the leaf hash, and copies of the body's fields for queries), audit_ledger_payload (the erasable groups, with their salts), audit_ledger_node (the closed subtrees of the tree) and audit_ledger_config (one row per chain). Their keys:
| Table | Primary key | Notes |
|---|---|---|
audit_ledger_state |
chain |
size, root, frontier, incarnation, and the cluster identity |
audit_ledger_entry |
(chain, seq) |
entry_id is unique across all chains; incarnation, type, actor, declared_at, appended_at and attributes are there for queries |
audit_ledger_payload |
(chain, seq, group_name) |
no entry_id: join it to the entry on (chain, seq); salt and value are bytes |
audit_ledger_node |
(chain, level, index) |
hash |
audit_ledger_config |
chain |
the chain's current config |
You may query them for your own reports, but read evidence through the API: verify(), the proofs and export_bundle() check what they read, a plain SELECT does not. Nobody but the owner writes them.
Ownership¶
Run the DDL as the role that will own the ledger, such as audit_maintenance in roles, in a schema that role owns and in which no other role has CREATE. The functions run as their owner, so whoever owns them can write the tables; nobody else should be able to.
CREATE TABLE IF NOT EXISTS keeps a table that is already there, so a table another role created first under one of the ledger's names would be adopted, and a role that may create in the schema could add objects there for the functions to find. create_ledger_tables() therefore refuses, with a message that names the problem, when:
- a ledger table is owned by another role than
current_user; - the schema is owned by another role than
current_user. Create it as the owner first, or letcreate_ledger_tables()create it; - another role, or
PUBLIC, hasCREATEon the schema. Revoke it (REVOKE CREATE ON SCHEMA audit FROM PUBLIC):USAGEis all the other roles need.
Superusers, and roles that are members of the owner, can do what the owner can, and are not checked.
The owner needs CREATE on the database (the DDL starts with CREATE SCHEMA IF NOT EXISTS), and creating a chain with restore detection on needs pg_control_system(), which PostgreSQL lets every role call.
Grants¶
The application role gets what ledger_grant_statements(tables, role) lists: USAGE on the schema, SELECT on the five tables, and EXECUTE on three functions: the append function, the record-checkpoint function and the bundle-manifest function. No INSERT, UPDATE or DELETE. The statements also revoke EXECUTE on every other ledger function from the role, and every privilege on the five tables before they grant SELECT, in case ALTER DEFAULT PRIVILEGES granted them when the functions and tables were created: a TRIGGER privilege, say, would let the role run its own code inside the functions, as the owner. The ledger has no sequences. Run them as the owner, after create_ledger_tables(), and again after each upgrade that runs it.
Erasing is separate. Either give an eraser role what ledger_eraser_grant_statements(tables, role) lists, USAGE, SELECT on audit_ledger_entry and EXECUTE on the erase function and nothing else, or let the application erase with ledger_grant_statements(tables, role, erase=True):
from sqlalchemy import text
with owner_engine.begin() as conn:
for statement in ledger.ledger_eraser_grant_statements(tables, "ledger_eraser"):
conn.execute(text(statement))
A read-only role, for a verifier or an auditor, gets what ledger_reader_grant_statements(tables, role) lists: USAGE on the schema and SELECT on the five tables, and nothing else. That is enough for verify(), the proofs, prepare_checkpoint(), erasure_journal() and export_bundle(), which only read; it cannot append, record a checkpoint or a bundle manifest, erase, create a chain or write a row. Like the other helpers, its statements first revoke EXECUTE on every ledger function and every privilege on the tables, which default privileges may have granted.
The eraser grant reads audit_ledger_entry only, so an eraser cannot run verify(), erasure_journal() or the other reads. If it should, give it the reader grant through a role of its own: run ledger_reader_grant_statements() for a role such as ledger_reader, then GRANT ledger_reader TO ledger_eraser. Do not run two helpers for one role: each revokes what the other grants, so the last one run wins.
Creating a chain, changing its config, recording maintenance, recording a restore and confirming an upgrade stay with the owner. The roles page sums up who may do what.
READ COMMITTED¶
Append under READ COMMITTED, PostgreSQL's default. Under REPEATABLE READ or SERIALIZABLE, a transaction that waited for a chain's lock while another appended to it fails with a serialization failure (SQLSTATE 40001) once the other commits: roll back and retry it.
A connection in AUTOCOMMIT is refused with ValueError by every call that writes: the chain's lock and lock_timeout would last only for the call.
Chains¶
A chain is created once, by the owner, with its config. Its name matches ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$: no space, no /.
from audit_trail.ledger import ChainConfig
CONFIG = ChainConfig(
reason_codes=("RETENTION_EXPIRED", "DATA_SUBJECT_REQUEST"),
protected_types=("case.closed",),
precondition="ledger_may_erase",
)
with owner_engine.begin() as conn:
ledger.create_chain(conn, tables, "evidence", CONFIG, actor="migration")
The chain's first entry, ledger.chain_started, records the config whole, and the config table holds it too, so a chain never runs under a config it has not recorded.
reason_codes: the codes an erasure may give, such asDATA_SUBJECT_REQUEST. A code matches^[A-Za-z][A-Za-z0-9_.-]{0,63}$and does not start withledger.. There is no free text: a reason is a code you define. With no codes, nothing can be erased.protected_types: entry types that may never be erased.precondition: the name of a SQL function every erasure must pass, orNone. See erasure.detect_restores(on by default): store the cluster identity, so that appends can tell when the database was restored. It is fixed when the chain is created. Turn it off only where the identity functions cannot be called;create_chain()then fails with aDBAPIErrorwhile it is on.
Types and reason codes starting with ledger., in any case, are the package's. Creating a name twice raises ValueError.
Writing entries¶
An Entry is a frozen dataclass. Building one checks nothing: add(), append() and append_many() check it, and refuse it with ValueError or TypeError before anything is written.
type: your type, such ascase.document_received, matching^[A-Za-z][A-Za-z0-9_.-]{0,127}$;attributes: a JSON object, never erased. The package checks only that it encodes canonically; validate it yourself;payload: group name (^[a-z][a-z0-9_]{0,63}$) to value, the erasable part. A group whose value isNoneis left out;actor: who submitted it, orNone; at mostMAX_ACTOR_LENGTH(1024) characters;declared_at: the time you declare, an awaredatetime, now by default. The append time is the database's, read under the lock; both are in the entry;type_version: the version of your type's schema, 1 by default;entry_id: auuid.UUID, random by default. It is stable before the entry is appended, so your own tables can reference it.
Values must fit the canonical encoding: None, bool, int, finite float, Decimal, str, lists and tuples, and dicts with str keys, at most 4300 digits per number and 256 nested levels. Convert dates, UUIDs and the like to text yourself. A value without a canonical encoding is refused with CanonicalEncodingError, a ValueError, before anything is written.
From a session¶
ledger.add() is the recommended way to write from a session, sync or async. It buffers the entry in the session; the outermost commit flushes the session, so your ORM changes and the rows of an installed AuditTrail are written first, then appends each chain's entries with one call, and commits:
import uuid
from audit_trail.ledger import Entry
document_id = uuid.uuid4()
with SessionLocal() as session, session.begin():
session.add(Document(id=document_id, title="Bank statement, March"))
pending = ledger.add(
session,
tables,
"evidence",
Entry(
"case.document_received",
attributes={"case": "2026-114", "document": str(document_id)},
payload={"submitter": {"name": "Jane Roe", "email": "jane@example.org"}},
actor="clerk-17",
),
lock_timeout="2s",
)
receipt = pending.head
assert receipt is not None
print(receipt.seq, receipt.leaf_hash.hex())
add()checks the entry at once and runs no SQL. It begins the session's transaction if none has begun, as a query would, sosession.begin()comes before it, not after.- The returned
PendingHeadgets itsheadonce the transaction has committed: a head handed out before could name an entry that a rollback undoes. A rollback, of the transaction or of the savepoint the entry was added in, or closing the session without committing, discards the entry:discardedis thenTrueandheadstaysNone. - The chain's lock is held only from the append to the commit. Chains are appended in a fixed order (by schema and name), so two sessions writing the same chains cannot deadlock.
- An empty buffer runs no SQL and takes no lock, and sessions that never call
add()run no extra code. - A chain's entries of one transaction are appended in one call, under one
lock_timeout: when they give different ones, the last one given (notNone) applies. - The commit raises what the append raises and does not commit:
LedgerBusyError(below),ValueErrorfor an unknown chain,IntegrityErrorfor anentry_idused before, or the error of the final flush. Roll the session back.
pending.entry.entry_id and pending.head (seq, leaf_hash, size, root) are the writer's receipt. Keep them where the person or system that submitted the entry can find them.
On a connection¶
append() and append_many() append in the connection's current transaction, under one lock per call:
with engine.begin() as conn:
heads = ledger.append_many(
conn,
tables,
"evidence",
[
Entry("case.note_added", attributes={"case": "2026-114", "note": n})
for n in range(3)
],
lock_timeout="2s",
)
latest = heads[-1]
The lock is held until the transaction ends, so append last, just before the commit, and keep the transaction short. The heads are provisional until the commit: a rollback frees their numbers for the next append. An empty list touches nothing.
One call takes at most MAX_BATCH (10,000) entries: append_many() refuses more with ValueError, and the append function, which the application role may call without the package, refuses more too, so no single call holds the chain for long. Append a larger batch in several calls; add() does that itself, one call per MAX_BATCH entries of a chain, in order and in the same transaction, each with its own append time.
Async¶
add() takes an AsyncSession as it is; the append runs in await session.commit(). On an AsyncConnection, use aappend() and aappend_many(); the other calls that use the database have an a form too (acreate_chain, aerase, averify, aprepare_checkpoint, ...), with the same arguments:
async def record_view(case: str, viewer: str) -> None:
async with async_engine.begin() as conn:
await ledger.aappend(
conn,
tables,
"evidence",
Entry("case.viewed", attributes={"case": case}, actor=viewer),
)
async with AsyncSessionLocal() as session:
exported = Entry("case.exported", attributes={"case": case}, actor=viewer)
ledger.add(session, tables, "evidence", exported)
await session.commit()
The chain's lock¶
Appends to one chain are serialized by a row lock on its state row. Each wait for a lock is bounded by the transaction's lock_timeout, or the one given as lock_timeout= ("2s"); when a wait runs out, the call raises LedgerBusyError. The transaction is then aborted: roll it back and retry later. Without a lock_timeout anywhere, a writer waits for as long as another transaction holds the chain, so set one.
lock_timeout bounds each wait, not the total. A call can wait for the row's lock, then for the transaction of each writer that held the row before it, and each of these waits may last up to lock_timeout. To bound the whole call, also set statement_timeout in the transaction (SET LOCAL statement_timeout = '5s'). It cancels the statement with SQLSTATE 57014 (query_canceled), raised as a DBAPIError, not LedgerBusyError: roll back and retry as for a busy chain.
The lock is not fair: waiters are not served in the order they came. With 16 writers on one chain, the 99th percentile of append latency was 10 to 40 times the median. Different chains do not wait for each other, so spread the load: a chain per tenant, case or box keeps the waits short.
Heads and proofs¶
A head (size, root) commits to the first size entries; (seq, leaf_hash) is an entry's own receipt. inclusion_proof() and consistency_proof() serve RFC 9162 proofs from the stored nodes, reading O(log n) hashes in one statement. Check them against heads you trust, such as heads your own appends returned or a signed checkpoint, never against the roots the proof carries:
first = receipt # the head of an earlier entry, kept by its writer
with engine.connect() as conn:
inclusion = ledger.inclusion_proof(conn, tables, "evidence", first.seq, latest.size)
consistency = ledger.consistency_proof(
conn, tables, "evidence", first.size, latest.size
)
assert inclusion.verify(latest.root, leaf_hash=first.leaf_hash)
assert consistency.verify(first.root, latest.root)
InclusionProof.verify(root, leaf_hash=None)checks that the entry atseqis in the tree ofsizewhose root isroot. Give the leaf hash you hold; by default it uses the stored one the proof carries.ConsistencyProof.verify(old_root, new_root)checks that the tree ofnew_sizeextends the tree ofold_size: nothing beforeold_sizechanged.- Both return
Falsefor anything that does not hold, and never raise. sizeandnew_sizedefault to the chain's current size; the proof carries the root of that size, which you then compare with a head you trust.
The tree is the RFC 6962 tree, so any RFC 9162 verifier checks these proofs too; the Merkle vectors give roots and proofs to test one against.
Three kinds of head¶
Headis what an append returns, one per entry:incarnation,seq,leaf_hash,sizeandroot.(seq, leaf_hash)is the writer's receipt for its entry, and(size, root)the tree just after it. It is provisional until the transaction commits.PendingHeadis whatadd()returns: thechain, theentry, andhead, the entry'sHeadonce its transaction has committed, elseNone.discardedisTruewhen a rollback dropped the entry.LedgerHeadis a head of the chain as a whole:chain,incarnation,sizeandroot.verify()returns one asreport.head, and a checkpoint signs one.
To read a chain's current head, run verify() and take report.head: the head it read first and then verified. To keep that cheap, pass an earlier report as since= (see catching up), so that it reads only the entries after it:
with engine.connect() as conn:
report = ledger.verify(conn, tables, "evidence", since=nightly)
current = report.head # LedgerHead(chain, incarnation, size, root)
Erasure¶
erase() deletes an entry's payload rows, values and salts, and appends a receipt, ledger.erased, in one call. It is the ledger's own erasure; the row audit's is scrub(), in privacy.
from audit_trail.ledger import ErasureRefusedError
try:
with eraser_engine.begin() as conn:
erased = ledger.erase(
conn,
tables,
"evidence",
pending.entry.entry_id,
"DATA_SUBJECT_REQUEST",
actor="dpo-2",
)
except ErasureRefusedError as exc:
logging.warning("not erased: %s", exc)
The erase function locks the chain, then checks, under the chain's current config, that the reason code is one of the chain's, that the entry's type is not protected and not a package type (a receipt is never erased), that the entry has payload left (a second erasure is refused, not repeated), and that the precondition returns true. Any refusal raises ErasureRefusedError and aborts the transaction: roll it back. An entry_id that is not in the chain raises a plain ValueError instead, before the erase function runs, as does a chain name or reason code that does not match its pattern. ErasureRefusedError is a ValueError too, so catch it first.
The receipt's attributes are the erased entry's entry_id, incarnation and seq, and the reason_code; no free text. The entry's body and its commitments stay, so the tree, every head and every proof are unchanged. verify() reports the missing payload as an ERASED note, explained by the receipt, and fails with PAYLOAD_MISSING for payload missing without one.
The attributes are never erased: keep personal data in the payload.
A restore undoes erasures made after the backup. record_restore() erases again only what the journal of the restore kit it is given lists, so after erasures take a new checkpoint and keep its kit, and keep a log of erasures off the database: see erasures after the newest kit.
The precondition¶
A chain's precondition names a SQL function (chain text, entry_id uuid, reason_code text) RETURNS boolean; anything but true refuses the erasure. Use it to keep entries under a legal hold, for example:
CREATE FUNCTION audit.ledger_may_erase(chain text, entry_id uuid, reason_code text)
RETURNS boolean
LANGUAGE sql
STABLE
SET search_path = pg_catalog, pg_temp
AS $$
SELECT NOT EXISTS (SELECT FROM public.legal_hold AS h WHERE h.entry_id = $2)
$$;
- A bare name is looked up in the ledger's schema;
schema.namenames another. The name is never pasted into SQL: it is resolved by its exact signature and called with bound arguments. Capitals must match the function's name as created. - It must be owned by the ledger owner, so that no other role can change what runs with the owner's rights, and it reads with the owner's privileges: grant the owner
SELECTon the host tables it reads. - It must set its own
search_path, ending inpg_temp, asSET search_path = pg_catalog, pg_tempdoes. PostgreSQL searches the caller's temporary schema first for tables unless the path lists it, so an eraser could otherwise create a temporarylegal_hold, empty, and erase what is on hold. The erase function refuses every erasure while the function breaks this rule, andcreate_chain()andchange_config()refuse a precondition whose function already exists and breaks it, with aDBAPIError. Qualify every name in it, or list its schema beforepg_temp: a bare name in no schema of the path is still looked up inpg_temp. - A missing function, or one with another signature, owner or search path, refuses every erasure.
Changing the config¶
change_config() replaces the config whole and records it in a ledger.config_changed entry, under the chain's lock: an append or erasure runs under the config before the change or after it, never a mix. Only the owner may call it, and detect_restores cannot change:
from dataclasses import replace
with owner_engine.begin() as conn:
ledger.change_config(
conn,
tables,
"evidence",
replace(CONFIG, reason_codes=(*CONFIG.reason_codes, "COURT_ORDER")),
actor="dpo-2",
)
A receipt is checked against the config in force when it was appended, which verify() rebuilds from the config entries.
Restore detection and incarnations¶
With detect_restores on, every append first compares the cluster identity stored on the chain's state row with the one it observes: the system identifier (pg_control_system()), the WAL timeline, the state table's OID and the server's major version. The first rule that matches applies:
| What changed | Typical cause | Result |
|---|---|---|
| The state table's OID | pg_dump / pg_restore, into a new cluster (new_cluster) or the same one (recreated) |
a new incarnation |
| The system identifier, with a higher major version | pg_upgrade |
a ledger.cluster_changed entry, no new incarnation, unconfirmed until the owner confirms it |
| The system identifier | pg_createsubscriber on a standby |
a new incarnation, new_cluster |
| The timeline | point-in-time recovery, a promoted standby | a new incarnation, new_timeline |
A new incarnation starts with a ledger.incarnation_started entry, appended before the caller's entries, which holds the cause and both identities. The sequence and the tree go on across it: an incarnation is a marked boundary, not a new chain. A chain that holds only its first entry has nothing to protect, so its identity is updated silently.
verify() notes every incarnation that nothing explains, UNEXPLAINED_INCARNATION. Two calls explain one:
-
record_maintenance(), for planned work that looks like a restore from inside the database: a dump-and-restore upgrade, a switchover to a standby. It appendsledger.maintenancewith a reason code of yours, after the append's own detection, so it explains the incarnation that detection just started. Only the owner may call it: -
record_restore(), for a restore from a backup, below.
Major upgrades¶
The second rule assumes that a new system identifier with a higher major version, and the same state table OID, is pg_upgrade, which keeps the data files as they were. It cannot tell that from a data-only restore of an older dump into a fresh cluster of a higher major version whose ledger tables were created by the same migrations: a fresh cluster gives out OIDs in the same order, so the state table gets its old OID back. The entries written after the dump are then gone, and the chain shows only a ledger.cluster_changed entry.
So a cluster change stays unconfirmed until the owner confirms it. Appends go on meanwhile: nothing is blocked. verify(), and a bundle verifier, note each ledger.cluster_changed that no confirmation names as UNCONFIRMED_UPGRADE; the report stays valid, with notes. To upgrade:
- Right before the upgrade, stop the writers, take a checkpoint (
prepare_checkpoint(), sign,record_checkpoint()) and store its kit off the database. - Upgrade. The first append after it writes
ledger.cluster_changed; note itsseq. - Verify the chain against that checkpoint. It must be
ANCHORED, with no failures: a chain that lost entries fails withTRUNCATEDorCHAIN_MISMATCH, and is a restore to record withrecord_restore(), not an upgrade. Passrestored_size=theseqbefore theledger.cluster_changedentry: detection started no incarnation here, so without it the call takes the chain's current size, which includes the entries appended since, and understates the lost range. - Confirm the upgrade as the owner with
confirm_upgrade(), which appendsledger.upgrade_confirmednaming that entry:
from audit_trail.ledger import Anchor, RestoreKit
before = RestoreKit.from_json(kit_text) # taken right before the upgrade
with engine.connect() as conn:
report = ledger.verify(
conn,
tables,
"evidence",
checkpoints=[before.checkpoint],
verifier=KEYS,
key_history=HISTORY,
)
changed = [n for n in report.notes if n.kind is ledger.LedgerNote.UNCONFIRMED_UPGRADE]
if report.failures or report.anchor is not Anchor.ANCHORED:
raise RuntimeError("the chain lost entries: record a restore, do not confirm")
with owner_engine.begin() as conn:
for note in changed:
ledger.confirm_upgrade(conn, tables, "evidence", note.seq, actor="ops")
confirm_upgrade() refuses, with ValueError, a seq that is not a ledger.cluster_changed entry and one that is confirmed already; aconfirm_upgrade() is its async form. Only the owner may call them: the application, eraser and reader roles get no EXECUTE on the function. A verifier fails a confirmation that names anything else, or the same cluster change twice, with MALFORMED_ENTRY, and it confirms nothing.
A cluster change recorded as a restore is never confirmed, so its UNCONFIRMED_UPGRADE note stays: the ledger.restored entry after it is what explains it. Do not confirm it to clear the note.
Checkpoints¶
A checkpoint is a signed head. Kept where whoever can rewrite the database cannot reach it, it catches a chain rewritten, cut short or restored to an earlier state (see checking a stored checkpoint), and it is what record_restore() trusts. Take one on a schedule, and after events that matter.
It takes three steps, so that signing holds no lock and no transaction, for a signer that waits, such as a person typing a PIN on a hardware token:
import os
from audit_trail.integrity.ed25519 import Ed25519Signer, Ed25519Verifier
from audit_trail.ledger import KeyHistory
SIGNER = Ed25519Signer.from_skey(os.environ["LEDGER_SIGNER_KEY"])
KEYS = Ed25519Verifier([SIGNER.vkey])
HISTORY = KeyHistory.from_vkeys([SIGNER.vkey])
ORIGIN = "audit.example.org/ledger"
with engine.connect() as conn:
prepared = ledger.prepare_checkpoint(
conn,
tables,
"evidence",
origin=ORIGIN,
verify={"verifier": KEYS, "key_history": HISTORY},
journal=True,
)
# No lock and no transaction from here on; take as long as needed.
signed = prepared.checkpoint.signed([SIGNER])
with engine.begin() as conn:
recorded = ledger.record_checkpoint(
conn, tables, "evidence", signed, verifier=KEYS, key_history=HISTORY
)
store_off_the_box(recorded.kit.to_json())
Ed25519Signer.generate(name) makes the signing key: keep its skey secret (here in LEDGER_SIGNER_KEY) and give its vkey to the verifiers, as in integrity's keys.
prepare_checkpoint()runsverify()now (verify=, its keyword arguments,{}for none) or takes a report you kept (verified=report), refuses withCheckpointRefusedErrorwhen the report has failures, and returns aPreparedCheckpoint: the unsignedLedgerCheckpointof the verified head, the journal, the report, and the consistency proof from the checkpoint before (see the restore kit). A kept report's head must still be a head of the chain as it is now, and of its current incarnation;verify(since=report)brings an old report up to date quickly. It reads committed data in shortREAD ONLYtransactions, writes nothing, and needs a connection without a transaction.- Sign it with any
Signer(checkpoint.signed([...])), or with any C2SP note tool overcheckpoint.text. Entries appended meanwhile are not covered; the next checkpoint covers them. record_checkpoint()checks the note (signed, every signature of a key the verifier knows verifies, at least one does, each such key valid in the key history, the origin of this chain, the journal line against the chain's receipts), then appends aledger.checkpointentry holding it, and returns aRecordedCheckpointwith the journal, the proof and thekit. The application role may call it. The same note recorded again returns the entry that holds it (createdisFalse) and writes nothing, so a retry after a lost connection is safe: keep the signed note text and retry with it, do not sign again.
Then store the restore kit, which holds the signed note, off the database: S3 Object Lock in compliance mode, an RFC 3161 timestamp, another machine, as for integrity's checkpoints. The note in the chain is a record that a checkpoint was taken, not an anchor.
The origin¶
A checkpoint's first line is its origin, <host origin>/<chain>/i<incarnation>, such as audit.example.org/ledger/evidence/i1:
audit.example.org/ledger/evidence/i1
42
3q2+7w...base64 of the root...=
sqlalchemy-audit-trail/ledger-journal/v1 Xk1...base64 of the journal commitment...=
— audit.example.org/officer Az3Q...signature...
The host origin is yours: a schema-less URL of 1 to 200 printable ASCII characters, no space or +, not ending in /. Naming the incarnation means two incarnations never sign one origin with different trees. checkpoint_origin(host, chain, incarnation) builds one, and LedgerCheckpoint.from_note(text) reads a note back, with chain, incarnation, size and root.
extensions= adds your own lines after the statement, signed with it, under integrity's rules for extension lines: prefix them with a name of your own; none may start with sqlalchemy-audit-trail/.
Key history¶
A retired or stolen key still verifies. KeyHistory gives each key the window of chain positions it may attest, by seq, as in integrity's key history: a checkpoint signature counts at the size the checkpoint names. A signature outside its window fails as KEY_NOT_VALID (before valid_from, from retired_at, or a key the history does not name) or KEY_COMPROMISED (from compromised_from). record_checkpoint() and record_restore() require a key history and refuse a note signed outside a window; verify() takes one with verifier=.
Give every key the verifier knows a window: a key the history does not name does not count. While no key was ever rotated out, KeyHistory.from_vkeys(vkeys), given the verifier's keys, gives each one a window from 1 with no end. After a rotation, give each key its window:
from audit_trail.ledger import KeyHistory, KeyWindow
HISTORY = KeyHistory(
{
OLD_SIGNER.key_id: KeyWindow(valid_from=1, retired_at=5000),
SIGNER.key_id: KeyWindow(valid_from=5000),
}
)
KeyHistory, KeyWindow, Status, Anchor, Signer, SignatureVerifier and the errors NoteError, BundleError and CanonicalEncodingError are integrity's, re-exported by audit_trail.ledger, so a ledger-only application imports them from there.
The erasure journal¶
journal=True commits the checkpoint to the erasure journal of its size: every ledger.erased receipt up to the checkpoint's size, by entry and receipt, with no value and no salt. It adds the journal line, and prepared.journal and recorded.journal are the journal itself, which the restore kit carries.
A restore brings back the payload that erasures after the backup deleted, and loses their receipts. The journal, trusted through the signed checkpoint, is how record_restore() erases it again. erasure_journal(conn, tables, chain, size) builds the journal of a size again at any time before a restore, if you lost it.
The restore kit¶
Keep the proof with each checkpoint (see prepare_checkpoint). Both prepare_checkpoint() and record_checkpoint() return, as proof, the consistency proof from the newest checkpoint recorded at or below the new one's size to the new one, read from the stored nodes while both sizes are in the database; since_size= starts it from another size. After a restore to a size between the two checkpoints, that proof is what lets record_restore() prove that the restored chain shares its first entries with a checkpoint it no longer reaches (see below). The first checkpoint of a chain has none.
A RestoreKit keeps the three together: the signed note, its journal and the proof steps. recorded.kit, or prepared.kit(signed) when you record elsewhere, builds it; kit.to_json() is a JSON document to store next to your backups, and RestoreKit.from_json(text) reads it back. It holds no payload, no salt and no key, and nothing in it is trusted for being there: record_restore() checks every part again. Keep the kit of every checkpoint, not only the newest: a restore to below where the newest kit's proof starts needs an older kit's proof too.
Recording a restore¶
After the database is restored from a backup, the chain is back at the size the backup held, the restored size. Your newest checkpoint may name a larger size: the entries in between are the lost range, and their erasure receipts are lost with them, so the payload they erased is readable again. Recording the restore is a step of your restore runbook:
- Restore the backup keeping ownership: do not pass
--no-ownertopg_restore. TheSECURITY DEFINERfunctions write as their owner, so they must stay owned by the ledger owner (see ownership). - Check that the grants came back (
--no-privilegesdrops them), or run the grant helpers again as the owner. - Let the application append again if it must. With restore detection on, its first append starts the new incarnation, which
record_restore()then explains. With detection off, or after a restore it cannot see, read The incarnation below first. - Run
record_restore()as the ledger owner, with the newest restore kit, as below. - Review
restored.unproven, and erase again what your log of erasures lists after the newest kit. - Take a new checkpoint with
journal=True, store its kit, and anchor on it from then on.
The operator runs record_restore() as the ledger owner, with the newest checkpoint's restore kit:
with owner_engine.begin() as conn:
restored = ledger.record_restore(
conn,
tables,
"evidence",
kit=newest_kit,
verifier=KEYS,
key_history=HISTORY,
actor="ops",
)
print(restored.restored_size, restored.lost, restored.proven_size)
for erasure in restored.unproven:
logging.error("erased payload is back: seq %s (%s)", erasure.seq, erasure.entry_id)
Without a kit, pass checkpoint_note= and journal= (the journal, or None to erase nothing again), and the steps as proof=.
restored.lost is the lost range as (first, last), both included: the seq numbers above the restored size, up to the checkpoint's size, that the chain held before the restore. It is None when the checkpoint is at or below the restored size, so nothing it covered was lost. The chain goes on from the restored size, so the new incarnation gives those same seq numbers to new entries: name an entry by its entry_id, or by its seq with its incarnation, not by seq alone.
It appends ledger.restored, which holds the checkpoint, the incarnation it explains, the restored size, the lost range, and what was proven, then erases again what the journal says was erased, in the same transaction. Appends may run between the restore and this call.
The incarnation. When restore detection started the current incarnation and nothing explains it yet, the entry explains that one, and the restored size is the seq before it started. Otherwise (detection off, or a restore it cannot see, such as a snapshot rollback) the entry starts a new incarnation itself, and the restored size is the chain's size before it. If entries were appended after such a restore and before this call, pass restored_size= with the size the backup held, so that the lost range is not understated. Without it, once the appends reach the checkpoint's size, the call takes the checkpoint as one the chain holds and refuses it, saying to pass restored_size.
Record the newest kit first. Record one restore once, with the newest kit; when the restore went below where its proof starts, add older kits' steps with proof=, not with another call. A second call with another kit records a second restore: the incarnation holds a ledger.restored already, so the call starts a new incarnation and takes the chain's current size as the restored size. If you must record again, pass restored_size= with the size the backup held, or the lost range is wrong.
What can be erased again: the proven prefix. Erasing again is safe only for an entry known to be the one the journal names: the same entry at the same position of the tree the checkpoint signed. In plain words:
- When the checkpoint's size is at or below the restored size, the restored database still holds the whole of it: its stored tree must have the checkpoint's root, and then every entry up to the checkpoint's size is proven.
- When the checkpoint's size is above the restored size, the hashes needed to link the restored entries to the checkpoint's root were lost with the newer entries. The database alone then proves nothing: it cannot tell a real earlier state of the chain from a forged one. A consistency proof kept from before the restore fills the gap: the kit's own proof, from the checkpoint before it, or a chain of them through older checkpoints, from a size the restored chain still holds up to the checkpoint's size. When the restore went below where the kit's proof starts, also pass an older kit's steps,
proof=older_kit.proof(several kits' steps chained, oldest first): they go before the kit's own. The entries up to the start of that proof, which must be at or below the restored size, are then proven.
When the checkpoint is at or below the restored size, the chain still holds the receipts it covers, so its journal line must commit to their journal, or the call is refused: nothing is erased again there that the chain does not show erased already. When it is above, ledger.restored carries the journal, so that verify() can check each re-applied receipt against it.
Of the journal's erasures, each whose entry is in the proven prefix, still has payload and has no receipt is erased again, with a receipt that carries the original reason code and reapplies, the id of the receipt it re-applies. The chain's current config and precondition are not asked again: the erasure was checked when it was made. A journal erasure inside the proven prefix that names another entry than the one stored there refuses the whole call.
Erasures outside the proven prefix are returned in restored.unproven and left alone: that payload is readable again. Review them and erase them with erase() if you decide to. unproven lists only erasures whose entry the restored database still holds, with payload and without a receipt: entries above the proven prefix and at or below the restored size. An erasure of an entry in the lost range is not listed: the entry is gone, payload and all. With no proof and a checkpoint above the restored size, the proven prefix is empty, so unproven holds every erasure of a restored entry whose receipt was lost: keep the kits.
erase() checks the chain's current config, and the restore lost every ledger.config_changed in the lost range too. When a lost change added the reason code an erasure uses, or changed the precondition, erase() may refuse it under the restored config: run change_config() again first.
It refuses with RestoreRefusedError, changing nothing, when the checkpoint is unsigned, signed outside a key window or of another chain, the journal is not the one its journal line commits to, a proof step does not lead to it, or the checkpoint is not of the chain's history. The same note recorded again in the incarnation it explained returns the entry holding it, with created false.
It runs as the owner. The record-restore function deletes payload, and SQL cannot check the note's signatures, which the Python side does. So only the ledger owner may call it, unless you grant EXECUTE on audit_ledger_record_restore separately; do not grant it to the application role. A role that can call it can record a restore under a checkpoint nobody signed, and erase what its journal names in the proven prefix: verify() given verifier fails such an entry with RESTORE_MISMATCH when its checkpoint is unsigned, and given key_history too when no known key signed it, and each re-applied receipt that is not in the journal the checkpoint commits to with RECEIPT_MISMATCH.
Erasures after the newest kit¶
A kit's journal lists the erasures up to its checkpoint's size. An erasure made after the newest kit is in no journal, and its receipt is lost with the lost range: on any restore its payload comes back, and record_restore() does not report it, not even in unproven. So:
- After erasures, take a checkpoint with
journal=Trueand store its new restore kit off the database. - Keep a log of erasures off the database too: the chain, the
entry_id, the reason code and the time of each, written once its transaction commits. - After a restore, once
record_restore()has run, erase again witherase()each entry in that log erased after the newest kit's checkpoint. It may needchange_config()first, as above.
For the row audit's scrubs, see restores undo erasures.
Verifying¶
Run verify() on a schedule, ideally from another machine, under a role that can read the ledger tables:
from audit_trail.ledger import Status
with engine.connect() as conn:
report = ledger.verify(conn, tables, "evidence", verifier=KEYS, key_history=HISTORY)
if report.status is Status.FAILED:
for failure in report.failures:
logging.error("%s at seq %s: %s", failure.kind, failure.seq, failure.detail)
It reads the state row first and checks the chain up to the size it names, so its head is a head it verified; appends may go on meanwhile. It recomputes every leaf from the stored columns and body bytes, the tree from the leaves, every stored node, and the state row's root and frontier, and checks that seq is gapless from a first ledger.chain_started, that each body is canonical and its query columns copy it, that payload rows match their commitments, that missing payload has a receipt, the package's own entries by type, the config table against the newest config entry, and, with verifier, the signatures of every recorded checkpoint. It takes no lock and reads in short READ ONLY transactions, chunk_rows entries at a time.
The LedgerReport has a status (VALID, VALID_WITH_NOTES or FAILED), the head (chain, incarnation, size, root), and failures and notes, each a LedgerFinding with a kind, a detail sentence, and the seq and entry_id it concerns. A finding never holds a stored value or a salt. The kinds and when each is raised are listed in the spec's findings table.
Without verifier, each recorded checkpoint is an UNCHECKED_SIGNATURES note. With one, a signature of a known key must verify, inside its window. The checkpoint of a ledger.restored entry is what its re-applied erasures are trusted through: given verifier, an unsigned one fails with RESTORE_MISMATCH, since record_restore() never records one; given both verifier and key_history, so does one that no known key signed; verify(require_signatures=True), verify_bundle(require_signatures=True) and --require-signatures fail it too.
Requiring signatures. verify(require_signatures=True) (and averify()) means what it means for verify_bundle(): every checkpoint the run relies on must carry a valid signature of a key verifier knows, inside its window of key_history. An unsigned checkpoint given as checkpoints= fails with BAD_SIGNATURE and is not used, and a ledger.restored entry whose checkpoint no known key signed fails with RESTORE_MISMATCH. A recorded ledger.checkpoint entry is not relied on, since the application role can record unsigned ones: without a signature of a known key it stays an UNCHECKED_SIGNATURES note. It needs verifier, and raises ValueError without one.
Catching up. verify(since=report) takes an earlier report without failures and reads only the entries after its head, after checking that the head is still a head of the stored tree (TRUNCATED or CHAIN_MISMATCH otherwise). It reports only what it finds in the entries it reads: findings about entries before since, such as the ERASED note of an erasure recorded before it or the UNCHECKED_SIGNATURES note of an earlier checkpoint, are not repeated. Keep the full run's report for them. Keep running full verifications on a schedule, and catch up between them:
with engine.connect() as conn:
nightly = ledger.verify(
conn, tables, "evidence", verifier=KEYS, key_history=HISTORY
)
report = ledger.verify(
conn, tables, "evidence", since=nightly, verifier=KEYS, key_history=HISTORY
)
assert report.since == nightly.verified_to
Checking a stored checkpoint¶
Without checkpoints, verify() checks the chain only against itself: a chain rewritten whole, hashes and all, verifies. Only a checkpoint kept off the database shows that the chain the database holds is the one you signed. Give your stored notes as checkpoints=, as integrity's verify() takes them:
from audit_trail.ledger import Anchor, RestoreKit
newest = RestoreKit.from_json(kit_text) # the newest kit, stored off the box
with engine.connect() as conn:
report = ledger.verify(
conn,
tables,
"evidence",
checkpoints=[newest.checkpoint],
verifier=KEYS,
key_history=HISTORY,
)
if report.status is Status.FAILED or report.anchor is not Anchor.ANCHORED:
logging.error("the chain is not the one the checkpoints signed")
- Each checkpoint, a
LedgerCheckpointor its note text, must name this chain and a head of the stored tree in the incarnation its origin names, checked by the stored frontier of its size and a consistency proof from the stored nodes: a chain shorter than one fails withTRUNCATED, another root or incarnation at its size withCHAIN_MISMATCH. - With
verifier, a signed checkpoint must verify (BAD_SIGNATURE,UNKNOWN_KEY), each key inside its window ofkey_history(KEY_NOT_VALID,KEY_COMPROMISED), or it is not used. An unsigned one is taken on your word, you gave it, unlessrequire_signatures=True: then it fails withBAD_SIGNATUREand is not used. report.anchorisANCHOREDwhen one matched, elseUNANCHORED; the entries after the largest one that matched are anUNANCHORED_TAILnote, to be covered by the next checkpoint.- It works with
since=too: the checkpoints are checked against the stored tree, whatever the run reads.
A restore to before a checkpoint fails this for good, as it should: the newest checkpoint from before the restore fails with TRUNCATED while the chain is shorter, and with CHAIN_MISMATCH once the restored chain grows past its size. Record the restore with record_restore(), then anchor on a checkpoint at or below restored.proven_size, or take a new checkpoint after the restore and check against that one from then on. A bundle checks the same with checkpoints= (below).
Bundles¶
export_bundle() writes a range of a chain, or the whole chain, to one zip file that can be checked without the database: for an auditor, a court, or an archive. The format is in the ledger format spec, on top of the bundle format of integrity.
from pathlib import Path
from audit_trail.ledger import EntryRange
result = ledger.export_bundle(
engine,
tables,
"evidence",
"evidence-2026-114.zip",
EntryRange(first=1, last=signed.size),
checkpoints=[signed.to_note()],
key_history=HISTORY,
host_files={"case/request.pdf": Path("request.pdf")},
signer=SIGNER,
)
print(result.first, result.last, result.entries, result.manifest_sha256)
- The scope,
EntryRange(first, last), picks entries byseq; the whole chain, up to the size the state row names, when it is left out orNone. It comes after the destination, as integrity's scope does. The bundle also carries the entries and hashes before the scope that its checks need. - It reads as
verify()does, without a lock, and writes entries as it reads them. It does not verify: runverify()first, or let the reader find what is wrong. checkpoints=are included as given; checkpoints recorded in the chain that can anchor the scope are included as well. Before the scope, that is the newest one, and the newest trusted one when the newest is not: the application role can record unsigned checkpoints, which must not push your signed one out. Passverifier=so that trusted means signatures that verify; with onlykey_history=, a signature line of a key it names is taken on its word.host_files=are your own files underhost/, covered by the manifest.signer=signs the manifest, as in integrity'sexport_bundle().- It takes an
Engineor aConnection; a connection already in a transaction is read in that transaction.aexport_bundle()takes anAsyncEngineor anAsyncConnection. - A bundle holds the payload still stored, personal data among it: keep it as you keep the ledger.
Anchoring host files in the log¶
A host file is anchored by a trusted signature of the manifest, by the manifest's hash kept elsewhere (result.manifest_sha256), or by the log itself: record_bundle_manifest() appends a ledger.bundle_manifest entry holding the digest of the host files, so a later bundle with the same files and that entry in scope anchors them, once a trusted checkpoint covers the entry. Record a checkpoint after it and before the export:
with engine.begin() as conn:
ledger.record_bundle_manifest(
conn, tables, "evidence", {"case/request.pdf": Path("request.pdf")}
)
The log anchors less than a signature does. The application role may record any digest, so a ledger.bundle_manifest entry proves only that a role allowed to append recorded that digest, not that the files are genuine. A signed checkpoint, kept off the database, that covers the entry adds that the entry was in the log by the checkpoint's size and that nobody, the owner included, has changed it since. To show that someone you trust vouched for the files, sign the manifest with signer= too.
Verifying a bundle offline¶
ledger.verify_bundle() checks a bundle without the database, and without SQLAlchemy; audit_trail.integrity.verify_bundle() does the same for either kind of bundle, by its stream type:
report = ledger.verify_bundle(
"evidence-2026-114.zip",
verifier=KEYS,
checkpoints=[signed.to_note()],
key_history=HISTORY,
require_signatures=True,
)
assert report.status is not Status.FAILED
assert report.anchor is Anchor.ANCHORED
Everything in scope gets the same findings as from verify(), except what needs the stored rows (columns, nodes, state and config). Trust comes only from the arguments: the keys and the checkpoints you give, never the key ids a bundle brings. The report is ANCHORED when a trusted checkpoint matches a head of the bundle's entries; entries after the newest one that matched are noted UNANCHORED_TAIL, and host files under a manifest nothing anchors UNANCHORED. A bundle that cannot be read as one raises BundleError.
verifier is a required keyword of verify_bundle(): leaving it out raises TypeError. The database verify() takes it as optional, and raises ValueError when require_signatures=True or key_history= comes without it.
The same check from the command line, with only this package and cryptography (the [integrity] extra) installed:
python -m audit_trail.integrity verify-bundle evidence-2026-114.zip \
--keys trusted.keys --checkpoint evidence-head.note \
--key-history key-history.json --require-signatures --require-anchor
Write the input files from what you already hold. --keys is required: a file of verifier keys, one per line. --key-history takes the JSON that KeyHistory.to_json() writes and KeyHistory.from_json() reads, and --checkpoint a note:
from pathlib import Path
Path("trusted.keys").write_text(SIGNER.vkey + "\n")
Path("key-history.json").write_text(HISTORY.to_json())
Path("evidence-head.note").write_text(signed.to_note())
For a ledger bundle, the positions in the key history (valid_from, retired_at, compromised_from) are the chain's seq numbers, as in key history.
The flags are integrity's: --keys, --checkpoint (a ledger checkpoint note, once per checkpoint), --key-history, --manifest-sha256, --require-signatures, --require-anchor and --json. --retention, --transaction-retention and --system-severity do not apply to a ledger bundle and exit with 2. It exits with 0 when the bundle verified, 1 when it did not, and 2 when it could not be checked. An auditor should pass --require-anchor and --require-signatures: without them, 0 means only that the bundle is consistent with itself.
Operations¶
Standbys and failover¶
A standby cannot append, create a chain or record anything: its transactions are read-only. The calls that only read (verify(), the proofs, erasure_journal(), export_bundle(), prepare_checkpoint()) run in READ ONLY transactions, so they can run on a hot standby, which may lag behind the primary.
A promoted standby appends again, in a new incarnation (new_timeline). After a planned switchover, record it with record_maintenance(). After a failover that may have lost the newest entries, treat it as a restore: record it with record_restore() and your newest checkpoint, which then shows what was lost.
PgBouncer¶
Every ledger call works behind transaction pooling: the chain's lock is a row lock held until the transaction ends, lock_timeout= is set for the transaction only, and nothing is held across transactions. The drivers' prepared statements need the settings in integrity's PgBouncer section.
Sizing¶
- Appends to one chain are serialized: each holds the chain's lock from its append to its commit, so a chain's throughput is bound by how long writers hold it. Append last, or use
add(), which appends at the commit. Oneappend_many()call is one statement for any number of entries, and restore detection runs once per call, not per entry. - A chain's ceiling: on a laptop with a local PostgreSQL 18, one
append_many()of 5,000 entries took about 1.3 s, some 3,900 entries a second (3,300 with one payload group per entry), Python's encoding included. That is the most one chain takes, however many writers wait on its lock. For more, spread the load over several chains, by tenant or by source say: chains append in parallel, and each is verified and checkpointed on its own. - Storage: per entry, one entry row (the body, its query columns and the leaf hash), one payload row per group, and on average one 32-byte node: a tree of
nentries stores fewer thannnodes. Nothing is ever deleted but erased payload. - Proofs read O(log n) stored hashes in one statement.
verify()readschunk_rowsentries (2000 by default) perREAD ONLYtransaction. Its memory grows with the number of erasures, not with the chain. Each recorded checkpoint costs one consistency proof from the stored nodes.verify_bundle()keeps every node the entries in scope close, about 64 bytes per entry.
Permission errors¶
A ledger call denied a privilege raises LedgerPermissionError, whose message is the server's followed by the row of this table that matches it. It is both a PermissionError and a SQLAlchemy ProgrammingError, so a handler of ProgrammingError or DBAPIError still catches it; it keeps the driver error's statement, params and orig, and that error is its __cause__. Roll the transaction back, fix the grant and run the call again.
| Error | Who may do it | Fix |
|---|---|---|
permission denied for function audit_ledger_append, audit_ledger_record_checkpoint or audit_ledger_record_bundle_manifest |
the application role | run ledger_grant_statements() for the role, as the owner |
permission denied for function audit_ledger_erase |
the eraser role, or the application with erase=True |
run ledger_eraser_grant_statements(), or ledger_grant_statements(..., erase=True) |
permission denied for function audit_ledger_create_chain, audit_ledger_change_config, audit_ledger_record_maintenance, audit_ledger_record_restore or audit_ledger_confirm_upgrade |
the owner only | run the call as the ledger owner |
permission denied for function audit_ledger_append_entries, audit_ledger_detect_restore or audit_ledger_cluster_identity |
only the other ledger functions | call the package, not the function |
permission denied for schema audit |
every role that uses the ledger | run the grant helper for the role: each grants USAGE |
permission denied for table audit_ledger_... on a read |
the application and reader roles; the eraser reads audit_ledger_entry only |
run ledger_grant_statements() or ledger_reader_grant_statements(); an eraser reads the other tables only through a reader role |
permission denied for table audit_ledger_... on a write |
the owner only | write through the package's calls |
permission denied for database ... from create_ledger_tables() |
the owner, with CREATE on the database |
GRANT CREATE ON DATABASE ... to the owner |
Limitations¶
The limitations page sums these up with the rest of the package's.
What the ledger cannot detect, or does not prevent:
- The application role can add entries, not alter them. It may append any entry of its own types, with any
actor,declared_atand attributes: the ledger proves what was written and when it was appended, not that it is true. It cannot change, reorder or delete an entry, write a package entry, or erase without the erase privilege. - Signatures are not checked in SQL. The application role may call the record-checkpoint function directly, with a note whose signatures are forged or of no known key: the function checks the head against the tree, and the note's form as the reader reads it (origin, journal line, extension lines, signature lines), so that no note it records stops later checkpoints, but not the signatures, which
record_checkpoint()does in Python.verify()with averifierfails such a checkpoint withBAD_SIGNATURE, or notesUNCHECKED_SIGNATURESwhen no known key signed it. A recorded checkpoint is never an anchor by itself. The same holds for the bundle-manifest function: any digest the application records is in the log, anchoring only what it registered. - The owner and superusers can rewrite the chain. They can change the tables directly and recompute every hash.
verify()alone then finds nothing: only a checkpoint stored off the database shows it, for the history the checkpoint covers. Everything after the newest checkpoint can be rewritten undetected. - Restores the database cannot see. Restore detection compares the cluster identity, so it misses a rollback of a VM or file-system snapshot, a file-level copy started without archive recovery, and a data-only restore into the existing tables; and a restore followed by
pg_upgradebefore the next append shows only asledger.cluster_changed. After any of these, compare the chain with your newest checkpoint and record the restore withrecord_restore(). - A cluster change is taken for
pg_upgrade. A data-only restore of an older dump into a fresh cluster of a higher major version gives the state table its old OID, so it shows asledger.cluster_changed, not a new incarnation, and the entries written after the dump are lost without a failure.verify()notes itUNCONFIRMED_UPGRADEuntil you check the chain against a checkpoint taken before the upgrade and runconfirm_upgrade()(see major upgrades). - Erasures across a restore need a proof. Without a restore kit, or a consistency proof, kept from before the restore, a checkpoint above the restored size proves nothing:
record_restore()erases nothing again, and reports inunproventhe erasures of entries the database still holds. - Erased payload lives on elsewhere. Erasing deletes the rows in the ledger, not copies in backups, bundles already exported, logs or replicas that have not caught up. A restore brings it back until
record_restore()runs, and, for erasures made after the newest restore kit, until you erase them again. - A checkpoint's window, not its time. A key history limits which positions a key may attest, not when it signed: whoever holds a retired key can still sign an earlier head inside its window.