Skip to content

Page checksums: the algorithm - #1316

Closed
Pranav-error wants to merge 1 commit into
pgmoneta:mainfrom
Pranav-error:page-checksums
Closed

Pranav-error wants to merge 1 commit into
pgmoneta:mainfrom
Pranav-error:page-checksums

Conversation

@Pranav-error

@Pranav-error Pranav-error commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1309.

Verify now checks the pages of a backup as well as the hashes of its files. The hash says a file is the one that was backed up; the page checksums say the pages inside it were not already damaged when it was. A file that fails its hash is reported for that and not checked twice.

commit
2743cf9 the checksum algorithm
c56255c fail the verify step when anything fails
8fa2b77 pick out the files with pages; check a whole file
b4c97e5 wire it into verify
47f48bf move the control-file fields behind an accessor
810b0f9 leave incremental, temporary and system files alone
dcf0fbd reject a segment number that does not fit
9322d0b docs

The two things you said on the issue

Failing the step. pgmoneta_verify() collected the failed files into the response and still answered response_ok, so a bad hash reported success at the protocol level. It now answers MANAGEMENT_ERROR_VERIFY_ERROR. This changes behaviour for plain hash failures too, not only page checksums — c56255c is that change on its own if you would rather it were separate.

The server's job. pgmoneta_sha512_verification() is untouched.

Decisions I made rather than hold the branch for

Both are cheap to change, so I picked and moved on. Say the word in review and I will flip either.

  • "(if enabled)" reads as the cluster's own setting. Pages are checked whenever the backup's pg_control has data_checksum_version != 0, and skipped silently otherwise. No new flag. That matches pgBackRest, and the cost is small enough not to need opting out of — page checksums run at 12–29 GB/s against ~1.5 GB/s for the SHA-512 this already does, on a file that is already decompressed and in hand, so it is a few percent of an existing verify.
  • verify first, not restore. The checksum core knows nothing about its caller, so restore --page-checksums is a later wiring change rather than a second implementation.
  • Incremental backups are skipped. An INCREMENTAL.* file holds only changed blocks behind a header, so it is not a run of pages at their own block numbers. Reconstructing them from the header is worth doing, separately.

Where the settings come from

The backup's own global/pg_control, not the server as configured now, since a backup can predate the current settings — block size, blocks per segment, and whether checksums were on. If it cannot be read, hashes are still checked and pages are skipped with a warning; guessing the block size would turn healthy pages into reported corruption. control_file_data is a union tagged by version, so those come through a small accessor.

Verified

Against pg_checksums on real clusters, including a relation over 1 GB so the second segment is genuinely exercised. Corrupting a block in segment 1 gives identical output from both:

this:          16384.1 segno=1 blk 20 stored=0xc09a computed=0x3db3
pg_checksums:  16384.1 block 20: calculated 3DB3 but block contains C09A

14 tests. Two bugs found by probing the classifier rather than by review, both of which would have reported healthy data as corrupt:

  • INCREMENTAL.16385 was read as segment 16385, putting every block number 16385 * relseg_size out.
  • A segment suffix too large for uint32_t was silently truncated, so 16385.4294967296 became segment 0.

Not verified here

The wired-up verify command has not been run end to end on my machine — test/check.sh wants Docker for its PostgreSQL container and I do not have it. Everything underneath it is tested as above; that path is covered by CI.

Two notes

build-linux (clang, Debug, 14) is red with The action 'Run Tests' has timed out after 45 minutes — that is #1295, and the draft in #1296 is the fix for it. Every other check passes.

Separately, process_result() in cli.c returns 0 whenever a reply parses, without reading Outcome.Status, so pgmoneta-cli verify ...; echo $? still prints 0 on a failed verification. That is shared by 27 commands, so I have left it alone rather than change every command's exit code inside this PR. Happy to do it as its own issue if you want it.

