Skip to content

Implement AOF data integrity check support. - #3565

Open
sumitk163 wants to merge 7 commits into
valkey-io:unstablefrom
sumitk163:aof-metadata-integrity
Open

sumitk163 wants to merge 7 commits into
valkey-io:unstablefrom
sumitk163:aof-metadata-integrity

Conversation

@sumitk163

@sumitk163 sumitk163 commented Apr 25, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds AOF integrity verification, which protects against bit rot, torn writes and missing log entries. With aof-integrity-check enabled, AOF files carry checksums that the server verifies when loading.

How it works

  • INCR files: each flush of the AOF buffer is written as a block with a header, #HDR:v1;len:<block_len>;checksum:<running_crc64>;\r\n. The checksum is a running CRC64 of the chain up to the end of the block, and the chain continues across INCR files and rewrites. The loader verifies each block before running any of its commands, and requires headers from the first byte of an integrity file.
  • Base file: an RDB base is protected by its own CRC64, also with rdbchecksum no. A RESP base (aof-use-rdb-preamble no) ends with a #CRC:<crc64> line covering the rest of the file.
  • Manifest: marks the files written with integrity (integrity 1), and records on the base line where the first INCR file's chain starts. A last line, # manifest-checksum: <crc64>, protects the manifest itself.
  • Torn writes: with aof-load-truncated yes, a torn block or header at the end of the last file is truncated at the end of the previous block. Anything else (a checksum mismatch, a missing header, incomplete data inside a verified block) is reported as corruption.

The header format is specified in design-docs/aof-header-spec.md.

Configuration

aof-integrity-check (default no). Changing it at runtime, or enabling it across a restart, schedules an AOF rewrite, and the new setting applies to the files it creates, so enabling it also covers the base once the rewrite completes. When disabled, files written with integrity are loaded without being verified, and since the end of the last INCR file isn't verified, it's no longer treated as an integrity file: writes continue in it without headers.

valkey-check-aof

The tool always verifies integrity metadata, including the manifest checksum. --fix truncates the last file at a block boundary, and --truncate-to-timestamp truncates at the start of the block that contains the timestamp. After a manual edit of the manifest, --fix can also update the manifest checksum.

Changes with the feature disabled

Tests

  • Integration tests in tests/integration/aof-integrity.tcl: torn writes and torn headers, corruption, commands crossing a block boundary, malformed headers, runtime toggling, restarts with a changed setting, a failed rewrite followed by a successful one, enabling appendonly at runtime, DEBUG LOADAOF, replication full sync (disk-based and diskless), manifest validation, base protection (RESP #CRC, RDB with rdbchecksum no, LZ4), and valkey-check-aof (--fix, --truncate-to-timestamp).
  • Unit tests for the header parser in src/unit/test_aof_header.cpp.
  • The full Tcl, module API, unit and sentinel suites pass with aof-integrity-check defaulting to yes, except two tests that check the exact AOF content without integrity.

Performance

All numbers are the median of 3 runs on a 16-core AMD EPYC 7B13, with files in the page cache.

Writes

valkey-benchmark -t set -r 100000, no pipelining, appendfsync everysec.

Clients Value size Integrity Writes/sec p50 (ms) p99 (ms) AOF bytes per write
50 10 B off 48,871 0.535 0.919 53.0
50 10 B on 48,773 (-0.2%) 0.543 0.983 69.7 (+32%)
50 1 KB off 48,426 0.567 0.983 1,069.0
50 1 KB on 48,695 (+0.6%) 0.583 1.039 1,077.5 (+0.8%)
50 10 KB off 35,714 1.199 2.015 10,286.0
50 10 KB on 32,415 (-9.2%) 1.335 2.247 10,287.6 (+0.02%)
1 10 B off 14,953 0.055 0.111 53.0
1 10 B on 14,835 (-0.8%) 0.055 0.103 99.3 (+87%)
  • Throughput: the CRC64 over each flushed block runs on the main thread. Its cost grows with the bytes written, so it shows mostly with large values (-9% at 10 KB).
  • Disk: each AOF write adds a header of about 50-65 bytes. That's negligible for large values or many commands per write, but almost doubles the AOF with one small command per write (for example, a single client). AOF rewrites trigger sooner by the same factor.

Loading

INCR files written with integrity, then loaded with aof-integrity-check on (verified) and off (headers skipped).

Workload File size Integrity off Integrity on
5M SET, 64 B values, 50 clients (~1.4M blocks) 610 MB 5.54 s 5.40 s (-2.5%)
Same, pipelined (-P 32) 535 MB 5.31 s 4.45 s (-16%)
200k SET, 4 KB values 829 MB 1.16 s 0.99 s (-15%)

Verified loading isn't slower. Each block up to 1 MB is read from the file once, checked in memory, and then parsed from there, which is cheaper than parsing through many small stdio reads.

Flame graphs

With data size 1KB : The flamegraph shows that 4.67% cpu cycles are spent on crc computation

Valkey checksumming performance

With data size 10KB: The flamegraph shows that 8.28% cpu cycles are spent on crc computation.

Valkey checksumming performance (2)

Follow-ups

Closes #3885

@madolson madolson left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some initial feedback β€” dead code, naming, and a log message fix. Please fix the DCO. Overall I think the general direction of the functionality makes sense.

Comment thread src/aof.c
if (!cksum_tag) {
serverLog(LL_WARNING, "AOF integrity header in %s lacks a checksum", filename);
goto fmterr;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Dead code. if (!cksum_tag) above goes to fmterr, so this if (cksum_tag) is always true. Remove the redundant guard. Same pattern in valkey-check-aof.c.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this, fixed.

Comment thread src/valkey-check-aof.c Outdated
off_t current_pos = ftello(fp);

size_t remaining = h_len;
unsigned char check_buf[16 * 1024];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same dead if (cksum_tag) guard as in aof.c.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

Comment thread src/aof.c Outdated
if (server.aof_integrity_check && sdslen(buf) > 0) {
server.aof_lsn++;
char hdr_prefix[128];
int hdr_prefix_len =

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

General naming feedback across the PR: prefer more descriptive names over abbreviations. aof_lsn β†’ aof_sequence or aof_seq_number (LSN is single-use jargon here), h_len/h_lsn/h_cksum β†’ hdr_len/hdr_seq/hdr_checksum, cksum β†’ checksum, calc_cksum β†’ computed_checksum, cksum_tag β†’ checksum_tag. The abbreviated forms save a few characters but make the code harder to read without context. Applies to variable names, header field names (cksum: β†’ checksum:), and the RDB aux key (aof-lsn β†’ aof-seq).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Makes sense, updated the naming as suggested.

Comment thread src/aof.c Outdated
size_t to_read = remaining > sizeof(check_buf) ? sizeof(check_buf) : remaining;
if (fread(check_buf, to_read, 1, fp) != 1) {
serverLog(LL_WARNING, "AOF short write detected in %s. Expected %zu more bytes",
filename, remaining);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

"AOF short write detected" β€” this is during loading, so it should be "short read". Same in valkey-check-aof.c.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated.

@madolson madolson added the major-decision-pending Major decision pending by TSC team label Apr 27, 2026
@madolson

Copy link
Copy Markdown
Member

Another alternative would be to have a running checksum that we persist, which might make some of the code a bit simpler. We would still need to persist it like the sequence number like we do today.

Otherwise, the general feature seems useful to me.

@sumitk163

sumitk163 commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Another alternative would be to have a running checksum that we persist, which might make some of the code a bit simpler. We would still need to persist it like the sequence number like we do today.

Thanks @madolson for the suggestion. Is the idea to use a running checksum in place of seq and per-log checksum in the incremental log headers? So, the incremental log header would comprise of the len and the (running) checksum fields. The AOF snapshots will have the running checksum for the incremental logs in the aux field.

Or is the suggestion something else?

@sumitk163
sumitk163 requested a review from murphyjacob4 April 27, 2026 20:55
@sumitk163

Copy link
Copy Markdown
Contributor Author

@sumitk163

Copy link
Copy Markdown
Contributor Author

@madolson I updated the header to use a running checksum instead of using an lsn and per-log checksum. Ptal.

@codecov

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.58200% with 58 lines in your changes missing coverage. Please review.
βœ… Project coverage is 81.59%. Comparing base (0608ff7) to head (8e00cc2).
⚠️ Report is 21 commits behind head on unstable.

Files with missing lines Patch % Lines
src/aof.c 90.27% 43 Missing ⚠️
src/valkey-check-aof.c 86.48% 15 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #3565      +/-   ##
============================================
+ Coverage     81.43%   81.59%   +0.16%     
============================================
  Files           199      200       +1     
  Lines        104768   105489     +721     
============================================
+ Hits          85317    86074     +757     
+ Misses        19451    19415      -36     
Files with missing lines Coverage Ξ”
src/config.c 81.82% <100.00%> (+0.06%) ⬆️
src/evict.c 99.18% <100.00%> (ΓΈ)
src/object.c 92.19% <100.00%> (-0.62%) ⬇️
src/rdb.c 77.56% <100.00%> (+0.39%) ⬆️
src/rdb.h 100.00% <ΓΈ> (ΓΈ)
src/rio.h 94.23% <ΓΈ> (ΓΈ)
src/server.c 90.26% <100.00%> (+0.07%) ⬆️
src/server.h 100.00% <ΓΈ> (ΓΈ)
src/unit/test_aof_header.cpp 100.00% <100.00%> (ΓΈ)
src/valkey-check-rdb.c 77.09% <100.00%> (ΓΈ)
... and 2 more

... and 25 files with indirect coverage changes

πŸš€ New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • πŸ“¦ JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread src/aof.c Outdated
uint64_t computed_checksum = crc64(server.aof_running_checksum, (unsigned char *)buf, checksum_tag - buf);
off_t current_pos = ftello(fp);

size_t remaining = hdr_len;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we cap this somehow? since we read this directly from file something like len:SUPERBIGNUMBER could have us spinning forever no?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's a valid point. While it won't spin forever (it will stop at EOF), a maliciously large len would force the server to checksum the entire remaining AOF file during recovery.

I also thought about enforcing that the hdr_len is below some threshold, but I am not sure what a safe threshold may be, since we currently don't enforce any such limit afaiu. So, I thought adding such a limit might be backwards incompatible. Maybe we can add some threshold like X GB?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(Sorry I didnt follow up here -- i am not in control of my github notifications). Some threshold for safety sounds reasonable, just to have some form of limit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could a corrupted header cause overflow? strtoull is unsigned 64 bit integer and off_t is 32/64 signed (depending on system). We should at least guard against that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

Comment thread src/aof.c Outdated
if (server.aof_state == AOF_ON || (server.aof_state == AOF_WAIT_REWRITE && server.child_type == CHILD_TYPE_AOF)) {
if (server.aof_integrity_check && sdslen(buf) > 0) {
char hdr_prefix[128];
int hdr_prefix_len = snprintf(hdr_prefix, sizeof(hdr_prefix), "#HDR:v1;len:%zu;", sdslen(buf));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

do we need to guard against a value of this greater than 128?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added an assertion to ensure the header fits within the allocated space.

Comment thread src/rdb.c Outdated
Comment on lines +3328 to +3329
} else if (!strcasecmp(objectGetVal(auxkey), "aof-checksum")) {
server.aof_running_checksum = strtoull(objectGetVal(auxval), NULL, 10);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should this be guarded by the config too

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, added.

Comment thread src/valkey-check-aof.c Outdated
int rdb_file = fread(sig, sizeof(sig), 1, fp) == 1 && memcmp(sig, "REDIS", sizeof(sig)) == 0;
if (rdb_file) {
char sig[6];
if (fread(sig, 1, 6, fp) == 6 && (memcmp(sig, "REDIS", 5) == 0 || memcmp(sig, "VALKEY", 6) == 0)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we change the condition to >= 9 ?

VALKEY009
^^^^^^~~~
6 bytes magic + 3 bytes version = 9 bytes minimum

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this, fixed.

@sumitk163
sumitk163 requested a review from jjuleslasarte May 2, 2026 02:47
@PingXie

PingXie commented May 2, 2026

Copy link
Copy Markdown
Member

High level review notes:

  1. Header format spec
    A new AOF annotation is part of the persistence format. We need a spec to define the exact grammar, field order, encoding, required fields, malformed-field behavior, duplicate/unknown-field behavior, and checksum coverage. It should also settle the footprint/readability tradeoff now. The current form, #HDR:v1;len:<n>;checksum:<crc>\r\n, is easy to read but fairly verbose for small AOF entries; changing it after release would be expensive.

  2. Integrity model
    The design choice between LSN + per-entry checksum and continuous running CRC affects what the feature guarantees and how recovery tooling behaves. Continuous CRC can detect corrupted, missing, or reordered records in a checked stream, but it makes rewrite boundaries, mixed-integrity regions, and PITR prefix validation more stateful.

  3. Integrity metadata ownership
    The current design stores AOF continuation state in RDB AUX fields, which couples AOF integrity to RDB-preamble mode and effectively requires aof-use-rdb-preamble yes. That may be unnecessarily limiting and coupling. A cleaner design may be: RDB checksum validates the base RDB, AOF headers validate command records, and the AOF manifest binds the selected base/incr file set. If Valkey wants integrity to work with plain AOF base files too, the metadata should probably live in AOF annotations or the manifest rather than RDB AUX.

  4. Runtime toggle semantics
    Because aof-integrity-check is modifiable, the format can contain integrity-enabled, disabled, and re-enabled regions. The design should define what guarantees apply across #INTEGRITY_OFF, whether re-enabling starts a new chain or resumes one, whether toggling is allowed during rewrite, and how older tools should handle mixed regions. This is in a sense part of the format spec too but more on the dynamic behavior.

@madolson

madolson commented May 4, 2026

Copy link
Copy Markdown
Member

From the OSS core team meeting:

  1. Block vs per-command. (Sumit is going to vibe code some POCs to get some concrete data about the trade-offs). Specifically performance and disk usage.
  2. Decision was to move the running checksum into the manifest.
  3. Summit will only a draft PR for the spec that we will keep around and merge into the final version.

@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch from d463e33 to 4835c75 Compare June 30, 2026 20:11
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▢️ Resume reviews
  • πŸ” Trigger review
Walkthrough

Introduces CRC64-based AOF integrity checks controlled by aof-integrity-check. Adds integrity framing for AOF writes and replay, checksum metadata in manifests, rewrite checksum propagation, RDB checksum gating, validation tooling, tests, and documentation.

Changes: AOF Integrity Checking

Layer / File(s) Summary
Integrity state and config
src/server.h, src/server.c, src/config.c, valkey.conf
Adds AOF integrity fields and marker declarations, initializes server state, and registers aof-integrity-check with an apply hook that resets checksum state and injects the off-marker when disabled.
Manifest checksums
src/aof.c
Adds per-entry checksum fields and a manifest-wide checksum line to AOF manifests, validates them while loading, and updates checksum state when opening new incremental files.
Integrity write path
src/aof.c
Adds aofWritev, prepends CRC64-framed #HDR:v1 headers to flush batches, updates short-write handling for the combined header and payload length, restores running checksum on error, and preserves unwritten data in aof_retry_buf.
Replay-time validation
src/aof.c
Tracks validated offsets during AOF load, parses and verifies #HDR:v1 headers and payloads, recognizes the integrity-off marker, enforces header boundaries before commands, and seeds the running checksum from the BASE manifest entry.
Rewrite and RDB checksum gating
src/aof.c, src/rdb.c
Refuses background rewrite while AOF buffers remain pending, captures and persists the running checksum into the rewritten BASE manifest entry, and extends RDB checksum enable and verify conditions for AOF preamble files.
valkey-check-aof validation
src/valkey-check-aof.c
Adds CRC64-based integrity-header parsing and validation, chain state tracking, missing-header enforcement, RDB preamble signature detection updates, and manifest-driven chain initialization for multi-part AOFs in valkey-check-aof.
Tests and docs
tests/integration/aof-integrity.tcl, tests/support/aofmanifest.tcl, valkey.conf
Adds end-to-end integrity tests, updates manifest parsing helpers to scan all lines, and documents the new configuration option and runtime toggle behavior.

Estimated code review effort: 4 (Complex) | ~75 minutes

Suggested reviewers: zuiderkwast, dvkashapov, sarthakaggarwal97

Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed The PR adds AOF integrity headers, checksum validation, and corruption detection aligned with issue #3885.
Out of Scope Changes check Passed The changes stay focused on AOF integrity support, related config, tooling, and tests.
Title check Passed The title clearly summarizes the main change: adding AOF data integrity checks.
Description check Passed The description is specific and related to the changeset. It states that the PR adds AOF integrity verification with an aof-integrity-check option. It describes the INCR block header format, base fi…
Full details: Description check

Explanation

The description is specific and related to the changeset. It states that the PR adds AOF integrity verification with an aof-integrity-check option. It describes the INCR block header format, base file protection, manifest checksum, and torn-write handling. It also lists the changes to valkey-check-aof, tests in tests/integration/aof-integrity.tcl, and a unit test for the header parser. These details match the raw summary's changes in aof.c, config.c, server.h, valkey-check-aof.c, and the Tcl test suite. The description also covers behavior changes with the feature disabled and includes performance data.

  • Autofix Β· Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch from 4835c75 to 107ca45 Compare June 30, 2026 20:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/aof.c (1)

1819-1865: πŸ—„οΈ Data Integrity & Integration | 🟠 Major | ⚑ Quick win

Validate that the entire RESP command stays inside the checked range.

The current check only proves the command’s first line starts before integrity_validated_until. A malformed header length that covers the first line but not the full bulk payload can let unverified bytes be parsed and executed.

Proposed fix
         for (j = 0; j < argc; j++) {
             /* Parse the argument len. */
             char *readres = fgets(buf, sizeof(buf), fp);
@@
                 goto readerr;
             }
         }
+
+        if (server.aof_integrity_check && server.aof_integrity_chain_active &&
+            ftello(fp) > integrity_validated_until) {
+            serverLog(LL_WARNING, "AOF command in %s extends beyond its integrity header.", filename);
+            freeClientArgv(fakeClient);
+            goto fmterr;
+        }
 
         /* Command lookup */
         sds err = NULL;
πŸ€– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/aof.c` around lines 1819 - 1865, The integrity check in the AOF command
parsing flow only validates the command header at the start of the RESP frame,
so malformed bulk lengths can extend past integrity_validated_until and still be
parsed; update the logic in the AOF reader loop to verify the full RESP command
range before accepting it. Use the existing parsing path around the integrity
check, argc handling, and the per-argument fread/strtol processing to compute
the total bytes for the command and reject it if any part would fall outside the
validated range.
πŸ€– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/aof.c`:
- Around line 1325-1341: `flushAppendOnlyFile()` can return while
`server.aof_retry_buf` still has pending bytes, so avoid any AOF rotation or
`openNewIncrAofForAppend()` switch until that buffer is fully drained. Update
the retry-buffer handling in `flushAppendOnlyFile()` (and the rotation path
referenced by the same logic) so it returns early with the existing
`server.aof_fd` preserved whenever `sdslen(server.aof_retry_buf) > 0`,
preventing leftover integrity-frame bytes from being written into a new INCR
file.
- Around line 1350-1363: The AOF write path in the checksum/header assembly
around the aofWritev() flow advances server.aof_running_checksum before the data
is actually written, so a full write failure can leave the retry seeded with an
invalid checksum state. Update the logic in the write path that builds the
header and calls aofWritev() to save the previous checksum before assigning
server.aof_running_checksum, and restore that saved value whenever writev fails
without writing bytes; apply the same rollback behavior in the matching retry
path used for the other affected block. Ensure the fix is tied to the checksum
update and write retry flow in aof.c rather than the header construction itself.
- Around line 312-327: The manifest parsing in src/aof.c currently only enforces
integrity when the # manifest-checksum: trailer is present, so a torn write that
drops that line can still be accepted. Update the manifest-reading logic around
the checksum handling path (the block that parses # manifest-checksum: and the
EOF exit path) to remember whether any per-file checksum was seen and whether
the final manifest checksum line was encountered, then reject the manifest at
EOF if checksum-bearing entries were parsed but the trailer is missing. Make the
failure follow the same fatal path used by the checksum mismatch case in the
manifest loader.

In `@src/valkey-check-aof.c`:
- Around line 189-194: The `#HDR`:v1 parser in the AOF checker is too permissive
because `strstr()` and `strtoull(..., NULL, 10)` accept malformed or ambiguous
fields. Tighten the parsing in the `src/valkey-check-aof.c` header-validation
path so the `len` and `checksum` values are each matched exactly once, consume
the full numeric token, and reject duplicate or non-numeric trailing content.
Update the logic around the `#HDR:v1` handling to fail closed whenever `len` or
`checksum` is missing, duplicated, or malformed.

In `@tests/integration/aof-integrity.tcl`:
- Around line 151-183: The AOF integrity toggle test currently only verifies the
disabled marker and final reload, but it does not confirm that re-enabling
integrity starts a new chain. In the test case in aof-integrity.tcl, after
calling CONFIG SET aof-integrity-check yes and writing key c via the same valkey
client, inspect the incr AOF file again and assert that a new `#HDR`:v1 header
appears before the SET c 3 entry. Use the existing ai_path, $rd, and the test
block around the dynamic toggle flow to locate the right spot, and keep the
final restart assertions unchanged.
- Around line 224-251: The current integration test in aof-integrity.tcl only
covers checksum corruption, but it does not exercise the new valkey-check-aof
path for commands missing an integrity header. Extend the existing test around
valkey-check-aof to append a raw RESP command without the `#HDR` header and run
the tool against the same manifest, then assert the CLI reports the
missing-header error. Use the existing helpers and symbols already in this test,
such as start_server, get_last_incr_aof_path, and valkey-check-aof, so the new
case stays in the same end-to-end integration flow.

In `@valkey.conf`:
- Around line 1725-1733: Document the runtime toggle semantics for
aof-integrity-check next to the existing checksum explanation: note that
inserting `#INTEGRITY_OFF` disables integrity recording, re-enabling starts a new
checksum chain, and an AOF may contain mixed protected and unprotected regions
until a rewrite. Update the directive’s surrounding comments in valkey.conf so
operators can understand the behavior they need to reason about.

---

Outside diff comments:
In `@src/aof.c`:
- Around line 1819-1865: The integrity check in the AOF command parsing flow
only validates the command header at the start of the RESP frame, so malformed
bulk lengths can extend past integrity_validated_until and still be parsed;
update the logic in the AOF reader loop to verify the full RESP command range
before accepting it. Use the existing parsing path around the integrity check,
argc handling, and the per-argument fread/strtol processing to compute the total
bytes for the command and reject it if any part would fall outside the validated
range.
πŸͺ„ Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7a8aee5f-01be-4932-804f-e6de6cb0bef8

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 5b690ce and 107ca45.

πŸ“’ Files selected for processing (10)
  • src/aof.c
  • src/config.c
  • src/rdb.c
  • src/server.c
  • src/server.h
  • src/valkey-check-aof.c
  • src/valkey-check-rdb.c
  • tests/integration/aof-integrity.tcl
  • tests/support/aofmanifest.tcl
  • valkey.conf

Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
Comment thread src/valkey-check-aof.c Resolved
Comment thread tests/integration/aof-integrity.tcl Resolved
Comment thread tests/integration/aof-integrity.tcl Resolved
Comment thread valkey.conf Resolved
@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch 2 times, most recently from 1a7116f to b65c440 Compare June 30, 2026 21:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

πŸ€– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/aof.c`:
- Line 134: The touched blocks in aof.c have whitespace-only formatting drift
that is causing the clang-format-18 CI check to fail. Reformat the affected
sections using clang-format-18 and ensure the edits around the mentioned aof.c
regions are purely style-aligned, with no logic changes, so the file matches the
repository’s C formatting rules.
- Around line 364-366: Replay logic in loadSingleAppendOnlyFile() and its
manifest parsing path currently records AOF_MANIFEST_KEY_FILE_CHECKSUM but never
validates finalized INCR entries against server.aof_running_checksum after the
file is loaded. Update the AOF manifest handling in src/aof.c to track whether a
checksum field was present for each entry, then in the replay flow compare
checksum-bearing non-last INCR files immediately after
loadSingleAppendOnlyFile() and reject mismatches before continuing with later
entries.
- Around line 2853-2855: The AOF rewrite completion path in aof.c is incorrectly
using the current server.aof_integrity_check toggle to decide whether to persist
server.aof_rewrite_base_checksum, which can break temp-INCR chaining after a
mid-rewrite integrity toggle. Update the BGREWRITEAOF/rewrite flow around the
code that writes the manifest and finalizes the rewrite so the base checksum is
preserved based on the state when the rewrite started, or explicitly abort and
restart the rewrite if integrity is disabled while in AOF_WAIT_REWRITE. Make
sure the logic in the rewrite completion and manifest emission paths uses the
rewrite-start state consistently, not the live toggle at completion.
- Around line 1837-1840: The integrity check in aof.c only verifies after the
RESP array header has been parsed, so a truncated or crafted block can leave
bulk lengths/data outside the validated range while still being loaded. Update
the command-loading path around the RESP parsing in the AOF loader (the
integrity header check near the command read loop) so the entire RESP command is
confirmed to fit within the checksummed block before any part is accepted or
executed. Make the same boundary validation apply to the later bulk-read
handling in the command parser path that covers the affected command read range,
using the existing integrity markers like integrity_validated_until and the AOF
loader logic.
- Around line 314-316: The integrity-field parsing in the AOF manifest/header
paths is too permissive because `strtoull(..., NULL, 10)` accepts prefixes and
malformed trailing content. Update the parsing in `src/aof.c` for the manifest
checksum line, the manifest `checksum` key, and the `#HDR:v1` `len:`/`checksum:`
fields to match the stricter checks used by `src/valkey-check-aof.c`, validating
delimiters and rejecting any trailing junk or overflow instead of accepting
partial parses.
πŸͺ„ Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2600430a-b81d-4a17-9322-2161e351e045

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 107ca45 and 1a7116f.

πŸ“’ Files selected for processing (10)
  • src/aof.c
  • src/config.c
  • src/rdb.c
  • src/server.c
  • src/server.h
  • src/valkey-check-aof.c
  • src/valkey-check-rdb.c
  • tests/integration/aof-integrity.tcl
  • tests/support/aofmanifest.tcl
  • valkey.conf
βœ… Files skipped from review due to trivial changes (1)
  • src/valkey-check-rdb.c
🚧 Files skipped from review as they are similar to previous changes (8)
  • tests/support/aofmanifest.tcl
  • src/rdb.c
  • valkey.conf
  • src/server.c
  • tests/integration/aof-integrity.tcl
  • src/server.h
  • src/config.c
  • src/valkey-check-aof.c

Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
Comment thread src/aof.c Resolved
@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch from b65c440 to bf78b71 Compare June 30, 2026 22:33
Comment thread src/aof.c Outdated
if (server.aof_integrity_check) {
uint64_t checksum = 0;
char hdr_prefix[64];
int prefix_len = snprintf(hdr_prefix, sizeof(hdr_prefix), "#HDR:v1;len:%zu;", sdslen(server.aof_buf));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Variadic functions, like snprintf, should be avoided in the critical path due to the additional overhead associated with parsing the format string at runtime, which is relatively slow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated. Ptal.

Comment thread src/aof.c
server.aof_integrity_chain_active = 0;
server.aof_running_checksum = 0;
}
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In case the aof integrity check was enabled on the server generating the aof file and also on the server loading it, the aof header could be corrupted but the header integrity check is skipped. We may want to introduce another configuration to allow loading an aof file only if it contains a valid integrity check header.

@zuiderkwast

Copy link
Copy Markdown
Contributor
  • Decision was to move the running checksum into the manifest.

@madolson (Sorry if this is outdated) If we move it to the manifest, don't we need to fsync both files on every write to keep them in sync?

@sumitk163

sumitk163 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Decision was to move the running checksum into the manifest.

@madolson (Sorry if this is outdated) If we move it to the manifest, don't we need to fsync both files on every write to keep them in sync?

This discussion was for storing the last running checksum for the AOF snapshot on AOF rewrite. When we perform AOF rewrite, the historical incremental logs are deleted, so we need to store the last running checksum corresponding to the last entry when the snapshot is taken.

Originally, I was storing the last running checksum as RDB aux field. However, that solution doesn't work when aof-use-rdb-preamble is false. Hence, the suggestion was to store the last running checksum for the base and incremental files in AOF manifest. This is done only when creating a new incremental file. So, we don't need to fsync both files on every write.

I updated the code based on the suggestion.

@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch 2 times, most recently from 64ac068 to b73ce2d Compare July 7, 2026 22:13
@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch 7 times, most recently from 55cc397 to 37d9b34 Compare November 13, 2026 04:08
Introduces AOF integrity verification using metadata headers with block length and running CRC64 checksums to protect against bit rot, torn writes, and missing log entries. Includes valkey-check-aof updates and integration tests.

Signed-off-by: sumitk163 <sumitk.163@gmail.com>
Signed-off-by: sumitk163 <sumitk.163@gmail.com>
Signed-off-by: sumitk163 <sumitk.163@gmail.com>
- Replace hardcoded ./src/valkey-check-aof with $::VALKEY_CHECK_AOF_BIN in aof-integrity.tcl to support builds where the binary is not in src/ (e.g. CMake builds).
- Fix minor formatting (trailing newline) in valkey-check-rdb.c.

Signed-off-by: sumitk163 <sumitk.163@gmail.com>
Introduces a design document (design-docs/aof-header-spec.md) detailing the formal grammar (ABNF), versioning, extensibility, and format rationale (text vs binary/Base64) for the AOF metadata header.

Signed-off-by: sumitk163 <sumitk.163@gmail.com>
Integrity model:
- Integrity is a property of each AOF file, recorded in the manifest
  ("integrity 1"). The writer adds headers based on the current INCR file,
  not the config.
- CONFIG SET aof-integrity-check schedules an AOF rewrite, and the new
  setting applies to the files it creates. It can't be changed while the
  AOF is loading. At startup with integrity enabled, if the last INCR file
  was written without it, a new INCR file is opened, and the AOF is
  rewritten while any file lacks integrity, e.g. after upgrading an old
  AOF or after a failed rewrite.
- The checksum chain continues across INCR files and rewrites, and the
  writer restarts it after a file without integrity, as the loader does.
  The base's starting checksum is recorded based on the INCR file opened
  at the start of the rewrite, not on the config when the rewrite
  completes.
- With aof-integrity-check disabled, files are loaded without being
  verified, and the last INCR file, whose end isn't verified, is no longer
  treated as an integrity file. Writes continue in it without headers.
  Loading without verification keeps the writer's running checksum.

Loading:
- Headers are required from the first byte of an integrity file.
- Each command must end inside its verified block. With integrity, the
  file is only truncated at the end of a verified block, and incomplete
  data inside a verified block is reported as corruption. A verified file
  that isn't the last one is never truncated, and an empty base written
  with integrity is an error.
- The checksum of a block covers the whole block, header included, except
  its own value, so header fields can come in any order.
- A single header parser, shared with valkey-check-aof, matches keys
  exactly, rejects a duplicate len or checksum, parses len strictly,
  ignores unknown fields, rejects control characters and reports
  unsupported versions. A block longer than the rest of the file is
  handled as a short read.
- Integrity errors include the byte offset, and suggest disabling
  aof-integrity-check to load the AOF without verification. When the
  first block of a file fails, the error says the file before it may be
  missing blocks at its end.
- A verified block of up to 1 MB is read from the file only once: it's
  checked in memory and then read from there. Larger blocks are read again
  after the check. Files without integrity are read as before.

Base file:
- A RESP base written with integrity ends with a #CRC line holding the
  CRC64 of everything before it, which is verified while loading.
- An RDB base (plain or streaming-compressed) has its checksum written and
  verified even when rdbchecksum is disabled. Written with integrity, it
  has nothing after the RDB, which its checksum wouldn't cover.

Manifest:
- The manifest checksum line is written whenever any file uses integrity,
  is parsed leniently, and must be the last line.
- Checksum values are parsed strictly, and an unknown integrity value is
  rejected.

valkey-check-aof:
- Always verifies integrity metadata, including the manifest checksum.
- Reports integrity errors through the same path as RESP errors, so --fix
  truncates the last file, at a block boundary. --truncate-to-timestamp
  truncates at the start of the block that contains the timestamp.
- Checks the CRC of a RESP base, and that nothing follows the RDB of an
  RDB base written with integrity.
- After a manual edit of the manifest, --fix can update its checksum, once
  the files are checked, also in the same run as a truncation.
  --truncate-to-timestamp reports the commands it truncates before the
  timestamp. Integrity errors, also at the --fix prompt, suggest loading
  the AOF with aof-integrity-check disabled as an alternative to --fix.

Write path:
- aofWrite() wraps aofWritev(), the running checksum is only updated once
  a block is on disk, and a pending retry buffer is written first.
- A rewrite is refused while AOF data couldn't be written yet, a partly
  written block or data in the AOF buffer, and that counts as a rewrite
  failure. A write error that has cleared doesn't block it.
- The retry buffer is counted like the AOF buffer in memory accounting and
  INFO, and released once written. Failing to write it is logged.

Other:
- Start a new chain when a primary's RDB is reused as the AOF base.
- The header spec describes integrity files, the manifest keys and the
  checksum chain. valkey.conf documents the overhead and the downgrade
  path, including starting this version once after an unclean shutdown.
- Skip annotations in the read_from_aof test helper.
- Add integration tests (including replication, enabling AOF at runtime, a
  failed rewrite, DEBUG LOADAOF, config changes while loading, empty bases
  and data after an RDB base), a Tcl CRC64 helper, and unit tests for the
  header parser.

Signed-off-by: sumitk163 <sumitk.163@gmail.com>
@sumitk163
sumitk163 force-pushed the aof-metadata-integrity branch from 6005db4 to 2bee0f2 Compare November 17, 2026 06:15

@murphyjacob4 murphyjacob4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks Sumit! Looks about ready

Comment thread src/aof.c
@@ -825,6 +997,14 @@ int openNewIncrAofForAppend(void) {
}
server.aof_fd = newfd;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In this function we fsync the manifest that names the new INCR file (persistAofManifest() above) before the old INCR file is fsynced (the background fsync and close just above this line). With everysec, I think a power loss in that window could leave the old file short while it is no longer the last file.

With integrity on, that load always fails ("ends unexpectedly, but it isn't the last AOF file"), and valkey-check-aof --fix won't truncate a non-last file. So the only way out would be aof-integrity-check no.

Should we fsync the file being closed before persisting the manifest when integrity is active? It would be one extra fsync per rewrite start.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

IIUC, this issue exists even without integrity, right? When appenfsync is set to everysec or no, and the manifest is fsync'd with the new incr file. Then, a torn write to the old incr file will fail the load.

I am not sure if issung an fsync is the best idea. With appenfsync no, we may have up to 30s of writes that didn't flush. So, it may cause stalls every time aof rewrite happens.

Probably, a better fix would be to update the loader so that it still allows truncation of a file if the next incr file is empty. And that fix will be regardless of the integrity setting. But we should add that fix in a separate PR. wdyt?

Comment thread src/rdb.c Resolved
Comment thread src/config.c Resolved
Comment thread src/aof.c
server.aof_fd = newfd;
/* The new INCR file starts a new chain after the new base. */
server.aof_running_checksum = 0;
server.aof_integrity_active = server.aof_integrity_check;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With integrity on, the base we adopt from the primary is left without the integrity flag.

If the RDB has a non-zero checksum, could we mark the base as protected instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

Comment thread src/aof.c

/* The checksum covers the whole block except its own value. The running
* checksum is only updated once the block is on disk, see below. */
checksum = crc64(server.aof_running_checksum, (unsigned char *)hdr, p - hdr);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Just curious, did we consider CRC32C here? Since the algorithm is part of v1 it would need a version bump to change later. If you haven't tried it, might be worth a shot, I think the performance is probably better, and since we do it on the main thread, could save a few percentage points of throughput. CRC32C seems to be industry standard in RocksDB, Kafka, Postgres, etcd, etc...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We already use CRC64 for RDB checksum and we don't have a vendored CRC32 in the repo. We would need to add that. I recommended against it in #4201 maily to have fewer dependencies.

CRC64 can be made fast (faster than the vendored one) with some modern SIMD instructions like PCLMULQDQ. I believe CRC32 can be equally fast but I have no proof.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, I had actually run some quick benchmarks with crc32 earlier, but the performance came out to be worse than crc64, probably since we have added some optimizations for crc64 computation in Valkey. AI agent suggested that even if we optimised crc32, we may not get better performance than crc64 on most platforms. So, I abandoned that idea. 1 reason why this may still be considered in the future is to reduce the header size overhead a little bit, although the gains may not be much.

Ack to Viktor's suggestion to minimize dependencies if we don't see significant value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Actually, earlier I had tested only with crc32 and not with crc32c. Based on some quick tests, crc32c is significantly more performant than crc32. I will try adding some optimisations to crc64 (as Viktor suggested) and compare the performance with crc32c next.

We can probably pursue this potential change in a follow up PR. I believe it should be ok to update the header spec until Valkey 10 launch, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I asked the AI agent to run some benchmarks. Here are the results

1. Raw checksum throughput

Block size Current crc64 (crcspeed) crc64 (PCLMULQDQ, 128-bit) crc64 (VPCLMULQDQ, 256-bit) CRC32C (1-way SSE4.2) CRC32C (3-way SSE4.2 + PCLMUL)
64 B 1.59 GB/s 4.26 GB/s 4.27 GB/s 7.34 GB/s 7.35 GB/s
256 B 1.63 GB/s 11.27 GB/s 12.59 GB/s 7.83 GB/s 7.81 GB/s
1 KB 1.65 GB/s 11.65 GB/s 22.11 GB/s 7.94 GB/s 14.65 GB/s
4 KB 2.37 GB/s 11.92 GB/s 23.48 GB/s 7.99 GB/s 18.73 GB/s
16 KB 2.54 GB/s 11.89 GB/s 23.49 GB/s 7.98 GB/s 20.15 GB/s
64 KB 3.16 GB/s 11.68 GB/s 23.79 GB/s 7.99 GB/s 19.94 GB/s
1 MB 3.40 GB/s 11.81 GB/s 23.50 GB/s 7.97 GB/s 20.11 GB/s

2. End-to-end valkey-server impact

AOF write throughput (valkey-benchmark -t set, appendonly yes, appendfsync everysec; server and benchmark pinned to separate physical cores, median of 5 interleaved trials):

Build / Mode SET 64 B (-P 1) SET 64 B (-P 16) SET 1 KB (-P 16)
aof-integrity-check no 51.5k rps 491.7k rps 348.9k rps
aof-integrity-check yes β€” Current crc64 52.2k rps (+1.3%) 475.3k rps (βˆ’3.3%) 320.3k rps (βˆ’8.2%)
aof-integrity-check yes β€” PCLMULQDQ crc64 (128-bit) 50.4k rps (βˆ’2.2%) 479.0k rps (βˆ’2.6%) 333.6k rps (βˆ’4.4%)
aof-integrity-check yes β€” VPCLMULQDQ crc64 (256-bit) 51.9k rps (+0.7%) 483.7k rps (βˆ’1.6%) 331.3k rps (βˆ’5.0%)
aof-integrity-check yes β€” CRC32C (SSE4.2 + PCLMUL) 49.6k rps (βˆ’3.8%) 481.3k rps (βˆ’2.1%) 339.9k rps (βˆ’2.6%)

Startup load time (200k Γ— 1 KB keys: 203.9 MB AOF / 199.1 MB RDB, pinned to one physical core, median of 5 interleaved trials):

Build / Mode AOF load RDB load
Checksum disabled (aof-integrity-check no / rdbchecksum no) 512 ms* 415 ms
Current crc64 (crcspeed) 424 ms 583 ms
PCLMULQDQ crc64 (128-bit) 378 ms (βˆ’10.8% vs current) 436 ms (βˆ’25.2% vs current)
VPCLMULQDQ crc64 (256-bit) 374 ms (βˆ’11.8% vs current) 436 ms (βˆ’25.2% vs current)
CRC32C (SSE4.2 + PCLMUL) 373 ms (βˆ’12.0% vs current) 431 ms (βˆ’26.1% vs current)

*AOF load with aof-integrity-check no is slower than yes here because verified blocks (up to 1 MB) are read into memory in one fread and parsed from RAM, whereas no issues per-argument fgets/fread calls on FILE*.

One thing to note is that once aof writes are moved to the bio thread, the crc computation will also move to the bio thread, so the impact of crc computation on throughtput should be further reduced after that.

I will start a separate issue / PR to close on whether we want to use crc32c (follow up to this PR)

Comment thread src/aof.c
* feedAppendOnlyFile() to issue a SELECT command. */
server.aof_selected_db = -1;
flushAppendOnlyFile(1);
if (sdslen(server.aof_retry_buf) > 0 || sdslen(server.aof_buf) > 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we drop this here since we have it in #5350 ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I kept it here too since I think some test was failing without it. If we can merge 5350 soon, I can rebase this PR and we remove this diff. Would that be ok?

Comment thread src/aof.c

/* Whether the INCR file being closed has integrity, for the new file's chain. */
listNode *last_node = listLast(temp_am->incr_aof_list);
if (last_node && ((aofInfo *)listNodeValue(last_node))->integrity) closing_integrity = 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we record the running checksum on a closing file's manifest line in openNewIncrAofForAppend()? We already persist the manifest there.

It would let each closed file be verified from the manifest alone. Also, right now, the end of a closed INCR file is only checked by the first block of the next file. If the next file is empty (no writes since the rewrite started) or was written without integrity, blocks lost from the end of the closed file load without an error. It is a narrow edge case, but if we seal the file with the final checksum in the manifest, it should close it and any similar bugs in the future.

Feel free to punt to a follow-up, but it might be nice to reserve the manifest key now

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, I had done that originally, but later reverted that change since it was adding some complexity without much benefit. If we add the running checksum in the manifest too, it introduces scenarios where there could be a mismatch in the checksum flushed to the incr file vs checksum flushed to the manifest, especially with fsync never and everysec policies. We would need to call fsync on the incr file even when fsync never is set to synchronize them. So, I decided against adding this.

As you said, we can consider adding it in a follow up PR if the need for it arises. The manifest key already exists "checksum" which we use for the base file today.

Comment on lines +124 to +127
## 6. Versioning and Extensibility

- **Versioning**: The version token (e.g., `v1`) defines the strict grammar. If a breaking change is made (e.g., changing the checksum algorithm), the version MUST be bumped to `v2`. A loader verifying a file MUST fail on an unknown version.
- **Extensibility**: Within a version (e.g., `v1`), the parser MUST ignore any unrecognized fields. This allows a server running only integrity checks to safely skip `replid` and `reploff` fields, ensuring forward compatibility.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You added #HDR as an annotation, so that it will be silently skipped in older versions, but if we bump to v2 in the future, a v1-compatible server will fail loudly? What's the reasoning here? Why not skip the whole annotation for #HDR:v2 and higher unknown versions?

Regarding changing the CRC algorithm (discussed in one of the threads on this PR) I suppose we could introduce a new field named e.g. crc32 and omit the checksum field without bumping the version. This follows from the "extensibility" rule. A node that doesn't understand crc32 will simply skip the checksum verification then.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, my original thought process was that when aof-integrity-check is enabled on a Valkey version that supports this config, we should ensure that integrity check is performed on load. So, if someone is loading a newer AOF version (say v2) on an older Valkey version that doesn't support that version, then the user should explicitly disable aof-integrity-check during load. So that we don't silently skip integrity validation and the user if aware of the behavior. Wdyt?

Similarly for the crc discussion. My consideration is that should we have some guarantees when aof-integrity-check is enabled - that integrity check will never be skipped unless the user explicitly disables the config (instead of silently skipping).

@sumitk163 sumitk163 Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thinking a bit more about this, the header will contain other fields like replication info too. And it's possible for a user to opt in for replication info but not for integrity. And in that, we can still load even if the header version is incompatible (we just lose the ability to psync, but that's alright). So, it doesn't seem ideal to reject unknown header versions, for backwards compatibility.

Let me update the spec so that unknown versions are simply ignored. But if aof-integrity-check is enabled, and we don't have checksums available in a compatible header version, we still fail the load (and add an error suggesting the user to disable aof-integrity-check). Would that be reasonable?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated so that a header with an unknown version is now skipped like any other annotation, and the spec says the same.
With aof-integrity-check enabled, the commands after such a header in an integrity file aren't covered by a verified header, so the load still fails and suggests disabling aof-integrity-check.

- Verify the checksum of an RDB base written with integrity even when
  it's zero, in the server and in valkey-check-aof. The writer always
  computes it for such a base, so zero doesn't mean the checksum was
  disabled.
- Retry a failed AOF rewrite while integrity is enabled and some AOF
  file was written without it, as at startup. Retries are rate-limited
  like other failed rewrites.
- Mark the base reused from a replica full sync as written with
  integrity when it's a plain RDB with a checksum, so a restart doesn't
  need to rewrite the AOF.
- Skip a header with an unknown version like any other annotation, and
  say so in the spec. In a verified file, the commands after it then
  lack a header, which is an error.

Signed-off-by: sumitk163 <sumitk.163@gmail.com>

@murphyjacob4 murphyjacob4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @sumitk163! I'm ready to merge this. Decision was approved in a previous TSC meeting (see #3515)

@murphyjacob4

Copy link
Copy Markdown
Contributor

@zuiderkwast, you have also been reviewing, did you want to approve as well? Or you are okay if I merge

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

Labels

major-decision-approved Major decision approved by TSC team

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

AOF integrity checks

7 participants