Ledger tables
A ledger table is a table whose rows cannot be changed, and cannot be deleted until a retention period you set has passed. Every committed row is recorded in a hash chain, and the chain's head can be copied to places the database host cannot rewrite, so an edited, removed or rolled-back row is found by one statement. Use one for payments, audit trails, consents, medical or financial records: anything you may have to prove was not altered.
Ledger tables are part of the enterprise server (rasterizeddb-enterprise). They work without an enterprise configuration file; the file and a few environment variables only choose where the chain and its anchors are kept. See Installing.
Create a ledger table
CREATE LEDGER TABLE takes a column list like CREATE TABLE, followed by the ledger clauses. The retention clause is required:
CREATE LEDGER TABLE payments (
id BIGINT NOT NULL,
payer TEXT NOT NULL,
amount BIGINT NOT NULL
)
NO DELETE UNTIL 7 YEARS AFTER INSERT
NO DROP UNTIL 90 DAYS IDLE
ANCHOR TO 'dir:/mnt/worm/ledger';CREATE LEDGER TABLE IF NOT EXISTS name (…) … is accepted too. Write rows with ordinary INSERT statements, from any protocol:
INSERT INTO payments (id, payer, amount) VALUES (1, 'acme', 1250);
SELECT id, payer, amount FROM payments ORDER BY id;The clauses
| Clause | Required | What it does |
|---|---|---|
NO DELETE UNTIL <n> <unit> AFTER INSERT | Yes | A row may be deleted only once this long has passed since it was inserted. 0 SECONDS allows deleting at once (the table is still append-only and chained). |
NO DROP UNTIL <n> <unit> IDLE | No | DROP TABLE is refused until no row has been inserted for this long. Without it, the table can be dropped once its newest row is past its retention. |
VERSIONED | No | Rows may be updated. Every version is kept on disk and chained. See Versioned ledger tables. Fixed at creation. |
ANCHOR TO '<sink>' [, '<sink>' …] | No | Where this table's chain heads are copied: dir:<path> or s3://<bucket>/<prefix>. See Anchors. |
HASHING USING 'sha256' | No | The hash the chain uses. SHA-256 is the only one, and the default. |
Units are SECOND, MINUTE, HOUR, DAY, WEEK, MONTH and YEAR, singular or plural, in any letter case. They are counted long, so a retention never ends early: a MONTH is 31 days and a YEAR is 366 days.
A clause the server does not know is refused (SQLSTATE 42601), and so is a CREATE LEDGER TABLE with no NO DELETE UNTIL clause.
The hidden insert time
Every ledger table gets one more column after yours: __ledger_ts BIGINT, the row's trusted insert time in microseconds since 1970. The server stamps it on every insert, whatever the statement gave for it, so a client cannot backdate a row to delete it early. No two rows share a stamp, so it also names the row: the verification report, the history and the receipt statements identify a row by it.
SELECT id, __ledger_ts FROM payments WHERE id = 1;Name your columns in INSERT; the server fills __ledger_ts itself.
What each statement does on a ledger table
The rules hold for every role. A superuser is not exempt.
| Statement | On a ledger table |
|---|---|
INSERT, COPY … FROM | Allowed. The row is stamped and, when its transaction commits, chained. |
INSERT … ON CONFLICT | Refused (0A000). |
UPDATE | Refused on an append-only table (0A000, "it is append-only"). Allowed on a VERSIONED table, except on __ledger_ts. |
DELETE | Each selected row is checked first. If any one of them is inside its retention, or the table is under a legal hold, the whole statement is refused (55000) and nothing is deleted. Rows past their retention are deleted, and the deletion is chained. |
TRUNCATE | Refused (0A000), also when reached by CASCADE. |
DROP TABLE | Refused (55000) while the table is under a legal hold, while its newest row is inside its retention, or before its NO DROP UNTIL … IDLE time has passed since the last insert. |
ALTER TABLE … ADD COLUMN | Allowed only for a nullable column with no default and no generated value. Existing rows still verify. |
Any other ALTER TABLE | Refused (0A000): dropping, renaming or retyping a column, constraints, defaults, renaming the table, converting it to a partitioned table. |
VACUUM, automatic compaction | Allowed on an append-only table (they keep every visible row). Refused on a VERSIONED table, whose old versions are its history. |
MOVE TABLE | Allowed. |
DROP DATABASE | Refused (55000) while any ledger table in it would refuse DROP TABLE. |
RESET BRANCH, PROMOTE BRANCH | Refused when the database they would replace (the branch for a reset, its parent for a promotion) holds a ledger table or a vault. See Branching. |
Writes are refused with a message that names the table and the rule, for example:
ERROR: "payments" is a ledger table: UPDATE is not allowed on it; it is append-only
ERROR: a row of "payments" is still within its retention (221356800 s after insert)Retention and legal holds
Change a ledger table's policy with ALTER LEDGER TABLE. Only the table's owner or a superuser may run it. Each change is itself added to the chain, with the role that made it.
-- A retention or drop-idle time is only ever raised.
ALTER LEDGER TABLE payments SET RETENTION 10 YEARS;
ALTER LEDGER TABLE payments SET NO DROP UNTIL 1 YEAR IDLE;
-- A legal hold stops every delete and the drop, even of rows past their retention.
ALTER LEDGER TABLE payments SET LEGAL HOLD 'case-4411';
ALTER LEDGER TABLE payments RELEASE LEGAL HOLD 'case-4411';
-- Another anchor for this table's chain.
ALTER LEDGER TABLE payments ADD ANCHOR 's3://audit-anchors/payments';Each answers with one line, for example:
payments: legal hold case-4411 placed by adminSET RETENTIONandSET NO DROP UNTIL … IDLErefuse a shorter time than the current one (55000).- A hold name is quoted and has no spaces. A table can carry several holds; each is released by name. Releasing a hold the table does not have is refused (42704).
- The policy is kept beside the table's schema as records that are only ever appended. A record that would loosen it (a shorter retention, a different kind of table) means the file was edited by something other than the server, and the table then refuses to open.
Versioned ledger tables
A VERSIONED ledger table takes UPDATE. Each update adds a new version of the row and chains it; the old versions stay on disk for good.
CREATE LEDGER TABLE accounts (id BIGINT NOT NULL, balance BIGINT NOT NULL)
VERSIONED
NO DELETE UNTIL 7 YEARS AFTER INSERT;
INSERT INTO accounts (id, balance) VALUES (1, 10);
UPDATE accounts SET balance = 20 WHERE id = 1;
UPDATE accounts SET balance = 30 WHERE id = 1;SHOW LEDGER HISTORY <table> <row stamp> lists every version of one row, oldest first, each marked chained when the chain holds its digest or UNCHAINED when it does not:
SELECT __ledger_ts FROM accounts WHERE id = 1;
SHOW LEDGER HISTORY accounts 1795701600000123;v1 chained xmin 12 xmax 13 id=1 balance=10
v2 chained xmin 13 xmax 14 id=1 balance=20
v3 chained xmin 14 id=1 balance=30__ledger_ts is the row's identity and is never assigned: UPDATE accounts SET __ledger_ts = … is refused. Vacuum and compaction are refused on the table, so its files only grow.
The hash chain
Each database has one chain. Every transaction that commits rows into any of its ledger tables (or vaults) appends one entry to it, listing a SHA-256 digest of each row it inserted or updated and the stamp of each row it deleted. Each entry's hash covers the entry before it, so editing, removing or reordering any entry breaks every hash after it. Policy changes, acknowledged rollbacks and vault audit events are entries too.
The entry is written and synced to disk before its transaction commits, so a commit never outlives its entry. A transaction that rolls back adds nothing.
Where the chain lives
The chain of a database is a file named chain.log:
- With a ledger directory set:
<ledger directory>/<name>/chain.log, where<name>is the database's directory path with every character other than a letter, a digit,-or_replaced by_, and leading and trailing_removed. For--location /var/lib/rasterizeddband a ledger directory/mnt/ledger, that is/mnt/ledger/var_lib_rasterizeddb/chain.log. - Without one:
<database directory>/rdb_ledger/chain.log.
The database's directory is the --location path as you gave it for the default database, and <location>/<database name> for every other database. Give --location as an absolute path, and keep it the same across restarts: the chain is found by it.
Put the chain on another disk than the data, so one failure or one intruder cannot take both. Set the ledger directory in the enterprise configuration file or the environment:
# /etc/rasterizeddb/enterprise.conf
ledger_dir /mnt/ledgerexport RDB_LEDGER_DIR=/mnt/ledgerThe configuration file's ledger_dir wins over RDB_LEDGER_DIR. When the chain is on the same device as its data, the server logs a warning at start and SHOW LEDGER prints WARNING: the chain is on the same device as the data.
The same directory also holds the database's vault keyrings, the vault audit log and the encrypted-column keys (see Secret vaults and keys). Back it up.
When the server opens a database, it reads the chain again and checks every link. A last entry cut short by a crash is dropped (its commit never happened). Any other damage stops ledger writes:
ERROR: the ledger chain /mnt/ledger/var_lib_rasterizeddb/chain.log is broken at entry 7: entry 7's hash does not follow from the one before it; ledger writes stop until it is examinedAnchors
The chain alone proves that no entry was edited by itself. It cannot prove that someone did not rewrite the data, the chain and every hash together. An anchor is a copy of "entry N had hash H at time T" kept where the database host cannot change it; once it exists, the chain can no longer be recomputed or cut back unnoticed.
| Sink | What it writes |
|---|---|
dir:<path> | One file per anchor, <path>/<name>/anchor-<entry number>-<hash prefix>, written once and synced, never overwritten. <name> is built from the database's path as for the chain. Put it on another disk, or a mount this host can only add files to. |
s3://<bucket>/<prefix> | One object per anchor under <prefix>/<name>/, written with S3 Object Lock in COMPLIANCE mode, which not even the bucket's owner can delete before its retain-until date. The bucket must have Object Lock enabled. |
Sinks come from three places, and every one applies:
- the table's
ANCHOR TOclause andALTER LEDGER TABLE … ADD ANCHOR(this database's chain); ledger_anchor <sink>lines in the enterprise configuration file, one sink per line (every database's chain);- the
RDB_LEDGER_ANCHORSenvironment variable, comma-separated (every database's chain).
# /etc/rasterizeddb/enterprise.conf
ledger_dir /mnt/ledger
ledger_anchor dir:/mnt/worm/ledger
ledger_anchor s3://audit-anchors/rasterizeddbBy default a background thread anchors each chain's newest head about once a second, and a commit does not wait for it. If the head stays unanchored too long (an S3 outage, a full disk), ledger writes stop:
ERROR: the ledger head (entry 412) has not been anchored for 61 s: s3://audit-anchors/rasterizeddb: …; ledger writes stop until an anchor succeedsAnchor settings
These are environment variables of the server process.
| Variable | Default | What it does |
|---|---|---|
RDB_LEDGER_ANCHORS | unset | Sinks every chain is anchored to, comma-separated. |
RDB_LEDGER_ANCHOR_MODE | async | sync anchors every commit's head before the commit returns. |
RDB_LEDGER_MAX_UNANCHORED_SECS | 60 | How long the newest head may stay unanchored before the failure policy applies. |
RDB_LEDGER_ON_ANCHOR_FAILURE | refuse | continue keeps accepting ledger writes past that window, logging an error on each commit. Any other value, or none, refuses them (55000). |
RDB_LEDGER_ANCHOR_LOCK_DAYS | 3660 | How many days an S3 anchor object is locked. |
RDB_LEDGER_S3_ENDPOINT | AWS | The S3 endpoint, https://host[:port]. Falls back to AWS_ENDPOINT_URL, then to https://s3.<region>.amazonaws.com. A non-AWS endpoint is addressed path-style. |
AWS_REGION, AWS_DEFAULT_REGION | us-east-1 | The S3 region. |
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN | none | Credentials for S3 sinks. Without the first two, every S3 anchor fails. |
RDB_LEDGER_SIGNING_KEY | unset | A file holding a signing seed; every anchor is then signed. See Signed anchors. |
For a service, set them in its unit (Environment= lines) or environment file.
Signed anchors
With RDB_LEDGER_SIGNING_KEY set to a file holding 64 hexadecimal characters, every anchor carries an ML-DSA-65 (FIPS 204) signature, which proves which database wrote it. On Linux and macOS the file must be readable by its owner only; otherwise the server logs an error and anchors go unsigned.
openssl rand -hex 32 > /etc/rasterizeddb/ledger-signing.key
chmod 600 /etc/rasterizeddb/ledger-signing.key
export RDB_LEDGER_SIGNING_KEY=/etc/rasterizeddb/ledger-signing.keySHOW LEDGER then prints the public verify key on its anchors line (signed ML-DSA-65 (verify key …)). Give that key to whoever checks the anchors: see Verifying a ledger.
Trusted time
Retention is measured with the server's trusted clock, not the raw wall clock:
- It never goes backwards. Each stamp is later than the last one, and the chain's newest time is read back when a database opens, so setting the clock back cannot backdate a row.
- Once an S3 anchor has been written, the S3 response's
Datebecomes a witness: "now" is then at most that time plus the time elapsed since, so setting the clock forward releases nothing.
Without an S3 sink there is no witness, and a retention is only as trustworthy as the host's clock.
Look at a ledger
SHOW LEDGER (or SHOW LEDGERS) describes the chain, its anchors and every ledger table and vault of the database; SHOW LEDGER <table> describes one table:
SHOW LEDGER payments;chain: 412 entries, head 9f2c4b0e…d71a, at /mnt/ledger/var_lib_rasterizeddb/chain.log
anchors: dir:/mnt/worm/ledger (async), unanchored: none
payments: ledger id 3b6f…a904, retention 221356800 s, drop after 7776000 s idle, hash sha256, anchors dir:/mnt/worm/ledger, holds case-4411The anchors line says anchors: none when no sink is set, and is followed by last anchor error: … after a failed anchor. Encrypted columns are listed too (see Encrypted columns).
To check that the rows match the chain, run VERIFY LEDGER: see Verifying a ledger.
Row receipts
SHOW LEDGER RECEIPT <table> <row stamp> returns the proof that one inserted row is in the chain, up to the newest head every sink has anchored:
receipt rdb-v1
row <ledger id> <stamp> <row digest>
entry <n> <previous hash> <entry payload>
after <payload digest>
head <n> <hash> anchoredThere is one after line per later entry, and the last line ends unanchored when the head it reaches is not anchored yet. Give a receipt to a third party with the anchor it ends at, and they can check the row was recorded without trusting the server. The enterprise Rust client crate (rasterizeddb_client_enterprise, in the repository and not on crates.io) checks one with verify_receipt.
Privileges
| Statement | Who may run it |
|---|---|
CREATE LEDGER TABLE | Whoever may create a table. |
INSERT, DELETE, SELECT | The table's ordinary privileges, then the ledger rules above. |
ALTER LEDGER TABLE | The table's owner or a superuser. |
ACKNOWLEDGE LEDGER ROLLBACK | A superuser. |
VERIFY LEDGER, SHOW LEDGER | Any role: no privilege is checked. |
Replication, backups and branches
- Replication. A ledger table replicates as what it is: the replication log carries the
CREATE LEDGER TABLEstatement as written, so a replica creates a ledger table under the same rules, not an ordinary table. Run replicas on the enterprise server: a server without the ledger features does not open a ledger table. See Replication. - Backups. A snapshot copies the database's directory. The chain is in the backup only when it lives there (no ledger directory set). With a ledger directory on another disk, back that directory up yourself. After restoring an older copy, the anchors written since point past the restored chain and
VERIFY LEDGERreports them asTAMPERED; record the restore withACKNOWLEDGE LEDGER ROLLBACK(see Verifying a ledger). See Backup and restore. - Branches.
RESET BRANCHis refused while the branch holds a ledger table or a vault, andPROMOTE BRANCHwhile its parent does: either would replace those tables with other copies. - A server without the enterprise features refuses to open a data directory that holds a ledger table, and refuses every statement on one. Once you create a ledger table, the directory is served by the enterprise server only.
In an embedded application
An application using the embedded engine gets ledger tables by depending on the rasterizeddb_enterprise crate and calling rasterizeddb_enterprise::install_always() before Builder::start. The ledger settings above are read from the process environment. rasterizeddb_enterprise is not published on crates.io: take it and rasterizeddb_embedded from the same checkout of the repository (for example the v1.1.0 tag), so both use one copy of the engine. See the embedded engine.
Limits
- A ledger table cannot be partitioned:
CREATE LEDGER TABLEtakes noPARTITION BY, andALTER TABLE … PARTITION BYis refused. Ledger statements on a partitioned table are refused. - Without any anchor sink, the chain proves that entries were not edited one by one, not that the whole chain was not rewritten.
VERIFY LEDGERsays so with aWARNINGline. - Without an S3 anchor, retention depends on the host clock not being moved forward.
VERIFY LEDGERreads every row of the tables it checks into memory.- A
VERSIONEDtable is never vacuumed; its files grow with every update. INSERT … ON CONFLICTis refused, andALTER TABLEtakes only a nullableADD COLUMNwithout a default.- The ledger settings are read once, when the server starts: changing an environment variable or the configuration file needs a restart.