Repository navigation
Conversation
| if (!cksum_tag) { | ||
| serverLog(LL_WARNING, "AOF integrity header in %s lacks a checksum", filename); | ||
| goto fmterr; | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Thanks for catching this, fixed.
| off_t current_pos = ftello(fp); | ||
|
|
||
| size_t remaining = h_len; | ||
| unsigned char check_buf[16 * 1024]; |
There was a problem hiding this comment.
Same dead if (cksum_tag) guard as in aof.c.
| if (server.aof_integrity_check && sdslen(buf) > 0) { | ||
| server.aof_lsn++; | ||
| char hdr_prefix[128]; | ||
| int hdr_prefix_len = |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Makes sense, updated the naming as suggested.
| 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); |
There was a problem hiding this comment.
"AOF short write detected" β this is during loading, so it should be "short read". Same in valkey-check-aof.c.
|
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. |
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? |
|
@madolson I updated the header to use a running checksum instead of using an lsn and per-log checksum. Ptal. |
Codecov Reportβ Patch coverage is
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
π New features to boost your workflow:
|
| 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; |
There was a problem hiding this comment.
should we cap this somehow? since we read this directly from file something like len:SUPERBIGNUMBER could have us spinning forever no?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
(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.
There was a problem hiding this comment.
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.
| 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)); |
There was a problem hiding this comment.
do we need to guard against a value of this greater than 128?
There was a problem hiding this comment.
Added an assertion to ensure the header fits within the allocated space.
| } else if (!strcasecmp(objectGetVal(auxkey), "aof-checksum")) { | ||
| server.aof_running_checksum = strtoull(objectGetVal(auxval), NULL, 10); |
There was a problem hiding this comment.
should this be guarded by the config too
There was a problem hiding this comment.
Good catch, added.
| 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)) { |
There was a problem hiding this comment.
should we change the condition to >= 9 ?
VALKEY009
^^^^^^~~~
6 bytes magic + 3 bytes version = 9 bytes minimum
There was a problem hiding this comment.
Thanks for catching this, fixed.
|
High level review notes:
|
5080701 to
d463e33
Compare
|
From the OSS core team meeting:
|
d463e33 to
4835c75
Compare
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Pre-merge checks:
|
4835c75 to
107ca45
Compare
There was a problem hiding this comment.
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 winValidate 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
π Files selected for processing (10)
src/aof.csrc/config.csrc/rdb.csrc/server.csrc/server.hsrc/valkey-check-aof.csrc/valkey-check-rdb.ctests/integration/aof-integrity.tcltests/support/aofmanifest.tclvalkey.conf
1a7116f to
b65c440
Compare
There was a problem hiding this comment.
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
π Files selected for processing (10)
src/aof.csrc/config.csrc/rdb.csrc/server.csrc/server.hsrc/valkey-check-aof.csrc/valkey-check-rdb.ctests/integration/aof-integrity.tcltests/support/aofmanifest.tclvalkey.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
b65c440 to
bf78b71
Compare
| 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)); |
There was a problem hiding this comment.
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.
| server.aof_integrity_chain_active = 0; | ||
| server.aof_running_checksum = 0; | ||
| } | ||
| continue; |
There was a problem hiding this comment.
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.
@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. |
64ac068 to
b73ce2d
Compare
55cc397 to
37d9b34
Compare
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>
37d9b34 to
7f0b662
Compare
373563b to
f9f4369
Compare
0c7f99e to
6005db4
Compare
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>
6005db4 to
2bee0f2
Compare
murphyjacob4
left a comment
There was a problem hiding this comment.
Thanks Sumit! Looks about ready
| @@ -825,6 +997,14 @@ int openNewIncrAofForAppend(void) { | |||
| } | |||
| server.aof_fd = newfd; | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
| 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; |
There was a problem hiding this comment.
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?
|
|
||
| /* 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); |
There was a problem hiding this comment.
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...
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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)
| * 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) { |
There was a problem hiding this comment.
Should we drop this here since we have it in #5350 ?
There was a problem hiding this comment.
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?
|
|
||
| /* 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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| ## 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Thanks @sumitk163! I'm ready to merge this. Decision was approved in a previous TSC meeting (see #3515)
|
@zuiderkwast, you have also been reviewing, did you want to approve as well? Or you are okay if I merge |
This PR adds AOF integrity verification, which protects against bit rot, torn writes and missing log entries. With
aof-integrity-checkenabled, AOF files carry checksums that the server verifies when loading.How it works
#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.rdbchecksum no. A RESP base (aof-use-rdb-preamble no) ends with a#CRC:<crc64>line covering the rest of the file.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.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(defaultno). 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.
--fixtruncates the last file at a block boundary, and--truncate-to-timestamptruncates at the start of the block that contains the timestamp. After a manual edit of the manifest,--fixcan also update the manifest checksum.Changes with the feature disabled
#TS:) is now treated as a short read: it's truncated withaof-load-truncated yes, and fails the load otherwise. Before, it was skipped, and the next write was glued onto it, so the following restart failed. Treat a torn annotation at the end of an AOF file as a short readΒ #5349Tests
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, enablingappendonlyat runtime,DEBUG LOADAOF, replication full sync (disk-based and diskless), manifest validation, base protection (RESP#CRC, RDB withrdbchecksum no, LZ4), and valkey-check-aof (--fix,--truncate-to-timestamp).src/unit/test_aof_header.cpp.aof-integrity-checkdefaulting toyes, 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.Loading
INCR files written with integrity, then loaded with
aof-integrity-checkon (verified) and off (headers skipped).SET, 64 B values, 50 clients (~1.4M blocks)-P 32)SET, 4 KB valuesVerified 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
With data size 10KB: The flamegraph shows that 8.28% cpu cycles are spent on crc computation.
Follow-ups
Closes #3885