Skip to content

Fix crash saving after upgrading a legacy index spec stored under an unexpected key - #11636

Merged
eyalrund merged 18 commits into
masterfrom
eyalrund-fix-legacy-spec-key-check
Oct 5, 2026
Merged

eyalrund merged 18 commits into
masterfrom
eyalrund-fix-legacy-spec-key-check

Conversation

@eyalrund

@eyalrund eyalrund commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #11630 (itself on #11605), which adds the legacy-RDB test helpers this test uses. Review only this PR's two commits; the merge commit only brings in #11630's branch. It retargets to master once the PRs below it merge.

Describe the changes in the pull request

  1. Current: when Redis starts from an RDB file (or a replica runs a full sync) with a pre-2.0 index spec stored under a key other than idx:<index name>, or in a database other than 0, the spec is upgraded but its key stays in the keyspace. The upgrade deletes only idx:<name> in db 0. The leftover key holds the legacy load result, not an index spec, so the next SAVE, BGSAVE, full sync or DUMP that writes it crashes the server.
  2. Change: the legacy spec loader checks that the spec is stored under idx:<its name> in db 0 and fails the load otherwise, logging Refusing a legacy index that is not stored under its index key in db 0.
  3. Outcome: such an RDB is refused at load with a clear log line, instead of loading and crashing at the first save. Legacy RDBs written by RediSearch 1.x always store specs at idx:<name> in db 0 and load as before.

Which additional issues this PR fixes

  1. N/A
  2. N/A

Main objects this PR modified

  1. IndexSpec_LegacyRdbLoad (src/spec.c): calls the new legacySpecKeyIsExpected right after reading the spec name, and fails the load when it returns false.
  2. test_legacy_module_types.py: new testLegacySpecUnderUnexpectedKeyFailsToLoad. The fixture writer now takes the key to store the spec under.

Mark if applicable

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

An RDB whose legacy spec is not at idx:<name> in db 0 is now rejected at load. RediSearch 1.x only wrote specs at that key, and FT.CREATE only allows db 0, so only a hand-edited file is affected. Today such a file loads and then crashes at the first save.

Release Notes

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

Review notes

Why refuse instead of cleaning up. The alternative is to record the key and db each legacy spec was loaded from and delete exactly that key during the upgrade. That would keep such files loading, but it needs new state on the spec or the legacy registry for input that RediSearch never writes. Refusing also stops the upgrade's DEL idx:<name> from removing an unrelated key that happens to have that name.

Scope of the check. It runs only for keyed loads. A value loaded without a key is never placed in the keyspace, so nothing can be left behind. The spec name is read first, since the check needs it, and it is freed on refusal.

Verification. The new test was run in fresh checkouts of the unfixed base and the fix:

Check Base: #11630 head 067a3de8d Head 8072234d3
Build (DEBUG=1) passed passed
testLegacySpecUnderUnexpectedKeyFailsToLoad failed as expected: the spec loaded, and SAVE crashed the server in IndexSpec_RdbSave_Wrapper → HiddenString_SaveToRdb passed: load refused with the new log line, no crash report
Existing legacy and RDB-compatibility tests (11, including testRDBCompatibility over the bundled 1.2-2.0 RDBs) 11 passed 11 passed
Independent review passed, 0 actionable, 4 informational

Performance. One key-name comparison per legacy spec, during the first RDB load only. Not measured.

Limitations.

  • The test covers a wrong key name. The non-zero-db case takes the same check but is not exercised on its own.
  • The test skips under ASan: the server exits mid-load by design, like the other load-rejection tests.
  • Where the load is accepted (only on unfixed code), the test issues the SAVE that crashes, so an unfixed build fails for the actual crash.
  • The test environment differs from CI: Redis 8.10-m03 built with MALLOC=libc, and headers not regenerated (REDISEARCH_GENERATE_HEADERS=0).

🤖 Generated with Claude Code

eyalrund and others added 12 commits September 29, 2026 12:39
Build a legacy (encver 16) index spec RDB file in the test and start the
server from it. One test checks that byte offsets which exactly fill
their blob load and upgrade. The other gives the offsets a length prefix
larger than the blob, which must fail the load with a diagnostic rather
than crash the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
LoadByteOffsets trusted the counts and lengths in the serialized blob,
so a blob shorter than its own length prefix made it read past the end
of the buffer, after allocating as much as the prefix claimed. Check
each read against the bytes remaining and return NULL when the blob is
short. DocTable_LegacyRdbLoad, its only caller, now logs and fails the
load in that case.

Failing the load also needs the legacy spec's cleanup to be safe:
IndexSpec_LegacyRdbLoad never initialized the spec's IndexError, so
freeing the spec on any load error hit an assertion (debug) or a NULL
dereference (release). Initialize it when the spec is created, and
clear it before the legacy upgrade reinitializes the stats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build a legacy (encver 16) index spec RDB file in the test and start the
server from it. Its only document is deleted and flagged as having a
payload; the load must drop it and upgrade the index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
DocTable_LegacyRdbLoad does not load the payload of a deleted document,
but it left Document_HasPayload set on it. Freeing the dropped document
then dereferenced its NULL payload in DMD_Free and crashed the server
during the RDB load. Clear the flag when the payload is not loaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Encver 13 is the only encoding that saved the payload of a deleted doc,
so its load has to skip that string as well as clear the payload flag.
Parameterize the legacy spec fixture by encoding version and cover it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Encodings older than 8 store a field's name but no path. Build an
encver 7 index spec RDB file with one TEXT field, start the server from
it, and check that the upgraded index reports and serves the field, also
after saving it in the current format and reloading.

