Skip to content

Seal committed audit entries into a hash chain - #76

Open
WiktorB2004 wants to merge 15 commits into
add-integrity-commitmentsfrom
add-integrity-sealer
Open

WiktorB2004 wants to merge 15 commits into
add-integrity-commitmentsfrom
add-integrity-sealer

Conversation

@WiktorB2004

Copy link
Copy Markdown
Owner

Summary

Closes #70. Builds on #75 (commitments, the xid column and add_integrity), so please review that first. This branch gets rebased onto main once #75 is merged.

This adds the sealer and the hash chain. It is still private: nothing new is exported from audit_trail, and there are no docs pages yet.

  • Block table. build_tables(integrity=True) also declares the block table, named by build_tables(seal_block_table="audit_seal_block") like transaction_table and activity_table. AuditTables.seal_block holds it. create_statements, drop_statements, add_integrity and testing.clear_audit_entries include it. body is stored exactly as it was hashed. The sealer lock follows the table name, so two sets of audit tables in one schema seal independently.
  • Genesis. migrations.write_genesis() is the last migration step, run once every writer has Integrity on. It records enforce_from, the horizon pg_snapshot_xmin(pg_current_snapshot()) at that moment. Calling it again returns the existing block with created=False, also when another call committed it after this transaction's snapshot. Before add_integrity it raises a ValueError that names migrations.add_integrity().
  • Sealer. audit.maintenance.seal() / aseal() write at most one block per call. The block covers [H(last), H), where H is the current horizon, and holds one RFC 6962 Merkle root per (stream, partition). The sealer runs in one REPEATABLE READ transaction. Its first statement checks pg_is_in_recovery(), tries an advisory lock and reads H.
    • On a standby it returns without sealing.
    • When another sealer holds the lock, or committed a block this snapshot does not see, it returns busy.
    • When H is below the sealed horizon, it refuses with XID_REWIND.
    • max_rows is a soft cap and never splits a transaction. The cut reads at most max_rows + 1 index entries per table (an ordered LIMIT per table, a Merge Append over the partition indexes), not the whole backlog.
    • Audit rows are never updated.
  • Leaves. A leaf hashes the columns that no scrub changes, the part of data outside changes, payload and the actor keys of context, and seal_commitments. It leaves out object_label, the actor columns, seal_salts and seal_erased.
  • Health. With integrity on, health() reports seal with the number of unsealed rows (counted up to a cap) and the lag, compared against max_seal_lag. The lag is measured from the entries' event time (issued_at, created_at), not their commit. It also lists prepared transactions older than that limit, because they hold the horizon back. Before add_integrity or write_genesis, seal is not ok and its message names the step to run; it does not raise. Without integrity, seal is None and ok works as before.
  • Golden vectors freeze the leaf rows, Merkle roots, and the genesis, seal and fork block bodies.
  • Test servers allow prepared transactions: testcontainers starts with max_prepared_transactions=10, and CI sets it on the service container and restarts it.

Test plan

  • Tests added or updated (or N/A — say why)
  • uv run pytest passes locally, including the PostgreSQL tests in tests/db
  • Schema, SQL or partition changes checked on PostgreSQL 14 (AUDIT_TEST_PG_IMAGE=postgres:14) as well as the default image
  • ruff check, ruff format --check and mypy pass
  • Docs and docstrings updated if the public API changed
  • CHANGELOG.md Unreleased bullet if callers should notice

Docstrings are updated. Docs and the CHANGELOG are left for the PR that makes integrity public.

The new database tests use real concurrent connections:

  • A transaction with a lower xid that commits after a seal lands in the next block.
  • A second sealer that runs while the first one holds the lock returns without sealing.
  • A sealer whose snapshot predates another sealer's commit returns busy, and a write_genesis in the same position returns the committed block.
  • Two sets of audit tables in one schema, with their own block tables, seal independently.
  • An idle read-only session does not hold the horizon back.
  • A prepared transaction does hold it back, and health() flags it.
  • On a real hot standby (a second container started with standby.signal), the sealer returns without sealing. In CI (AUDIT_TEST_EXPECT_PG set) this test fails instead of skipping when it cannot start the container.

Every one of these tests was checked to fail when its fix is reverted.

EXPLAIN (ANALYZE, BUFFERS) with 1.1M unsealed rows (110k transactions, 990k activities, 45 leaf partitions) and the default max_rows of 50,000:

PG14 before PG14 after PG18 before PG18 after
cut 168 + 470 ms, Parallel Seq Scan + Sort, 2 × 12,251 buffers 71 ms, Merge Append of Index Only Scans, 496 buffers 115 + 185 ms, same 59 ms, same, 496 buffers
health 22 + 101 ms, Parallel Seq Scan + Aggregate, 12,173 buffers 7 ms, Limit over Merge Append, 303 buffers 12 + 87 ms 7 ms, 303 buffers

The sealer tests prepare a transaction to check that it holds the seal
horizon back. The testcontainers server starts with
max_prepared_transactions set, CI sets it on its service container, and
the environment test asserts it there.
A leaf hashes the columns of a row that never change after insert, the
part of data no scrub touches, and seal_commitments. Segment roots are
RFC 6962 Merkle tree hashes built with an O(log n) stack. Block bodies
are canonical JSON naming their version, kind, chain and seq, and chain
by SHA-256 over the previous hash and the stored body. Golden vectors
freeze leaves, roots and the genesis, seal and fork bodies.
build_tables(integrity=True) declares it in the same metadata, so
create_statements and drop_statements include it, add_integrity creates
it on an existing install, and clear_audit_entries empties it. body is
stored exactly as hashed, and a partial unique index on
retired_partition will keep retire blocks idempotent. Without integrity
nothing changes.
migrations.write_genesis starts the chain with enforce_from, the horizon
pg_snapshot_xmin(pg_current_snapshot()) at that moment. seal() and
aseal() then append one block per call over [H(last), H): one REPEATABLE
READ transaction whose first statement checks pg_is_in_recovery(),
tries the advisory lock and reads the horizon. A second sealer returns
busy, a standby returns without sealing, and a horizon below the sealed
one refuses with XID_REWIND. max_rows is a soft cap: the cut never
splits a transaction. health() reports the seal lag and prepared
transactions older than max_seal_lag.
build_tables(seal_block_table=...) names the block table like the other
two, and AuditTables carries it. The sealer lock key follows the block
table, so two sets of audit tables in one schema seal independently.
A sealer whose snapshot predates another sealer's commit can still win
the try-lock. Its block insert then fails on the seq primary key; treat
that unique violation as busy instead of raising.
At REPEATABLE READ, a write_genesis whose snapshot predates another
call's commit does not see block 1 and hits its primary key. Insert in a
savepoint and read the committed block on a fresh connection instead.
health and write_genesis check for the block table with to_regclass in
their first query. health reports the chain as not started with a
message, and write_genesis raises a ValueError, instead of failing with
a ProgrammingError that aborts the caller's transaction. The message for
a chain without a genesis block names write_genesis.
The cut sorted the whole unsealed range of both tables, twice per seal,
and health counted it. Each table now gets an ordered LIMIT branch that
walks its (xid, id) indexes, merged in one pass that yields the first row
and the one past max_rows. Health takes the oldest unsealed entry by
xid with LIMIT 1 and counts up to UNSEALED_ROWS_CAP.
The second seal's horizon was compared with itself; check it against
the last write and the block instead. The standby fixture now fails
instead of skipping when AUDIT_TEST_EXPECT_PG is set, as in CI, and
also skips without Docker when the container cannot even be created.
AuditTables carries seal_block_table even when no block table is
declared, so add_integrity on an install that has no integrity yet
creates the block table under the configured name instead of
audit_seal_block. Docstrings no longer name the default table.
The first sealer sealed nothing when another transaction of the cluster
still held the horizon below the test's write, so it never reached its
INSERT and the poll ran out. Wait until the horizon passes the write, and
poll only for a backend that holds the sealer lock while waiting on this
block table.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant