Skip to content

[MOD-17512] Fix unloadable RDB from leftover pre-2.0 index keys breaking replication, backups and exports - #10817

Merged
dor-forer merged 13 commits into
masterfrom
codex/fix-vulnerability-in-legacy-index-keys
Aug 11, 2026
Merged

dor-forer merged 13 commits into
masterfrom
codex/fix-vulnerability-in-legacy-index-keys

Conversation

@dor-forer

@dor-forer dor-forer commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Describe the changes in the pull request

Scope. Fixes MOD-15685 finding #29 only. Finding #71 (a legacy RESTORE reaching NULL
legacySpecDict/legacySpecRules) is untouched and verified still live, so MOD-15685 should stay
open
when this merges.

Deliberately narrow. It does not remove existing legacy keys (separate follow-up), cannot
repair RDBs or backups already written, and no longer carries the loader hardening — a separately
reachable CPU DoS in the same functions, now held on dor-mod15685-loader-hardening for its own PR.
That DoS remains open on master.

The branch was merged up to current master (hence the merge commit); it had been based on a
three-month-old base, so its earlier CI runs were not meaningful.

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 the dummyNonNull sentinel rather than NULL, so Redis keeps the key in the keyspace after the payload has been consumed and thrown away.

The rdb_save registered for those types was:

void GenericType_DummyRdbSave(RedisModuleIO *rdb, void *value) {
  RS_ABORT("Attempted to save a legacy type to RDB");
}