@Pranav-error
Pranav-error marked this pull request as ready for review September 18, 2026 08:11
Copilot AI lite review requested due to automatic review settings September 18, 2026 08:11

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Verify compared each file in a backup against its stored SHA-512. That
catches a file that changed after the backup was taken, but not a page
that was already corrupt when it was written, because the bad page is
hashed faithfully along with everything else.

Add the PostgreSQL page checksum algorithm and run it over the relation
files of a backup as part of verify, so a backup can be shown to be
restorable rather than merely unchanged.

The page settings are read from the backup's own global/pg_control, not
from the running server's configuration, so an old backup is checked
with the settings it was actually taken with. Files without pages are
skipped: incremental files, pgsql_tmp temporary files, and files whose
size is not a whole number of blocks. A relation's segment number is
folded into the block number, as PostgreSQL does, so segments past the
first verify correctly.

Verify now answers MANAGEMENT_ERROR_VERIFY_ERROR when a file fails,
instead of reporting success with the failures listed in the payload.

The algorithm was checked against pg_checksums on real clusters,
including a relation larger than 1GB with a .1 segment, and agrees
byte for byte. Page checksumming runs at 12.6-29 GB/s against roughly
1.5 GB/s for SHA-512, so it adds a few percent to an existing verify.
Pranav-error added a commit to Pranav-error/pgmoneta that referenced this pull request Oct 4, 2026
dirname() is not required to return the pointer it was given -- on
macOS/BSD libc it can return a pointer into static storage instead of
modifying the strdup'd buffer in place. free(dir_path) was freeing
whatever dirname() returned rather than the actual allocation, which
crashes macOS's hardened malloc ("BUG IN CLIENT OF LIBMALLOC: not an
allocated block") and is undefined behavior elsewhere.

Found while getting PR pgmoneta#1316's test_cli_verify to actually run
end-to-end: any restore (or verify, which restores internally) of a
backup containing a tablespace crashed inside
copy_tablespaces_restore() -> pgmoneta_symlink_at_file() before this
fix.

Uses pgmoneta_append() rather than strdup() per project convention.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@Pranav-error

Copy link
Copy Markdown
Collaborator Author

Got test/check.sh -t test_cli_verify actually building and running end-to-end for the first time (previously blocked by environment-level issues under colima on macOS/arm64), and the page-checksum verify logic now passes against a live PostgreSQL 17 backup with tablespaces.

Along the way I hit two pre-existing bugs, unrelated to this PR's own diff, that were specifically what crashed this test before it ever reached the checksum logic:

With both of those fixed, test_cli_verify passes. Also hit #1347 / #1350, test-harness-only issues (sudo detection + Dockerfile GPG trust) that block Docker-based testing under colima regardless of this PR.

None of this is a change to this PR's own code -- just flagging that it's now been genuinely exercised end-to-end rather than only harness-verified.

@jesperpedersen

Copy link
Copy Markdown
Member

Rebased and merged.

Thanks for your contribution !

jesperpedersen pushed a commit that referenced this pull request Oct 8, 2026
dirname() is not required to return the pointer it was given -- on
macOS/BSD libc it can return a pointer into static storage instead of
modifying the strdup'd buffer in place. free(dir_path) was freeing
whatever dirname() returned rather than the actual allocation, which
crashes macOS's hardened malloc ("BUG IN CLIENT OF LIBMALLOC: not an
allocated block") and is undefined behavior elsewhere.

Found while getting PR #1316's test_cli_verify to actually run
end-to-end: any restore (or verify, which restores internally) of a
backup containing a tablespace crashed inside
copy_tablespaces_restore() -> pgmoneta_symlink_at_file() before this
fix.

Uses pgmoneta_append() rather than strdup() per project convention.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jesperpedersen pushed a commit that referenced this pull request Oct 8, 2026
pgmoneta_crc_init() had its entire body wrapped in
#ifdef HAVE_CRC32_SSE42, an x86-only macro. The software fallback
implementation, pgmoneta_crc32c_software(), was also defined inside
that same guard, so on any platform without HAVE_CRC32_SSE42 (ARM64
in particular) neither implementation is compiled, crc_init() is a
no-op, and the crc_impl function pointer is left NULL. Every call to
pgmoneta_create_crc32c_buffer() then branches through a NULL function
pointer.

The software implementation has no SSE4.2 dependency at all -- it's a
plain lookup-table CRC -- so it belongs outside the SSE42-only guard.
Only the actual SSE4.2 hardware path stays gated on
HAVE_CRC32_SSE42 + runtime cpu_supports_sse42().

Found and verified live on macOS/arm64: pgmoneta-cli verify crashed
every time with a SIGSEGV at address 0 inside
get_controlfile_by_exact_path() -> pgmoneta_read_control_data(), which
is the first thing that calls pgmoneta_create_crc32c_buffer() during
backup verification. This was specifically what blocked PR #1316's
test_cli_verify from ever completing on this platform; after this fix
it passes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jesperpedersen pushed a commit that referenced this pull request Oct 8, 2026
Two independent fixes needed to get test/check.sh working under
colima, a free Docker Desktop alternative:

1. check.sh and all three postgresql{14,15,17} Makefiles detected
   whether to prefix docker commands with sudo purely by checking
   `id -u`. Under a rootless Docker context the socket is already
   reachable without sudo, and forcing sudo anyway just blocks
   forever on an interactive password prompt in a non-interactive
   invocation. Now also check whether `docker info` already succeeds
   before falling back to sudo.

2. The postgresql17 Dockerfile's `--nogpgcheck` on installing the
   pgdg-redhat-repo RPM only skips verification for that one package;
   it does not import the key into any trust store dnf consults for
   later operations. Every subsequent dnf call against the
   pgdg-common/pgdg-rhel10 repos then fails GPG verification, in three
   layers as each is patched (repo_gpgcheck on `dnf -y upgrade`, then
   again on any later install, then package-level gpgcheck once
   repo_gpgcheck is disabled -- the actual PostgreSQL 17 RPMs are
   signed with a key that doesn't match what's in the vendored
   PGDG-RPM-GPG-KEY-RHEL file). Disables both checks for this repo via
   the dropped-in .repo file rather than solving the stale-key problem,
   since the key itself needs attention from someone who can verify
   what's current upstream.

Verified by getting test/check.sh -t test_cli_verify to build and run
successfully under colima on macOS/arm64 for the first time -- this
was blocking any Docker-based testing of PR #1316 before these fixes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jesperpedersen pushed a commit that referenced this pull request Oct 8, 2026
process_result() in cli.c always returned 0 once a response was
received and printed, never checking whether the operation itself
succeeded. pgmoneta-cli verify/backup/restore/etc. exited 0 even when
the server reported Outcome.Status = false, so a script checking $?
could not tell a failed operation from a successful one.

Read Outcome.Status after printing and return 1 when it is false,
matching the pattern already used for the same field in conf_get's
error handling a few hundred lines above (cli.c ~2208). All 25 call
sites route through process_result the same way, so this is a single
change rather than 25.

Confirmed with @jesperpedersen on #1309/#1316 (page checksums): Success
== 0, Error == 1. Opened separately from #1316 since this changes the
exit code of every command, not just verify.

Verified: builds clean (binary + full test suite), clang-format clean,
and the fix mirrors an already-proven pattern in the same file rather
than introducing a new one. Could not exercise this end to end -- the
existing CLI tests (test_cli.c) go through the tsclient library
against the management protocol directly, bypassing cli.c entirely,
and test/check.sh's integration harness needs Docker/podman, which
isn't available on this machine (same constraint already noted on

Signed-off-by: sai pranav <[email protected]>
#1316).
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.

Page-level checksum verification: design proposal

3 participants