Store the fixture's legacy spec under idx:<name>, the key the upgrade
deletes, instead of a plain name the upgrade left behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FieldSpec_RdbLoadCompat8, the loader for encodings older than 8, set a
field's name but left its path NULL. Everywhere else a field without a
separate path uses its name as the path, and IndexSpec_BuildSpecCache
relies on that: it duplicates the path whenever it is not the name,
so a NULL path crashed the server during the RDB load. Set the path to
the name when loading these fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in test_legacy_module_types.py by keeping both the
legacy-loader tests from this branch and the failed-sync RESTORE test from
master (#11619).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…field-path-load

Pick up master (via #11605's branch) and resolve the conflict in
test_legacy_module_types.py by keeping both this branch's test and
master's failed-sync RESTORE test (#11619).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Store an encver 16 index spec under a key other than idx:<name> in the
RDB file the server starts from. The load must fail with a diagnostic
rather than leave the key behind for a later save to crash on. The
fixture writer takes the key to store the spec under.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The legacy upgrade deletes each spec's key by the name it was saved
under, idx:<name> in db 0. A spec loaded from any other key, or from
another db, was upgraded but its key stayed in the keyspace, holding the
legacy load result rather than an IndexSpec. Saving that key, on the
next SAVE, BGSAVE or DUMP, handed it to IndexSpec_RdbSave_Wrapper and
crashed the server. Fail such a load instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-04T08:22:03.353679Z 2dfac32 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: a975bdead3

ℹ️ 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/spec.c
const char *keyStr = RedisModule_StringPtrLen(key, &keyLen);
const size_t prefixLen = strlen(INDEX_SPEC_KEY_PREFIX);
const size_t nameLen = strlen(specName);
return RedisModule_GetDbIdFromIO(rdb) == 0 && keyLen == prefixLen + nameLen &&

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 Cover legacy specs loaded from a nonzero database

The new condition rejects a correctly named legacy spec when it is outside database 0, but _write_legacy_spec_body_rdb always emits SELECTDB 0 and the added test exercises only an unexpected key. Consequently, a regression in the database check could reintroduce the leftover-key/save-crash path while this test still passes; parameterize the fixture's database and add a SELECTDB 1 case using idx:idx that asserts load refusal without a crash report.

AGENTS.md reference: AGENTS.md:L21-L22

Useful? React with 👍 / 👎.

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.

This comment predates this PR?

Comment thread src/spec.c
Comment on lines +3511 to +3515
if (!legacySpecKeyIsExpected(rdb, legacyName)) {
RedisModule_LogIOError(rdb, "warning",
"Refusing a legacy index that is not stored under its index key in db 0");
RedisModule_Free(legacyName);
return NULL;

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 upgrade rules when rejecting a full sync

During a diskless full sync containing multiple legacy specs, an earlier valid spec removes its entry from legacySpecRules at the end of IndexSpec_LegacyRdbLoad; if this new guard then rejects a later miskeyed spec, the LOADING_FAILED path does not restore those consumed rules. Every subsequent full-sync attempt therefore rejects the earlier valid spec with “Could not find upgrade definition,” even after the source RDB has been corrected, until the replica is restarted. Keep the upgrade rules transactional across failed loads or restore consumed entries when this rejection aborts replication.

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Sep 29, 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 83.50%. Comparing base (3d129c9) to head (2dfac32).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/spec.c 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #11636      +/-   ##
==========================================
- Coverage   84.15%   83.50%   -0.66%     
==========================================
  Files         642      667      +25     
  Lines       85156    86227    +1071     
  Branches    39311    40368    +1057     
==========================================
+ Hits        71667    72006     +339     
- Misses      13126    13850     +724     
- Partials      363      371       +8     
Flag Coverage Δ
flow 84.66% <92.85%> (-0.06%) ⬇️
unit 58.71% <0.00%> (-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.

eyalrund and others added 5 commits September 30, 2026 12:05
FieldSpec_RdbLoadCompat8 read each field name into an allocated buffer
and passed it to NewHiddenString with takeOwnership set, which copies
the buffer rather than adopting it, so the loaded buffer leaked.
FieldSpec_RdbLoad hands the buffer over instead (takeOwnership false),
and FieldSpec_Cleanup frees it; do the same. The leak became reachable
once loading these fields stopped crashing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ec-key-check

Pick up the fix for the legacy field-name leak.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-field-path-load

# Conflicts:
#	tests/pytests/test_legacy_module_types.py
…-field-path-load

# Conflicts:
#	tests/pytests/test_legacy_module_types.py
…oad' into eyalrund-fix-legacy-spec-key-check

# Conflicts:
#	tests/pytests/test_legacy_module_types.py
Base automatically changed from eyalrund-fix-legacy-field-path-load to master October 1, 2026 13:09
…-spec-key-check

# Conflicts:
#	tests/pytests/test_legacy_module_types.py
@sonarqubecloud

sonarqubecloud Bot commented Oct 4, 2026

Copy link
Copy Markdown

@eyalrund
eyalrund requested a review from GuyAv46 October 4, 2026 13:38
@eyalrund
eyalrund added this pull request to the merge queue Oct 5, 2026
Merged via the queue into master with commit 795785c Oct 5, 2026
61 checks passed
@eyalrund
eyalrund deleted the eyalrund-fix-legacy-spec-key-check branch October 5, 2026 12:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants