Repository navigation
[MOD-18182] Avoid reindexing for score/payload-only Hash updates - #11384
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3720e22898
ℹ️ 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".
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #11384 +/- ##
==========================================
- Coverage 84.00% 83.50% -0.50%
==========================================
Files 635 664 +29
Lines 83908 86332 +2424
Branches 38773 40195 +1422
==========================================
+ Hits 70486 72095 +1609
- Misses 13063 13865 +802
- Partials 359 372 +13
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:
|
| static inline void DMD_Return(const RSDocumentMetadata *cdmd) { | ||
| RSDocumentMetadata *dmd = (RSDocumentMetadata *)cdmd; | ||
| if (dmd && !__atomic_sub_fetch(&dmd->ref_count, 1, __ATOMIC_RELAXED)) { | ||
| if (dmd && !__atomic_sub_fetch(&dmd->ref_count, 1, __ATOMIC_ACQ_REL)) { |
There was a problem hiding this comment.
Why do we need the strongest memory order now? It used to be safe to use RELAXED, no?
There was a problem hiding this comment.
Can we reduce it to RELEASE + a fence ACQUIRE inside the if block?
| if (doc->payload) { | ||
| DocTable_SetPayload(&sctx->spec->docs, md, doc->payload, doc->payloadSize); | ||
| if (!DocTable_SetPayload(&sctx->spec->docs, md, doc->payload, doc->payloadSize)) { | ||
| BAIL("Document metadata has no payload slot"); |
| return alreadyIndexed ? IndexUpdate_Skip : IndexUpdate_Full; | ||
| } | ||
|
|
||
| static bool updateHashMetadata(IndexSpec *spec, RedisModuleCtx *ctx, RedisModuleString *key) { |
There was a problem hiding this comment.
Add a short description for this helper, what it does, and what it returns
| dmd = (RSDocumentMetadata *)DocTable_Borrow(&spec->docs, docId); | ||
| // Buffered results retain their DMD after releasing the spec lock. Only the table and | ||
| // this borrow may own it during mutation; acquire pairs with those readers' returns. | ||
| if (!dmd || __atomic_load_n(&dmd->ref_count, __ATOMIC_ACQUIRE) != 2) { |
There was a problem hiding this comment.
Why not replace the DMD, leaving the old one untouched for those who may read it? And then this condition can be relaxed
There was a problem hiding this comment.
Changed to copy-on-write when readers retain the DMD, preserving the same docId and leaving their metadata untouched. The unshared case still updates in place. Added ownership/concurrency tests and handled subsequent deletion or reindexing so stale snapshots are discarded before loading. Unit and flow tests pass, including ASan checks.
| // Expiration can change indexed content independently of the fields named by this write. | ||
| if (!k || RedisModule_KeyType(k) != REDISMODULE_KEYTYPE_HASH || | ||
| RedisModule_GetAbsExpire(k) != REDISMODULE_NO_EXPIRE || | ||
| RedisModule_HashFieldMinExpire(k) != REDISMODULE_NO_EXPIRE || |
There was a problem hiding this comment.
Some of these checks can be replaced with asserts - can we get here with a non-hash key?
There was a problem hiding this comment.
Changed the existing-key type check to an assertion. Kept the null-key guard because HDEL removes the key before notifying us when the last field is deleted. Added regression coverage for deleting the sole score/payload field.
| updated = true; | ||
| } | ||
| if (updated) { | ||
| dmd->score = score; |
There was a problem hiding this comment.
Why update the score only if the payload was updated? Can't a user update only the score?
There was a problem hiding this comment.
Score-only updates already worked, but the code unnecessarily rewrote the existing payload. I’ve separated score/payload change tracking so each update touches only the requested fields, and added regression coverage for independent and combined updates.
| if (dmd->type != DocumentType_Hash || (dmd->flags & Document_FailedToOpen) || | ||
| __atomic_load_n(&dmd->expirationTimeNs, __ATOMIC_RELAXED) || | ||
| DocTable_GetFieldExpirations(&spec->docs, docId).len || | ||
| (spec->rule->payload_field && !(dmd->flags & Document_HasPayloadSlot))) { |
There was a problem hiding this comment.
Some of these checks can be asserted or dropped
| DMD_Return(dmd); | ||
| RedisSearchCtx_UnlockSpec(&sctx); | ||
| if (payload) { | ||
| RedisModule_FreeString(ctx, payload); |
There was a problem hiding this comment.
Is the payload string owned? Can't we get a reference?
There was a problem hiding this comment.
Yes, HashGet returns a string that we need to free here. I checked the available APIs but couldn’t find a way to borrow a single hash field’s value directly. Do you know an API or an existing example we could use to avoid the temporary allocation?
There was a problem hiding this comment.
Yes, HashGet returns a string that we need to free here. I checked the available APIs but couldn’t find a way to borrow a single hash field’s value directly. Do you know an API or an existing example we could use to avoid the temporary allocation?
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5afc3948e5
ℹ️ 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 (!k) { | ||
| goto cleanup; | ||
| } | ||
| RS_ASSERT(RedisModule_KeyType(k) == REDISMODULE_KEYTYPE_HASH); |
There was a problem hiding this comment.
Handle an empty key before asserting Hash type
When HDEL removes the last field and that field is the configured SCORE_FIELD or PAYLOAD_FIELD, the deferred subkey callback still classifies the update as metadata-only, but RedisModule_OpenKey returns a non-NULL handle whose type is REDISMODULE_KEYTYPE_EMPTY (also modeled explicitly in tests/cpptests/redismock/redismock.cpp). This assertion therefore aborts an ENABLE_ASSERT server for an ordinary last-field deletion; check for EMPTY and take the deletion/full-update fallback instead of asserting that every returned handle is a Hash.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This path opens the key with REDISMODULE_READ | REDISMODULE_OPEN_KEY_NOEFFECTS. For a missing key, Redis returns NULL in read mode; only write mode returns an empty key handle. The existing if (!k) therefore handles last-field deletion before the assertion.
The OpenKey API documentation confirms this distinction, as does Redis's implementation. The cited mock always returns a handle and differs from real Redis in this case.
testMetadataLastFieldDeletion covers deleting the sole score field and the sole payload field. It passed against real Redis with ENABLE_ASSERT=1, including in the full behavioral run on the current head 5afc3948e.
| // Detached snapshots receive neither deletion flags nor key-name changes from RENAME. | ||
| const RSDocumentMetadata *current = DocTable_Borrow(&self->sctx->spec->docs, dmd->id); | ||
| bool valid = current && !(dmd->flags & (Document_FailedToOpen | Document_Deleted)) && | ||
| (current == dmd || sdscmp(current->keyPtr, dmd->keyPtr) == 0); | ||
| DMD_Return(current); |
There was a problem hiding this comment.
This looks like a heavy price to pay. I now question the idea of cloning and keeping the ID. Why not refresh the meta fields only?
- Score is just a number
- Payload is deprecated - maybe we can avoid adding support for it
The price we pay here is an additional borrow/return per loaded result, which could be pretty big
| SearchResult *curr_res; | ||
|
|
||
| // The GIL is already held; protect document-ID validation while loading buffered snapshots. | ||
| RedisSearchCtx_LockSpecRead(self->sctx); |
|
@GuyAv46 Ready for another look.
|
| RedisModuleString *key, DocumentType type, | ||
| RedisModuleString **changedFields, | ||
| size_t numChangedFields) { | ||
| if (!changedFields || !numChangedFields || type != DocumentType_Hash || spec->diskSpec || |
There was a problem hiding this comment.
- Avoid checking both array and its length.
- why 0 field changes requires full reindex? When does it happen?
- JSON is a future optimization? Why it has to be explicitly skipped? Isn’t that field array covers it?
|
❌ The last analysis has failed. |
Describe the changes in the pull request
Score-only, payload-only, and combined Hash writes currently rebuild indexed content and assign a new internal document ID. For eligible existing RAM Hash documents, update only the changed metadata fields in place while preserving the document ID and index entries.
Update metadata only when the document table and updater are its sole owners. When a query retains the metadata, use the existing full reindex path so that reader keeps its old payload alive. Schema, language, filter, expiration, storage, and unknown-change cases also retain full reindexing. This adds no metadata cloning or query-loader lookup or lock.
Indexes configured with PAYLOAD_FIELD reserve a payload-pointer slot in RAM metadata, including when the document has no payload (one pointer, 8 bytes on x86-64). Clearing a payload releases its buffer and wrapper but retains that capacity for later updates. There is no persistence-format change.
Which additional issues this PR fixes
Main objects this PR modified
Validation on dorer-intel with assertions enabled: 1,066 unit tests and 2,387 standalone behavioral tests passed. AddressSanitizer unit tests and 44 focused behavioral tests also passed, with no leaks reported.
Mark if applicable
Release Notes
If a release note is required (bug fix / new feature / enhancement), describe the user impact of this PR in the title.