RS_ABORT expands to RS_LOG_ASSERT_FMT, which is defined as // NOP unless ENABLE_ASSERT is 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 RDB file contains module data for the module 'search' that is not terminated by
the proper module value EOF marker

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_rewrite pointed at GenericAofRewrite_DisabledHandler, which calls abort() 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

  • Add LEGACY_EMPTY_ENC_VER 2 and register ft_invidx, numericdx and ft_tagidx with it, so records we write carry that version. GenericType_EmptyRdbSave writes 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.
  • Guard the saver with RS_ASSERT_ALWAYS rather than RS_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.
  • Loading genuine 1.x records is unchanged. Redis passes the record's own encoding version to rdb_load with 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.
  • Replace GenericAofRewrite_DisabledHandler with a DUMP→RESTORE rewrite for these types. The shared handler calls abort(), 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 on EXISTS / TYPE / DBSIZE / TTL. The IO's database is selected first, since a detached thread-safe context starts on DB 0 — which is why RMUtil_DefaultAofRewrite (dead code in this repo) cannot be reused verbatim.
  • Drop the now-unused util/misc.h include.
  • Tests, C++ (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.
  • Tests, Python (test_legacy_module_types.py, new): end-to-end against real Redis, which validates the module type id, the module EOF marker, the DUMP footer and the CRC for us. Builds RESTORE payloads 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 through RESTORE/DUMP/RESTORE plus a reload; survival of an AOF rewrite under aof-use-rdb-preamble no, 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.
  • Tests, Python (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_rewrite is the third callback of a module type, next to rdb_save and rdb_load, and it serves
a 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 is
abort(). That runs in the forked rewrite child, so it kills the child rather than the shard — and
Redis 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_AofRewrite asks Redis to serialize the key with DUMP and emits a RESTORE of those
exact bytes, so replay recreates it. Using DUMP avoids hand-building the envelope (RDB version plus
CRC), and it is worth noting the dependency: DUMP only succeeds because of the three
rdb_save callbacks above — before them it produced the same empty payload as any other save.

Three details each guard a specific failure:

Detail Why
SelectDb(RedisModule_GetDbIdFromIO(aof)) A detached thread-safe context starts on DB 0, so without this a legacy key in DB 1 would DUMP whatever unrelated key shares its name in DB 0. testLegacyAofRewriteUsesTheKeysOwnDatabase plants a decoy string in DB 0 specifically to catch this. It is also why RMUtil_DefaultAofRewrite — same DUMP→RESTORE shape, no SELECT, and dead code in this repo — cannot be reused.
No ThreadSafeContextLock The rewrite child inherits the module GIL already held and is single-threaded; locking would deadlock.
0LL rather than 0 for the TTL "l" consumes a long long, and a bare 0 is an int — undefined behaviour on any ABI that lays variadic int and long long out differently.

An unexpected DUMP reply fails the rewrite rather than warning and emitting nothing, because a base
that 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_save and keeps it — so a live replica and a pure-AOF-restarted master would disagree on
EXISTS, TYPE, DBSIZE and TTLs. Cost to a database without legacy keys is zero: Redis only
invokes 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,
numericdx or ft_tagidx — keys that can only come from deserializing a pre-2.0 payload.

What this PR actually changes in src/legacy_types.c:

Element Change
GenericType_DummyRdbSave removed
InvertedIndex_RdbSave_Empty, NumericIndexType_RdbSave_Empty, TagIndex_RdbSave_Empty, LegacyType_AofRewrite new — reachable only via the three legacy types
RegisterLegacyTypes different function pointers assigned into the type-methods struct
The three *_RdbLoad_Consume loaders and GenericType_DummyFree byte-identical to master
#include "util/misc.h" removed, no longer used

Path by path:

Path Cost without legacy keys
Module load Unchanged — still three RedisModule_CreateDataType calls. Only the constants placed in the struct differ.
Any command (FT.*, HSET, RESTORE, …) None. No code on any command path changed.
RDB save None. Redis dispatches per key type; these savers sit only in those three type entries.
RDB load None — the loaders are untouched in this PR.
AOF rewrite None. Same per-type dispatch.
Keyspace notifications Not touched by this PR at all.
Background work None added: no new globals, allocations, timers, scans or subscriptions.

One thing does newly exist in release builds: the RS_ASSERT_ALWAYS guards. They are compiled in
where the old RS_ABORT compiled away — but they sit inside the three savers, so a database with no
legacy 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_invidx keys in the old ft:<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 reported rdb_last_bgsave_status:ok the whole time. data_persistence was disabled and no backups existed, so the only copy of the data was in RAM on a single node. FT.DROPINDEX has no effect on these keys — they are ordinary keyspace keys, not index state.

Known gaps, deliberately not addressed here

  1. 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.

  2. ft_index0 is not affected — checked, on every branch. master, 8.6 (v8.6.8) and 8.6-rse all register .rdb_save = IndexSpec_RdbSave_Wrapper, and IndexSpec_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: whether IndexSpec_RdbSave_Wrapper is safe when handed a spec left behind by IndexSpec_LegacyRdbLoad, and deleting the dead IndexSpec_LegacyRdbSave so it cannot be wired up by mistake later.

  3. 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 iterates legacySpecDict, which is populated only when a legacy idx:<name> key loads, which in turn requires a matching UPGRADE_INDEX <name> module argument — IndexSpec_LegacyRdbLoad returns NULL without one (src/spec.c:3281-3286). Term keys are then enumerated by walking sp->terms, with no scan-by-type or prefix backstop. Import or restore without UPGRADE_INDEX and the keys are orphaned with nothing to ever collect them.

  4. 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) the test_rdb_compatibility.py additions assert the sweep left no legacy keys before saving, so they never invoke the new callbacks and are upgrade-path coverage only.

  5. The loader hardening is not here. The same three loaders trust attacker-controlled counts, so a truncated RESTORE payload declaring UINT64_MAX entries spins the server, and TagIndex_RdbLoad_Consume has no encver guard. Verified and fixed on dor-mod15685-loader-hardening, held back so this PR stays one defect. Note for whoever reviews that one: RedisModule_IsIOError only functions when the module sets HANDLE_IO_ERRORS, which src/notifications.c gates on a Redis-version check — fine on master, needs auditing per backport target.

  6. 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

  1. MOD-15685
  2. ZD 168121

Main objects this PR modified

  1. src/legacy_types.c — rdb_save and aof_rewrite callbacks for the legacy module types
  2. tests/cpptests/test_cpp_rdb.cpp — legacy dummy-value save/load round-trip tests
  3. tests/pytests/test_legacy_module_types.py (new) — end-to-end coverage against real Redis
  4. tests/pytests/test_rdb_compatibility.py — leftover-key assertion plus dump-and-reload coverage

Mark if applicable

  • This PR introduces API changes
  • This PR introduces serialization changes

Release Notes

  • This PR requires release notes
  • This PR does not require release notes

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

codecov Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.07%. Comparing base (81e656c) to head (57d95bc).
⚠️ Report is 22 commits behind head on master.

Files with missing lines Patch % Lines
src/legacy_types.c 92.85% 1 Missing ⚠️
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              
Flag Coverage Δ
flow 84.06% <92.85%> (+0.08%) ⬆️
unit 55.48% <92.85%> (-0.33%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dor-forer dor-forer changed the title Provide safe minimal RDB save for legacy module types (ft_invidx / numericdx / ft_tagidx) [MOD-15685] Fix unloadable RDB from leftover pre-2.0 index keys breaking replication, backups and exports Aug 9, 2026
dor-forer and others added 2 commits August 10, 2026 12:37
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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/legacy_types.c Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread src/legacy_types.c Outdated
// 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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
@github-actions github-actions Bot added size:L and removed size:S labels Aug 10, 2026
- 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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +75 to +77
if (fields.get('aof_rewrite_in_progress', '0').strip() == '0'
and fields.get('aof_rewrite_scheduled', '0').strip() == '0'):
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_rewrites increments at rewrite start — stat_aof_rewrites++ sits immediately before redisFork in aof.c — so a change in it proves a rewrite actually began. The activity flags alone can read idle before it starts.
  • aof_last_bgrewrite_status is 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]>
dor-forer and others added 2 commits August 11, 2026 09:58
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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/legacy_types.c Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread src/legacy_types.c
// 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)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_Consume reject with encver > LEGACY_ENC_VER → return NULL → Redis reports "the responsible module is not able to load" and aborts the load. Loud, at least.
  • TagIndex_RdbLoad_Consume on master has no encver guard, so it reads the empty payload's first field — which is Redis's module EOF marker. io.error is set, n_tags comes 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>

@GuyAv46 GuyAv46 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🎣

Comment thread src/legacy_types.c Resolved
Comment thread src/legacy_types.c Resolved
Comment thread src/legacy_types.c Resolved
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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

GuyAv46
GuyAv46 previously approved these changes Aug 11, 2026
pull Bot pushed a commit to Mu-L/RediSearch that referenced this pull request Aug 12, 2026
…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]>
@dor-forer

Copy link
Copy Markdown
Collaborator Author

/backport-agent 8.8 8.8-rse 8.6 8.6-rse 8.4 8.2 8.0 2.10 2.8 2.6

@redisearch-backport-pull-request

Copy link
Copy Markdown
Contributor

🤖 Auto-backport summary

Target Status Backport PR
8.10 clean #10934
8.8 conflicts(1) #10935 — see Conflict Log in the PR body
8.8-rse clean #10936
8.6 conflicts(1) #10937 — see Conflict Log in the PR body
8.6-rse conflicts(1) #10938 — see Conflict Log in the PR body
8.4 conflicts(1) #10939 — see Conflict Log in the PR body
8.2 skipped Legacy module types are active data types and src/legacy_types.c is absent — manual backport required
8.0 skipped Legacy module types are active data types and src/legacy_types.c is absent — manual backport required
2.10 skipped Legacy module types are active data types and src/legacy_types.c is absent — manual backport required
2.8 skipped Legacy module types are active data types and src/legacy_types.c is absent — manual backport required
2.6 skipped Legacy module types are active data types and src/legacy_types.c is absent — manual backport required

(Summary generated by .github/codex/prompts/pr-backport-auto.md.)

@dor-forer

dor-forer commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Follow-up on the auto-backport summary above: the five skipped targets (8.2, 8.0, 2.10, 2.8, 2.6) do not need a manual backport — they are not affected by this defect.

The three legacy types only started saving zero bytes when #6438 ("Simplify legacy RDB support - MOD-10352", 2025-07-06) deleted InvertedIndex_RdbSave, NumericIndexType_RdbSave and TagIndex_RdbSave and pointed ft_invidx / numericdx / ft_tagidx at the aborting GenericType_DummyRdbSave. That commit introduced src/legacy_types.c, and it exists on 8.4 and newer only.

On 8.2 and older those three types still register their original, real savers (src/redis_index.c, src/numeric_index.c, src/tag_index.c), so a legacy key there serializes a genuine payload and the RDB stays loadable. The corrupt-RDB bug is a regression introduced in the 8.4 cycle, which makes 8.4 the oldest affected branch — so the six backports (#10934 8.10, #10935 8.8, #10936 8.8-rse, #10937 8.6, #10938 8.6-rse, #10939 8.4) cover every affected release line. The backport-8.2/8.0/2.10/2.8/2.6-agent labels have been removed accordingly.

One separate lead, noted so it is not lost — it is not this defect and needs its own ticket. On 8.2 and older, ft_index0 registers .rdb_save = IndexSpec_LegacyRdbSave (src/spec.c), whose body is // we do not save legacy indexes / return; — also a zero-byte save. Reachability is unverified: IndexSpec_LegacyRdbLoad returns NULL unless legacySpecRules holds an entry for the index (i.e. a matching UPGRADE_INDEX <name> module argument), and if it does return a spec, whether the upgrade sweep subsequently deletes the idx:<name> key decides whether a saveable husk can survive at all. Worth confirming before assuming any impact.

github-merge-queue Bot pushed a commit that referenced this pull request Sep 29, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants