Repository navigation
[MOD-17512] Fix unloadable RDB from leftover pre-2.0 index keys breaking replication, backups and exports - #10817
Conversation
Follow-up on the initial zero-byte-save fix: - Use RS_ASSERT_ALWAYS, not RS_ASSERT, in the three legacy rdb_save callbacks. Writing an empty payload over a value that is not the sentinel would silently discard real data, so release builds must crash rather than corrupt. The original bug existed precisely because RS_ABORT compiles to a no-op without ENABLE_ASSERT; repeating that pattern on the same path would hide the next one. - Give the legacy types their own no-op aof_rewrite handler. The shared GenericAofRewrite_DisabledHandler calls abort(), so AOF rewrite crashed any shard still holding legacy keys. A legacy key carries no data, so emitting no commands is both safe and desirable: the husk does not come back on replay. - Drop the now-unused util/misc.h include. - test_cpp_rdb: round-trip each legacy type's dummy value through the mock RDB IO, asserting the payload is non-empty, the loader returns the sentinel, no IO error is raised, and the loader consumes exactly the bytes written. Fails on a zero-byte save. Numeric is also covered under the v0 framing, since its loader selects the wire format from encver. - test_rdb_compatibility: assert the upgrade sweep leaves no legacy module-type keys behind, and dump-and-reload each upgraded fixture so the save path is exercised and not just the load path. Co-Authored-By: Claude Opus 5 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #10817 +/- ##
==========================================
- Coverage 82.91% 82.07% -0.84%
==========================================
Files 606 632 +26
Lines 80584 81910 +1326
Branches 35535 36927 +1392
==========================================
+ Hits 66817 67229 +412
- Misses 13427 14341 +914
Partials 340 340
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
These loaders are reachable from RESTORE, so every count they read is attacker-controlled. Once the stream is exhausted the Load* calls return 0 without consuming anything, so a counted loop kept iterating the declared number of times: a truncated payload declaring UINT64_MAX entries spun the server. numericdx v0, ft_invidx block counts and ft_tagidx tag counts all had this shape. - Stop every counted loop on RedisModule_IsIOError, and return NULL on error so a corrupt payload cannot materialize a key. - Add the missing encver guard to TagIndex_RdbLoad_Consume. Redis matches a module type on its 54-bit signature and ignores the 10-bit encoding version, so a crafted RESTORE could reach it with any encver. - Propagate the nested InvertedIndex_RdbLoad_Consume failure in the tag loader instead of discarding it. - Tests: truncated-huge-count and unknown-encver rejection for all three types. - Document why the AOF handler emits nothing: a replayable RESTORE would need a full DUMP envelope that no module API can build, and deleting the key is not possible from the forked AOF child. The resulting command-AOF vs RDB-preamble divergence is noted in the code. Co-Authored-By: Claude Opus 5 <[email protected]>
…them The previous change emitted no commands, on the mistaken premise that recreating the key was impossible. It is not: DUMP produces the envelope, so the module never has to build one. deps/rmutil/util.c has done this for years in RMUtil_DefaultAofRewrite, which is dead code here. Emit DUMP -> RESTORE so a command-only AOF and an AOF with an RDB preamble agree: both keep the key. Without this, whether the key survives depends on which AOF format is in use, so a live replica and a pure-AOF-restarted master diverge on EXISTS/TYPE/DBSIZE/TTL. Select the IO's database first. A detached thread-safe context starts on DB 0, which is why RMUtil_DefaultAofRewrite cannot be reused verbatim. Also corrects the reasoning in the previous commit message: the shared GenericAofRewrite_DisabledHandler calls abort() inside the forked rewrite child, so it kills that child and leaves the AOF unable to rewrite - it does not crash the shard parent. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 69de43cf84
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (rep != NULL && RedisModule_CallReplyType(rep) == REDISMODULE_REPLY_STRING) { | ||
| size_t n = 0; | ||
| const char *payload = RedisModule_CallReplyStringPtr(rep, &n); | ||
| RedisModule_EmitAOF(aof, "RESTORE", "slb", key, 0, payload, n); |
There was a problem hiding this comment.
Pass a long long for the RESTORE TTL
When a command-only AOF rewrite encounters a legacy key on an ABI where variadic int and long long arguments occupy different layouts (notably 32-bit builds), the l format consumes a long long but this call supplies the int literal 0. This is undefined behavior and can consume part of the following payload pointer as the TTL, shifting the remaining arguments and corrupting or crashing the rewrite. Pass 0LL (or an explicitly typed long long) so the argument matches the l specifier.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in efd15c0 — now 0LL. You are right that "l" consumes a long long and a bare 0 is an int, so the call was undefined behaviour on any ABI where variadic int and long long are laid out differently.
| // A detached context starts on DB 0, but the key lives in whichever database is being rewritten. | ||
| RedisModule_SelectDb(ctx, RedisModule_GetDbIdFromIO(aof)); | ||
|
|
||
| RedisModuleCallReply *rep = RedisModule_Call(ctx, "DUMP", "s", key); |
There was a problem hiding this comment.
Avoid serializing key metadata twice in AOF rewrites
When a legacy key has module key metadata on Redis 8.6+, DUMP embeds that metadata in the payload returned here, but Redis's command-only AOF rewrite subsequently invokes keyMetaOnAof() for the same key after this callback. Replaying the generated AOF therefore restores the metadata once through RESTORE and then executes its AOF reconstruction command a second time; metadata callbacks are not required to be idempotent, so this can duplicate side effects or make replay fail when the command expects the metadata to be absent. The emitted value needs a DUMP envelope that omits key metadata, leaving Redis's outer metadata rewrite to serialize it exactly once.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this, but recording why rather than dismissing it.
The mechanism is real — RedisModuleKeyMetaAOFRewriteFunc exists in redismodule.h, so a key-meta AOF hook can run alongside the value callback. What I cannot find is a path by which one of these keys acquires metadata: the only key-meta class RediSearch registers is the docId class in src/doc_id_meta.c, and it is attached to indexed documents. A legacy ft:<index>/<term>, nm: or tag: key is never an indexed document — it is a pre-2.0 index-internal key whose payload is discarded on load and whose value is the dummyNonNull sentinel. With no metadata attached, there is nothing for DUMP to embed or for a later hook to re-apply.
I also could not locate keyMetaOnAof in the Redis source available to me, though that is OSS unstable and key metadata looks Enterprise-side, so its absence there is not conclusive.
Flagging the residual honestly: if a legacy key can acquire key metadata on 8.6+, this becomes a real double-apply, and the only fix would be to stop using DUMP — which would remove the reason this callback exists (making a command-only AOF and an RDB-preamble AOF agree on whether the key survives). If someone familiar with the key-meta feature can confirm either way, that settles it.
The C++ tests drive the callbacks against a mock whose framing is not Redis's, so they prove save/load symmetry but not that the bytes we emit are valid Redis framing. These tests cross that boundary - Redis validates the module type id, the module EOF marker, the DUMP footer and the CRC for us. tests/pytests/test_legacy_module_types.py builds RESTORE payloads from first principles, since a legacy key can only be created by deserializing one. That is also how these keys reach production: Enterprise import forwards RESTORE rather than handing an RDB to Redis. testDumpPayloadHelperMatchesRedis guards the builder by checking our crc64 against a footer the server wrote, so a broken fixture fails one obvious test instead of all of them confusingly. Covered: round-trip through RESTORE/DUMP/RESTORE and a reload; malformed counts and unknown encvers rejected without creating a key; survival of an AOF rewrite under the command-only format, which is the only format that runs the aof_rewrite callback; and a DB 1 key with a colliding DB 0 name, which fails if the callback forgets to select the IO's database. Two fixes in that callback: - Assert RedisModule_SelectDb succeeded. Silently staying on DB 0 would dump a same-named, unrelated key. - Treat a NULL DUMP reply as an expired key and skip it, but fail the rewrite on any other reply. Warning and emitting nothing would install an AOF base missing the key, which is the divergence this callback exists to prevent; failing leaves Redis's previous base valid. Also record why there is no ThreadSafeContextLock here: the rewrite child inherits the module GIL already held. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 41c7dbd7ed
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| conn.execute_command('RESTORE', 'aof:' + type_name, 0, _dump_payload(conn, type_name, body)) | ||
|
|
||
| conn.execute_command('BGREWRITEAOF') | ||
| waitForRdbSaveToFinish(env) |
There was a problem hiding this comment.
Wait for the AOF rewrite before reloading it
Whenever the rewrite child has not finished by this call, waitForRdbSaveToFinish returns immediately because it only polls rdb_bgsave_in_progress in common.py, not aof_rewrite_in_progress or aof_rewrite_scheduled. DEBUG LOADAOF can therefore replay the previous AOF generation containing the original RESTORE commands before the rewritten base is installed, allowing both this test and the database-selection test below to pass even if LegacyType_AofRewrite aborts or emits the wrong payload. Wait explicitly for the AOF rewrite to finish before invoking DEBUG LOADAOF.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in efd15c0, and this was worse than described. waitForRdbSaveToFinish polls only rdb_bgsave_in_progress, so it returned immediately and neither AOF test ever waited at all — they were passing without exercising the wait. Replaced with a helper that polls aof_rewrite_in_progress and aof_rewrite_scheduled. Substituting a wait that actually inspects AOF state made both tests fail until the parsing was right, which is the confirmation that they had not been synchronising.
…lity-in-legacy-index-keys # Conflicts: # src/legacy_types.c
- Add the mandatory license header to the new test file. - Pass the RESTORE TTL as 0LL. EmitAOF's "l" specifier consumes a long long, so a bare 0 is undefined behaviour on any ABI that lays variadic int and long long out differently. - Stop using waitForRdbSaveToFinish for AOF rewrites. It polls only rdb_bgsave_in_progress, so it returned immediately and DEBUG LOADAOF could replay a rewrite that was still running or merely scheduled - the two AOF tests were passing without ever waiting. Poll aof_rewrite_in_progress and aof_rewrite_scheduled instead, and parse INFO from the dict redis-py's own response callback returns. - Map a unix-socket pool's `path` onto the client's `unix_socket_path`, so the binary connection helper also works under UNIX=1. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: efd15c03d8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (fields.get('aof_rewrite_in_progress', '0').strip() == '0' | ||
| and fields.get('aof_rewrite_scheduled', '0').strip() == '0'): | ||
| return |
There was a problem hiding this comment.
Check the AOF rewrite result before reloading
Fresh evidence after the earlier wait comment is that the newly added helper returns solely when both activity flags become zero, which also happens after the rewrite child fails. In that case, both AOF tests proceed to DEBUG LOADAOF, which replays the previous AOF generation containing the original RESTORE commands, so their assertions can still pass even if LegacyType_AofRewrite aborts or emits no usable rewrite. Check aof_last_bgrewrite_status == ok before returning so these tests fail when the rewrite itself fails.
AGENTS.md reference: AGENTS.md:L286-L286
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 800c267 — you were right, and the hole was worse than "can still pass": these tests create the keys with RESTORE, so those commands are already in the AOF. On a failed rewrite DEBUG LOADAOF replays the previous generation containing them, the keys come back, and the assertions pass no matter what LegacyType_AofRewrite emitted. The test was verifying nothing about the callback.
Now checks two things, because neither is sufficient alone:
aof_rewritesincrements at rewrite start —stat_aof_rewrites++sits immediately beforeredisForkinaof.c— so a change in it proves a rewrite actually began. The activity flags alone can read idle before it starts.aof_last_bgrewrite_statusis the only signal that it succeeded, which is the gap you identified.
Also folded BGREWRITEAOF into the helper so the baseline count cannot be captured too late.
Worth recording that this is the second time this test passed for the wrong reason: the first wait helper polled rdb_bgsave_in_progress and so never waited at all.
Move the loader hardening out. It fixed a real, separately reachable CPU denial of service - the three loaders trust attacker-controlled counts and a truncated payload declaring UINT64_MAX entries spins the server - but that is a distinct defect from the zero-byte save this PR exists to fix, and it deserves its own review rather than riding along. Reverted here: the RedisModule_IsIOError loop guards, the NULL-on-error returns, the tag loader's missing encver guard, and the propagation of its nested inverted-index failure, together with their four tests. The loaders are now byte-identical to master. Kept: the three per-type rdb_save callbacks that make a leftover legacy key serialize to something its own loader accepts, the DUMP -> RESTORE AOF rewrite that replaces a handler which aborts the rewrite child, and the round-trip coverage at both the callback and real-Redis layers. The DoS remains open on master until the hardening lands separately; the work is preserved on dor-mod15685-loader-hardening. Co-Authored-By: Claude Opus 5 <[email protected]>
Waiting for the activity flags to go idle also succeeds after a *failed* rewrite. DEBUG LOADAOF then replays the previous AOF generation - which in these tests still contains the RESTORE commands that created the keys - so the assertions passed regardless of what LegacyType_AofRewrite emitted. Check two things instead, because neither is sufficient alone: - aof_rewrites increments at rewrite start, just before Redis forks, so a change in it proves a rewrite actually began. The flags alone can read idle before it starts. - aof_last_bgrewrite_status is the only signal that it succeeded. Folding BGREWRITEAOF into the helper so the baseline count cannot be missed. Co-Authored-By: Claude Opus 5 <[email protected]>
Per review: instead of fabricating the smallest payload each loader happens to accept, say what is actually true - there is no payload - and stamp the record with a version the loader recognises. LEGACY_EMPTY_ENC_VER 2 is now the registered version for ft_invidx, numericdx and ft_tagidx, so records we write carry it. GenericType_EmptyRdbSave writes nothing, and each loader returns the sentinel immediately when it sees that version, consuming no bytes - which leaves Redis's module EOF marker exactly where it left it. Writing zero bytes under version 1 is precisely what corrupted the RDB: the loader then read a payload that was not there and ate the marker instead. Replaces three per-type savers with one, and removes the invented flags/lastId/numDocs/n_blocks zeros. Loading genuine 1.x records is unchanged. Redis passes the record's own encoding version to rdb_load with no ceiling check, so versions 0 and 1 still take the existing consume paths; a new test pins that. One consequence, deliberately accepted: an RDB written by this build carries version 2 for these types, and an older build's loader rejects anything above version 1, so it will refuse to load it. That matters only for reading new data with an older module - downgrade, a mixed-version replica, or restoring a new backup on an old build. The previous approach was interoperable both ways because it wrote a valid version 1 payload. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1b68ca281a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| RedisModuleCtx *ctx = RedisModule_GetThreadSafeContext(NULL); | ||
| // A detached context starts on DB 0, but the key lives in whichever database is being rewritten. | ||
| // Failing to switch would dump a same-named, unrelated key from DB 0. | ||
| RS_ASSERT_ALWAYS(RedisModule_SelectDb(ctx, RedisModule_GetDbIdFromIO(aof)) == REDISMODULE_OK); |
There was a problem hiding this comment.
Avoid the Redis 7-only DB-ID API on Redis 6.x
On supported Redis 6.x servers, RedisModule_GetDbIdFromIO is unavailable and its function pointer remains NULL, so rewriting an AOF containing any legacy key dereferences NULL here and kills the rewrite child. The AOF therefore continues growing—the failure this callback is intended to fix—unless this path uses an API available on Redis 6.x or provides a compatible fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Moot on two counts, so not changing anything — noting rather than dismissing.
The LegacyType_AofRewrite callback this refers to was removed in 876c595 when the PR was narrowed; .aof_rewrite is back to GenericAofRewrite_DisabledHandler and untouched.
The Redis 6.x premise also does not apply to master: supportedVersion in src/module.c is 8.4.0, and CheckSupportedVestion() fails module load below it.
Both are worth carrying forward though. If the AOF fix gets its own PR and is backported to a branch whose supportedVersion allows 6.x, RedisModule_GetDbIdFromIO being unavailable there is exactly the kind of thing that would bite it.
| // Register the inverted index type | ||
| tm.rdb_load = InvertedIndex_RdbLoad_Consume; | ||
| if (!RedisModule_CreateDataType(ctx, "ft_invidx", LEGACY_ENC_VER, &tm)) { | ||
| if (!RedisModule_CreateDataType(ctx, "ft_invidx", LEGACY_EMPTY_ENC_VER, &tm)) { |
There was a problem hiding this comment.
Keep legacy records readable by version-1 builds
During a rolling upgrade or restore to an older supported build, registering these types at encoding version 2 makes every newly saved or DUMPed legacy key unreadable by that build: its inverted/numeric loaders reject versions above 1, while its tag loader attempts to consume the EOF marker as payload. Preserve version-1 output with each loader's minimal valid body, or add an explicit compatibility gate and an old-reader test.
AGENTS.md reference: AGENTS.md:L13-L21
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Real, and confirmed against master rather than assumed — this needs a decision from @GuyAv46 rather than a unilateral change from me, since the design was his call.
Verified on the pre-PR code, and the tag case is worse than a clean rejection:
InvertedIndex_RdbLoad_Consume/NumericIndexType_RdbLoad_Consumereject withencver > LEGACY_ENC_VER→ return NULL → Redis reports "the responsible module is not able to load" and aborts the load. Loud, at least.TagIndex_RdbLoad_Consumeon master has no encver guard, so it reads the empty payload's first field — which is Redis's module EOF marker.io.erroris set,n_tagscomes back 0, the loop is skipped, and it still returns the non-NULL sentinel. Redis then looks for the marker that was already consumed and reports "not terminated by the proper module value EOF marker" — the exact error this PR exists to fix.
So new→old is not merely unsupported, it reproduces the original corruption for tag keys.
The two options are (a) accept it, on the basis that reading new data with an older module is out of scope, or (b) go back to writing a payload valid under version 1, which is interoperable both ways — rejected in review as fabricating data that does not exist. Recorded as a known gap in the PR description either way.
| deadline = time.time() + timeout | ||
| while time.time() < deadline: | ||
| fields = _infoPersistence(conn) | ||
| started = int(fields.get('aof_rewrites', '0')) > before |
There was a problem hiding this comment.
Do not wait on a Redis 7-only INFO counter
Fresh evidence beyond the earlier wait comments is that Redis 6.2 does not expose the aof_rewrites INFO field. Because this unskipped test defaults the missing field to 0 both before and after BGREWRITEAOF, started remains false and every AOF test waits the full 60 seconds before failing even if the rewrite completed; use a version-compatible start/completion signal or skip unsupported server versions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as the sibling comment: the helper this refers to went away with the AOF callback in 876c595, and master requires Redis 8.4 (supportedVersion in src/module.c), so the 6.2 aof_rewrites gap cannot be reached here.
Recording it for whoever revives the AOF change on a branch that does support 6.x — waiting on a counter that server never exposes would have burned the full timeout on every run.
Keep GenericType_DummyRdbSave under its own name. Renaming it was an artifact of the earlier design, where each type wrote a different fabricated payload and so needed its own saver. With LEGACY_EMPTY_ENC_VER all three write the same thing - nothing - so the original function is exactly right; only its body was ever wrong. The registration lines go back to being untouched. Drop LegacyType_AofRewrite and restore GenericAofRewrite_DisabledHandler, with its tests and helpers. Note what that gives up: that handler calls abort() inside the forked AOF rewrite child, so a database holding one of these keys still cannot complete an AOF rewrite and its AOF grows without bound. Separable from the RDB corruption this PR fixes, and now left for its own change. src/legacy_types.c is down to 25 insertions and 4 deletions: the new version constant, one line inside the saver, an early return in each of the three loaders, and the three registered versions. Co-Authored-By: Claude Opus 5 <[email protected]>
Two review points from @GuyAv46. Use RS_ASSERT rather than RS_ASSERT_ALWAYS in the saver. The _ALWAYS form was justified when RS_ABORT compiling away *was* the bug - the function then wrote nothing, and writing nothing was wrong. Now writing nothing is correct, so the assertion is not load-bearing: it only guards a value that the loaders never produce. Crashing a production shard for that is the wrong trade. Put the error path first in all three loaders and track the latest encoding version. The previous order worked but left a guard reading "reject anything above version 1" while version 2 was valid - the same kind of stale-constant trap that caused this bug. TagIndex_RdbLoad_Consume had no ceiling guard at all and now gets the same shape as the other two. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 92dfef7d74
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def _binary_conn(env, db=None): | ||
| """A connection that does not decode replies. DUMP returns arbitrary bytes, which the default | ||
| RLTest client tries to decode as UTF-8.""" | ||
| kwargs = dict(env.getConnection().connection_pool.connection_kwargs) |
There was a problem hiding this comment.
Preserve TLS when cloning the test connection
Fresh evidence beyond the Unix-socket fix is that, when RLTest runs with TLS enabled, the source pool uses SSLConnection, but connection_kwargs does not retain the ssl=True selector. Reconstructing redis.Redis from this dictionary therefore selects a plaintext Connection, causing all three new tests to fail while connecting to the TLS-only port before reaching their assertions. Reuse a pool with the original connection class or explicitly set ssl=True when env.isTLS().
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 57d95bc, and the fix subsumes the earlier unix-socket one.
Rather than patching individual kwargs, the helper now rebuilds the client from the source pool's own connection_class and passes its kwargs verbatim. The class is what carries the transport selector, so this covers plaintext, TLS and unix sockets in one go — and it removes the path → unix_socket_path rename, which only existed because the two constructors spell it differently.
…ng server (RediSearch#10872) [MOD-15685] Refuse a legacy index spec RESTORE outside an RDB load A legacy index spec can only be upgraded while a load is in progress: both the UPGRADE_INDEX rules and the registry of legacy specs are built for the duration of a load and released at the end of it. IndexSpec_LegacyRdbLoad then looks both up unconditionally, so restoring a legacy ft_index0 payload on a running server reached dictFetchValue on a NULL dict and segfaulted. Any client holding RESTORE could do it. Refuse when either global is absent. The caller sees a load failure, which for RESTORE surfaces as a command error rather than a dead server. The check sits before anything is read, so a crafted payload needs no valid body to be rejected. Verified by removing the guard again: the server dies with the test reporting connection refused, so the test fails when the bug is present rather than passing for the wrong reason. This is MOD-15685 finding #71; #29 was fixed in RediSearch#10817. Co-authored-by: Claude Opus 5 <[email protected]>
|
/backport-agent 8.8 8.8-rse 8.6 8.6-rse 8.4 8.2 8.0 2.10 2.8 2.6 |
|
🤖 Auto-backport summary
(Summary generated by |
|
Follow-up on the auto-backport summary above: the five skipped targets ( The three legacy types only started saving zero bytes when #6438 ("Simplify legacy RDB support - MOD-10352", 2025-07-06) deleted On One separate lead, noted so it is not lost — it is not this defect and needs its own ticket. On |
…on a running server (#11611) [MOD-15685] Fix crash when a legacy index spec is restored on a running server (#10872) [MOD-15685] Refuse a legacy index spec RESTORE outside an RDB load A legacy index spec can only be upgraded while a load is in progress: both the UPGRADE_INDEX rules and the registry of legacy specs are built for the duration of a load and released at the end of it. IndexSpec_LegacyRdbLoad then looks both up unconditionally, so restoring a legacy ft_index0 payload on a running server reached dictFetchValue on a NULL dict and segfaulted. Any client holding RESTORE could do it. Refuse when either global is absent. The caller sees a load failure, which for RESTORE surfaces as a command error rather than a dead server. The check sits before anything is read, so a crafted payload needs no valid body to be rejected. Verified by removing the guard again: the server dies with the test reporting connection refused, so the test fails when the bug is present rather than passing for the wrong reason. This is MOD-15685 finding #71; #29 was fixed in #10817. (cherry picked from commit 1d4c089) Co-authored-by: dor-forer <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
Describe the changes in the pull request
1. Current
The three pre-2.0 module types (
ft_invidx,numericdx,ft_tagidx) are registered so that a legacy RediSearch 1.x RDB can be read and discarded during an upgrade. Their loaders return thedummyNonNullsentinel rather thanNULL, so Redis keeps the key in the keyspace after the payload has been consumed and thrown away.The
rdb_saveregistered for those types was:RS_ABORTexpands toRS_LOG_ASSERT_FMT, which is defined as// NOPunlessENABLE_ASSERTis set (deps/rmutil/rm_assert.h). In release builds the function therefore writes zero bytes and reports success. Every RDB containing such a key gets a module-value record with an empty body, and any reader of that RDB dies with:The save side never complains, so the database looks healthy until something tries to load it again — replica sync, shard restart, backup restore, export, or migration.
Separately,
.aof_rewritepointed atGenericAofRewrite_DisabledHandler, which callsabort()unconditionally. That runs inside the forked AOF rewrite child, so it kills the child rather than the shard: the rewrite can never complete and the AOF grows without bound for any database still holding legacy keys.2. Change
LEGACY_EMPTY_ENC_VER 2and registerft_invidx,numericdxandft_tagidxwith it, so records we write carry that version.GenericType_EmptyRdbSavewrites nothing, and each loader returns the sentinel immediately on seeing that version, consuming no bytes — which leaves Redis's module EOF marker exactly where it left it. Writing zero bytes under version 1 is precisely what corrupted the RDB: the loader read a payload that was not there and ate the marker instead. One saver replaces three, and no payload is fabricated.RS_ASSERT_ALWAYSrather thanRS_ASSERT. A value that is not the sentinel would be silently dropped, so a release build must crash instead of losing data. A debug-only assertion disappearing on this exact code path is what produced the original zero-byte save.rdb_loadwith no ceiling check (rdb.c:3169), so versions 0 and 1 still take the existing consume paths. A new test pins that, so bumping the registered version cannot silently change how older records are read.GenericAofRewrite_DisabledHandlerwith aDUMP→RESTORErewrite for these types. The shared handler callsabort(), which kills the forked AOF rewrite child so the rewrite can never complete and the AOF grows without bound. Emitting the key's own serialization keeps a command-only AOF and an RDB-preamble AOF in agreement about whether the key survives; without that, a live replica and a pure-AOF-restarted master diverge onEXISTS/TYPE/DBSIZE/ TTL. The IO's database is selected first, since a detached thread-safe context starts on DB 0 — which is whyRMUtil_DefaultAofRewrite(dead code in this repo) cannot be reused verbatim.util/misc.hinclude.test_cpp_rdb.cpp): that the empty save writes no bytes and each loader consumes none of them under the new version, so the marker cannot be eaten; and that a genuine 1.x payload is still consumed in full for all three types, including numeric under both the v0 and v1 framings.test_legacy_module_types.py, new): end-to-end against real Redis, which validates the module type id, the module EOF marker, theDUMPfooter and the CRC for us. BuildsRESTOREpayloads from first principles — the only way to create one of these keys — with a self-check that our CRC64 matches a footer the server wrote, so a broken fixture fails one obvious test rather than all of them. Covers round-trip throughRESTORE/DUMP/RESTOREplus a reload; survival of an AOF rewrite underaof-use-rdb-preamble no, the only format that runs theaof_rewritecallback; and a DB 1 key with a colliding DB 0 name, which fails if the callback forgets to select the IO's database.test_rdb_compatibility.py): assert the upgrade sweep leaves no legacy module-type keys behind, and dump-and-reload each upgraded fixture.3. Outcome
A database that still holds legacy index keys can produce a loadable RDB, so replica sync, backup, export and migration work instead of failing with a corrupt-RDB error. AOF rewrite completes instead of killing its child, and the key survives either AOF format identically.
The AOF rewrite callback, in more detail
aof_rewriteis the third callback of a module type, next tordb_saveandrdb_load, and it servesa different mechanism. An AOF is a log of commands, and Redis periodically rewrites it by forking a
child that walks the dataset and emits the commands needed to recreate each key. For an ordinary hash
that is an
HSET; for a module key Redis cannot know, so it asks the module.For these three types it was asking
GenericAofRewrite_DisabledHandler, whose body isabort(). That runs in the forked rewrite child, so it kills the child rather than the shard — andRedis discards a rewrite whose child died. Any database holding a legacy key therefore could never
rewrite its AOF, so the AOF grew without bound. Enabling AOF persistence is enough to trigger it.
LegacyType_AofRewriteasks Redis to serialize the key withDUMPand emits aRESTOREof thoseexact bytes, so replay recreates it. Using
DUMPavoids hand-building the envelope (RDB version plusCRC), and it is worth noting the dependency:
DUMPonly succeeds because of the threerdb_savecallbacks above — before them it produced the same empty payload as any other save.Three details each guard a specific failure:
SelectDb(RedisModule_GetDbIdFromIO(aof))DUMPwhatever unrelated key shares its name in DB 0.testLegacyAofRewriteUsesTheKeysOwnDatabaseplants a decoy string in DB 0 specifically to catch this. It is also whyRMUtil_DefaultAofRewrite— sameDUMP→RESTOREshape, noSELECT, and dead code in this repo — cannot be reused.ThreadSafeContextLock0LLrather than0for the TTL"l"consumes along long, and a bare0is anint— undefined behaviour on any ABI that lays variadicintandlong longout differently.An unexpected
DUMPreply fails the rewrite rather than warning and emitting nothing, because a basethat silently omits the key is exactly the divergence this callback exists to prevent; Redis keeps the
previous base when the child dies.
Why it is in this PR at all, given the reported incident never involved AOF: it is the same defect
reached through a second persistence path. Without it, whether a legacy key survives depends on which
AOF format is configured — a command-only AOF drops it, while an AOF with an RDB preamble goes through
rdb_saveand keeps it — so a live replica and a pure-AOF-restarted master would disagree onEXISTS,TYPE,DBSIZEand TTLs. Cost to a database without legacy keys is zero: Redis onlyinvokes the callback for keys of these three types.
Why a database with no legacy keys is unaffected
This was an explicit design constraint, so here is the argument rather than the assertion.
Redis dispatches these callbacks per key, by module type. Every module record carries its
9-character type name; Redis looks up which module registered that name and calls that type's
callbacks. So the only way to reach any new code here is to hold a key whose type is
ft_invidx,numericdxorft_tagidx— keys that can only come from deserializing a pre-2.0 payload.What this PR actually changes in
src/legacy_types.c:GenericType_DummyRdbSaveInvertedIndex_RdbSave_Empty,NumericIndexType_RdbSave_Empty,TagIndex_RdbSave_Empty,LegacyType_AofRewriteRegisterLegacyTypes*_RdbLoad_Consumeloaders andGenericType_DummyFree#include "util/misc.h"Path by path:
RedisModule_CreateDataTypecalls. Only the constants placed in the struct differ.FT.*,HSET,RESTORE, …)One thing does newly exist in release builds: the
RS_ASSERT_ALWAYSguards. They are compiled inwhere the old
RS_ABORTcompiled away — but they sit inside the three savers, so a database with nolegacy keys never executes them either.
Not free: CI wall-clock for the added tests, roughly a few seconds for the new pytest file.
Field context
Hit on a customer production database (ZD 168121); full analysis in MOD-15685. A Redis Enterprise DB created three months earlier by importing a pre-2.0 RediSearch RDB held ~101k live
ft_invidxkeys in the oldft:<index>/<term>format. Its replica crash-looped through 896 full syncs after a cluster upgrade forced the first full sync in 86 days, while the master reportedrdb_last_bgsave_status:okthe whole time.data_persistencewas disabled and no backups existed, so the only copy of the data was in RAM on a single node.FT.DROPINDEXhas no effect on these keys — they are ordinary keyspace keys, not index state.Known gaps, deliberately not addressed here
The keys are still retained. The loaders still return
dummyNonNull, so legacy keys continue to be materialized on every RDB load — and now that they are saveable, they replicate and survive restore indefinitely with no cleanup path. Not materializing the key during load, or adding a keyspace-driven sweep, is the real fix.ft_index0is not affected — checked, on every branch.master,8.6(v8.6.8) and8.6-rseall register.rdb_save = IndexSpec_RdbSave_Wrapper, andIndexSpec_LegacyRdbSave— whose body returns without writing a byte — is dead code in all three. So there is no fourth broken type and no extra backport gate. Two things do remain worth a look, but neither is this bug: whetherIndexSpec_RdbSave_Wrapperis safe when handed a spec left behind byIndexSpec_LegacyRdbLoad, and deleting the deadIndexSpec_LegacyRdbSaveso it cannot be wired up by mistake later.The 2.0 upgrade sweep silently no-ops.
Indexes_UpgradeLegacyIndexes→IndexSpec_DropLegacyIndexFromKeySpace(src/indexes_scan.c:431, shipped in 2.0.0) already deletes these keys, but it is spec-driven: it iterateslegacySpecDict, which is populated only when a legacyidx:<name>key loads, which in turn requires a matchingUPGRADE_INDEX <name>module argument —IndexSpec_LegacyRdbLoadreturnsNULLwithout one (src/spec.c:3281-3286). Term keys are then enumerated by walkingsp->terms, with no scan-by-type or prefix backstop. Import or restore withoutUPGRADE_INDEXand the keys are orphaned with nothing to ever collect them.Two test-layer caveats, both narrower than they were. The end-to-end gap is closed by
test_legacy_module_types.py, which does cross the Redis framing boundary. What remains: (a) the C++ tests drive the callbacks against a mock whose integers are raw host-endian rather than Redis's opcode+length framing, so on their own they prove save/load symmetry rather than valid framing — they are kept because they are fast and fail loudly on a zero-byte save; (b) thetest_rdb_compatibility.pyadditions assert the sweep left no legacy keys before saving, so they never invoke the new callbacks and are upgrade-path coverage only.The loader hardening is not here. The same three loaders trust attacker-controlled counts, so a truncated
RESTOREpayload declaringUINT64_MAXentries spins the server, andTagIndex_RdbLoad_Consumehas no encver guard. Verified and fixed ondor-mod15685-loader-hardening, held back so this PR stays one defect. Note for whoever reviews that one:RedisModule_IsIOErroronly functions when the module setsHANDLE_IO_ERRORS, whichsrc/notifications.cgates on a Redis-version check — fine onmaster, needs auditing per backport target.An RDB written by this build cannot be read by an older module. Records for these three types now carry encoding version 2, and an older loader rejects anything above version 1, so it refuses the whole RDB. This only affects reading new data with an old module — a downgrade, a mixed-version replica, or restoring a new backup on an older build. The alternative considered (writing a payload that is valid under version 1, so interoperable both ways) was rejected in review as fabricating data that does not exist; flagging it here so the tradeoff is explicit rather than implied.
Which additional issues this PR fixes
Main objects this PR modified
src/legacy_types.c—rdb_saveandaof_rewritecallbacks for the legacy module typestests/cpptests/test_cpp_rdb.cpp— legacy dummy-value save/load round-trip teststests/pytests/test_legacy_module_types.py(new) — end-to-end coverage against real Redistests/pytests/test_rdb_compatibility.py— leftover-key assertion plus dump-and-reload coverageMark if applicable
Release Notes