Skip to content

Canonical encoding and hashes

This page specifies, byte for byte, the canonical JSON encoding of the tamper evidence feature and the hashes built on it: commitments, Merkle leaves, segment roots, block hashes and the commitment of an erasure journal. With it and the test vectors, an implementation in another language can recompute every hash the package writes.

It describes format version 1, the one every release with integrity has written, and the erasure journal's two versions. It does not cover checkpoints (signed notes) or the verification algorithm.

Conventions

The key words MUST, MUST NOT, SHOULD and MAY are to be read as in RFC 2119 and RFC 8174 when, and only when, they appear in capitals.

  • SHA-256(x) is the 32-byte SHA-256 digest of the bytes x.
  • || is byte concatenation.
  • 0x00 and 0x01 are single bytes.
  • A quoted string such as "sqlalchemy-audit-trail/leaf/v1" stands for its ASCII bytes, without a terminator.
  • canonical(v) is the encoding of the JSON value v that the next section defines.
  • base64 is standard base64 (RFC 4648, section 4) with = padding.

Canonical JSON encoding

The encoding is close to JCS (RFC 8785) but is not JCS: numbers are written differently. Its output is UTF-8 text with no whitespace outside strings.

The writer encodes the values it is about to store, and the verifier encodes the values it reads back from PostgreSQL jsonb. Both MUST give the same bytes. The rules below make that hold for every value jsonb can hold: jsonb stores numbers as exact decimals, drops the sign of zero, and rejects \u0000 and lone surrogates.

Values

A value is one of:

  • null, true or false;
  • a number: a finite, exact decimal value;
  • a string: a sequence of Unicode scalar values;
  • an array: an ordered sequence of values;
  • an object: a set of members, each a string key and a value, with no two keys equal.

There are no other values. An encoder MUST refuse a value of any other kind, NaN or an infinity.

A number has no type beyond its value. 1, 1.0, 1.00, 1e0 and 100e-2 are the same number, and MUST encode the same.

A reader of stored JSON MUST parse every number as an exact decimal. It MUST NOT round a number through an IEEE 754 binary64 double or a 64-bit integer. Audit data holds integers beyond 253 (xid values, bigint ids, application data), and jsonb keeps every digit of a decimal.

The reference reader does this: the sealer and the verifier read every jsonb column as PostgreSQL's text of it and parse that with loads_exact, which reads a number with a fraction or an exponent as an exact decimal, and an integer as an exact integer without the host's digit limit. They do not use the database driver's JSON parser. A number the reference writer stores (a double as its shortest round-trip text, an integer exactly) reads back as the same value either way; an exact reading matters for numbers that another writer stored.

A writer that holds an IEEE 754 binary64 double MUST use the decimal value of its shortest round-trip text: the shortest decimal that reads back as the same double, and of those the closest to the double's exact value. This is what Python's repr(float) gives, and what Python's json module writes into jsonb. For example, the double nearest 12345678901234567890 has the exact value 12345678901234567168, and encodes as 12345678901234567000.

Literals

null, true and false encode as the ASCII bytes null, true and false.

Numbers

A number MUST be written as plain decimal text:

  1. If the number is zero, its text is 0. A negative zero is zero.
  2. Otherwise, a - if the number is negative; then the integer part in decimal digits, without leading zeros, or 0 if the integer part is zero; then, if the fraction part is not zero, a . and the fraction digits, without trailing zeros.

The text never has an exponent, a + sign, a leading zero before another integer digit, a trailing . or a trailing fraction zero.

Value Text
-0, -0.0, 0e5, 0.000e-10 0
2.50 2.5
100.0, 1e2 100
1e16, 1E+16 10000000000000000
1e-7 0.0000001
-1.25 -1.25
9007199254740993 9007199254740993
0.1234567890123456789012345678901234567890 0.123456789012345678901234567890123456789

The encoder MUST NOT round. Every significant digit of the value is written, however many there are, up to the limit below.

Strings

A string MUST be written as ", then each of its characters as below, then ".

Character Written as
" (U+0022) \"
\ (U+005C) \\
U+0008 \b
U+000C \f
U+000A \n
U+000D \r
U+0009 \t
Any other character from U+0001 to U+001F \u00 and two lowercase hex digits, such as \u001f
U+0000 refused
Anything else its UTF-8 bytes

"Anything else" includes /, U+007F, U+2028, U+2029 and every character outside the Basic Multilingual Plane: they are written as raw UTF-8, never escaped. A string MUST NOT hold U+0000 or a lone surrogate; an encoder MUST refuse it. Strings are not normalized: é (U+00E9) and e followed by U+0301 are different strings.

These are the escapes of Python's json.dumps(s, ensure_ascii=False).

Arrays

An array MUST be written as [, its elements in order separated by ,, then ]. An empty array is [].

Objects

An object MUST be written as {, its members separated by ,, then }. A member is its key encoded as a string, :, and its value. An empty object is {}.

Members MUST be sorted by their keys, compared as sequences of UTF-16 code units: the first unequal code unit decides, as an unsigned 16-bit number, and a key that is a prefix of another sorts first. This is the order of JCS. It differs from code point order for keys with characters above U+FFFF: 😀 (U+1F600, code units D83D DE00) sorts before U+E000.

A key MUST NOT hold U+0000 or a lone surrogate. Keys are unique: jsonb keeps only the last of two equal keys, and the encoder's input, a mapping, cannot hold two.

Limits

Both limits are fixed numbers of the format. An encoder MUST accept every value within them and MUST refuse every value beyond them, whatever its platform, settings or call stack.

  • Digits. A number whose text has more than 4300 digits MUST be refused, and a number of at most 4300 digits MUST encode. Digits are the characters 0 to 9 of the text as written above; the sign and the . do not count, and the 0 before the . of a number below 1 does. So 1e4299 and 1e-4299 encode, 1e4300 and 1e-4300 are refused, and 1. followed by 5000 zeros encodes as 1. The limit does not follow any runtime setting: in Python, the encoder MUST NOT depend on sys.set_int_max_str_digits(), which a host may lower to 640.
  • Depth. The top-level value is at depth 1. The elements of an array and the member values of an object at depth d are at depth d + 1. An array or object at a depth greater than 256 MUST be refused, even an empty one, and every value whose arrays and objects are all at depth 256 or less MUST encode. Other values are never refused for their depth: a number inside 256 nested arrays is at depth 257 and encodes. Put another way, at most 256 brackets and braces may be open at once. Keys do not count as levels. So [[]] has depth 2, 256 nested arrays encode, and 257 are refused.

The reference encoder raises CanonicalEncodingError for both. It does not recurse, so its depth limit is the same however deep the caller's stack is.

The limits bind the encoder. A reader of stored JSON MUST read every number of up to 4300 digits exactly, whatever its settings, so that the encoder, not the reader, decides what has an encoding. A reader MAY refuse a value nested too deeply for it to parse; for anything a writer stored, that is far beyond 256 levels.

Refusals

A value that has no encoding has no commitment and no leaf. The writer refuses to write it. A verifier that cannot encode a value it read treats the hash as not matching.

Domain tags

Every hash input starts with, or contains, a domain tag of the form "sqlalchemy-audit-trail/<name>/v<n>":

Tag Used in
sqlalchemy-audit-trail/commit/v1 Commitments
sqlalchemy-audit-trail/leaf/v1 Leaf hashes
sqlalchemy-audit-trail/block/v1 Block hashes
sqlalchemy-audit-trail/retire/v1 The retire digest
sqlalchemy-audit-trail/erasure-journal/v1 Erasure journal, version 1
sqlalchemy-audit-trail/erasure-journal/v2 Erasure journal, version 2
sqlalchemy-audit-trail/ledger-entry/v1 Ledger leaf input
sqlalchemy-audit-trail/ledger-journal/v1 Ledger erasure journal and the journal line of a ledger checkpoint
sqlalchemy-audit-trail/ledger-host-files/v1 Host-files digest of a ledger bundle

A change to the canonical encoding or to any preimage below MUST get a new tag, never a change to the bytes an existing tag gives.

Commitments

Each part of a row that a scrub may erase is a group, with a salted commitment to its value.

Group Table Value
label audit_activity the object_label column
changes audit_activity data.changes
payload audit_activity data.payload
state audit_activity data.state
actor audit_activity an object of the keys actor_label, remote_addr, user_agent and meta of data.context
actor audit_transaction an object of the columns actor_label, remote_addr, user_agent and meta

The groups of an audit_activity row are, in order, label, changes, payload, state and actor; those of an audit_transaction row are actor. state is the row a model with record_state stores; a row without data.state has no state group, and its commitments are what they were before the group existed. An entity.deleted or entity.updated entry whose row was gone when its state was to be loaded has no data.state but data.state_missing (the string "row_gone"): that key is not a group, and the leaf keeps it like any other key of data. A writer MUST NOT store data.state as null, and a scrub never leaves it null; a verifier MUST fail a sealed row whose data has the key state with the value null (COMMITMENT_MISMATCH for the state group), since no commitment covers it.

A group is present when its value is not null. An actor object holds only the fields whose value is not null, and the actor group is present when it holds at least one. If data.context is missing or not an object, the activity actor group is not present.

In the actor group of an audit_transaction row, remote_addr is the text PostgreSQL's inet output gives for the stored address. In the actor group of an audit_activity row, remote_addr is the string stored in data.context, as it is.

For each present group, the writer draws a fresh random 16-byte salt and computes:

commitment = SHA-256("sqlalchemy-audit-trail/commit/v1" || 0x00
                     || u8(len(group)) || group
                     || salt
                     || canonical(value))
  • group is the group name in UTF-8. It MUST be at most 255 bytes.
  • u8(len(group)) is one byte, the length of group in bytes.
  • salt MUST be exactly 16 bytes.

The row stores {group: base64(commitment)} in seal_commitments and {group: base64(salt)} in seal_salts, for the present groups only. A row with no present group stores {} in both. A row written without integrity has SQL NULL in both.

A scrub deletes the salt of each group it erases and stamps the group in seal_erased. The commitment never changes.

Leaf hash

Each sealed row is a leaf. Its leaf row is an object of the row's columns that never change after insert:

Table Columns
audit_transaction id, issued_at, actor_type, actor_id, method, path, channel, auth_method, request_id, correlation_id, xid, seal_commitments
audit_activity id, transaction_id, verb, severity, object_type, object_id, target_type, target_id, actor_id, scope_id, correlation_id, created_at, data, xid, seal_commitments

Every listed column MUST be present, with null for SQL NULL. No other column is included: the leaf leaves out the erasable groups (object_label and the actor columns), seal_salts and seal_erased, which a scrub changes. The commitments in seal_commitments cover the erasable groups instead.

Column values are converted to JSON values:

  • A timestamp (issued_at, created_at) MUST be written as UTC text with six fraction digits and Z: YYYY-MM-DDTHH:MM:SS.ffffffZ. For example, 2026-11-26 13:05:09.123456+01 is "2026-11-26T12:05:09.123456Z".
  • A UUID (request_id, correlation_id) MUST be written as its lowercase, hyphenated 36-character text.
  • An integer (id, transaction_id, severity, xid) is a number.
  • seal_commitments and every jsonb value are their JSON values.
  • Every other column is a string.

Of data, the leaf keeps every key except changes, payload and state. If data.context is an object, the leaf keeps it without its actor_label, remote_addr, user_agent and meta keys, even when nothing is left in it.

leaf = SHA-256(0x00 || "sqlalchemy-audit-trail/leaf/v1" || canonical(leaf row))

The 0x00 comes first, as the leaf prefix of RFC 6962, and the tag follows it.

Segment roots

A seal block covers every audit row whose xid is in [xid_from, xid_to). Its rows are split into segments, one per stream and partition that has rows in the range.

  • The stream of an audit_transaction row is transaction. The stream of an audit_activity row is activity.<severity>, with the severity as a decimal integer, such as activity.10.
  • The partition is the name of the monthly partition that holds the row, without a schema.

A segment's root is the Merkle Tree Hash of RFC 6962, section 2.1, over the leaf hashes of its rows in (xid, id) order, ascending:

  • The hash of no leaves is SHA-256("").
  • The hash of one leaf is the leaf hash itself.
  • For n > 1 leaves, let k be the largest power of two less than n. The hash is SHA-256(0x01 || MTH(first k leaves) || MTH(the other n - k leaves)).

The leaf hashes already carry the 0x00 prefix, so they are not hashed again. A segment in a block never has zero rows.

Block hash

The chain is a sequence of blocks numbered by seq from 1. Each block has a body, the canonical encoding of a JSON object, stored exactly as hashed:

block_hash = SHA-256("sqlalchemy-audit-trail/block/v1" || 0x00 || prev_hash || body)

prev_hash is the 32-byte block_hash of the block before it. For block 1, the genesis block, it is 32 zero bytes.

A writer MUST store canonical(body). A verifier MUST hash the stored body bytes as they are; the reference verifier does not re-encode them.

Every body has the members v (the number 1), kind, chain (the chain id, a UUID as text) and seq. Hashes inside a body are base64. The members of each kind are:

kind Other members
genesis enforce_from: the xid horizon when the chain started. Always seq 1
seal xid_from, xid_to; segments: an array of {"stream", "partition", "rows", "root"}, with rows the number of leaves and root the base64 segment root, sorted by stream and then partition
fork incarnation; reason; prior_checkpoint: {"seq", "block_hash"} with the hash in base64; xid_at_fork; id_floor and id_count: objects from stream to number, or both null
checkpoint xid_to
retire table (transaction or activity); partition; streams: a sorted array of stream names; upper_bound: a timestamp as in leaf rows; retention: whole seconds, or null; and seals, segments, rows and segments_digest from the retire digest
ack failure; scope: an object; waives: an array of objects; reason

segments and streams are sorted by Unicode code point. Stream and partition names are ASCII, where that order equals UTF-16 order. The canonical encoding keeps array order, so the sort is part of the body.

The retire digest

A retire block covers every segment of its partition in the seal blocks before it. Take those segments, each with the seq of its seal block, sorted by seq and then stream. Then:

  • seals is {"first": seq, "last": seq} of the first and last of them, or null if there are none;
  • segments is how many there are;
  • rows is the sum of their rows;
  • segments_digest is base64 of SHA-256("sqlalchemy-audit-trail/retire/v1" || 0x00 || c1 || c2 || ...), where ci is canonical({"seq", "stream", "rows", "root"}) of the i-th segment, with root in base64.

Erasure journal

An erasure journal lists the scrubs since a point, without any erased value or salt. A version 2 checkpoint statement commits to it (see the bundle specification):

commitment = SHA-256("sqlalchemy-audit-trail/erasure-journal/v<n>" || 0x00 || form)

where <n> is the journal's version, the v member of form, and form is the journal's canonical encoding. A reader MUST refuse a journal text that is not exactly that encoding, and MUST hash the text as it is.

The form is an object with exactly these members:

  • v: the version, 1 or 2;
  • chain: the chain id;
  • since: a timestamp as in leaf rows, or null;
  • blocks: an array of [seq, block_hash], block_hash in base64, sorted by seq: the genesis block and every block a row names;
  • erasures: an array of objects, one per scrub transaction, sorted by xid, with exactly the members:
  • xid: the scrub's transaction id;
  • erased_at: the created_at of its audit.scrubbed record, a timestamp as in leaf rows;
  • severity: that record's severity;
  • reasons: the reason codes, sorted;
  • rows: the rows it stamped, sorted by table and then id, each an object with exactly table (activity or transaction), id, xid, groups (sorted: for an activity row actor, or changes, label and payload, with state too for a row that had data.state, or actor with those), seq (the seal block holding the row, or null) and leaf (the row's leaf hash in base64);
  • uncommitted, in version 2 only: the rows it erased that carry no commitments, sorted by table and then id, each an object with exactly table, id, xid (null for a row older than the xid column) and groups (sorted).

Version 1 is the form 0.5.0 writes; later releases write version 2 and read both. A row of uncommitted has no commitment and no leaf, so nothing in the chain attests it: the journal names it by id and xid only.

Test vectors

The vectors are JSON files under docs/spec/vectors/. canonical.json, commitments.json, leaves.json and blocks.json are copies of the package's golden test fixtures: a test fails if either copy changes without the other, and the package's tests fail if the encoder or the hashes stop matching them. The other files exist only here, and the package's tests run them from here. Hashes and salts are lowercase hex. Text fields are compared as UTF-8 bytes.

File Contents
canonical.json encode: input and its canonical text. refuse: inputs that have no encoding
numbers.json encode: numbers a reader must parse exactly: integers beyond 253, long decimals, negative zero, 1e16 and above
limits.json encode: numbers of exactly 4300 digits and values nested exactly 256 levels deep. refuse: one digit or one level more
commitments.json group, salt, value, its canonical text and the commitment
leaves.json row, its canonical text and the leaf hash; with table, row is a stored row and the leaf row is derived from it first
blocks.json merkle: leaf hashes and their root. blocks: one chain of prev_hash, body and block_hash, one block of each kind but ack
journals.json journals: an erasure journal text of each version and its commitment

Read the inputs as follows:

  • In numbers.json and limits.json, every number of input is an exact decimal. A reader MUST pass these. limits.json holds an integer of 4301 digits, one more than Python's default limit for int, so a reader may need to lift its own digit limit to read it. The reference reader, loads_exact, reads it as a decimal, which the encoder then refuses.
  • In canonical.json, commitments.json and leaves.json, a number of input, value or row with a fraction or an exponent is a binary64 double, as Python's json module reads it, and other numbers are exact integers. Only one case differs from an exact reading: large float in canonical.json, where the double's shortest round-trip text gives 12345678901234567000. Read exactly, the same input encodes as 12345678901234567890.
  • In leaves.json, a case with table holds a row as a driver reads it back: issued_at and created_at are timestamps with an offset, and request_id and correlation_id are UUIDs. Build the leaf row from it as in Leaf hash. A case without table hashes row as it is.
  • In blocks.json, the merkle leaves are the leaf hashes of {"n": 0}, {"n": 1} and so on.