Repository navigation
Seal committed audit entries into a hash chain - #76
Open
WiktorB2004 wants to merge 15 commits into
Open
WiktorB2004 wants to merge 15 commits into
WiktorB2004 wants to merge 15 commits into
Conversation
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.
4 of 6 tasks
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #70. Builds on #75 (commitments, the
xidcolumn andadd_integrity), so please review that first. This branch gets rebased ontomainonce #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.build_tables(integrity=True)also declares the block table, named bybuild_tables(seal_block_table="audit_seal_block")liketransaction_tableandactivity_table.AuditTables.seal_blockholds it.create_statements,drop_statements,add_integrityandtesting.clear_audit_entriesinclude it.bodyis stored exactly as it was hashed. The sealer lock follows the table name, so two sets of audit tables in one schema seal independently.migrations.write_genesis()is the last migration step, run once every writer hasIntegrityon. It recordsenforce_from, the horizonpg_snapshot_xmin(pg_current_snapshot())at that moment. Calling it again returns the existing block withcreated=False, also when another call committed it after this transaction's snapshot. Beforeadd_integrityit raises aValueErrorthat namesmigrations.add_integrity().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 checkspg_is_in_recovery(), tries an advisory lock and reads H.busy.XID_REWIND.max_rowsis a soft cap and never splits a transaction. The cut reads at mostmax_rows + 1index entries per table (an orderedLIMITper table, a Merge Append over the partition indexes), not the whole backlog.dataoutsidechanges,payloadand the actor keys ofcontext, andseal_commitments. It leaves outobject_label, the actor columns,seal_saltsandseal_erased.health()reportssealwith the number of unsealed rows (counted up to a cap) and the lag, compared againstmax_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. Beforeadd_integrityorwrite_genesis,sealis not ok and its message names the step to run; it does not raise. Without integrity,sealisNoneandokworks as before.max_prepared_transactions=10, and CI sets it on the service container and restarts it.Test plan
uv run pytestpasses locally, including the PostgreSQL tests intests/dbAUDIT_TEST_PG_IMAGE=postgres:14) as well as the default imageruff check,ruff format --checkandmypypassCHANGELOG.mdUnreleasedbullet if callers should noticeDocstrings are updated. Docs and the CHANGELOG are left for the PR that makes integrity public.
The new database tests use real concurrent connections:
busy, and awrite_genesisin the same position returns the committed block.health()flags it.standby.signal), the sealer returns without sealing. In CI (AUDIT_TEST_EXPECT_PGset) 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 defaultmax_rowsof 50,000: