Skip to content

[MOD-18182] Avoid reindexing for score/payload-only Hash updates - #11384

Merged
dor-forer merged 13 commits into
masterfrom
dor-mod-18182-metadata-updates
Sep 23, 2026
Merged

dor-forer merged 13 commits into
masterfrom
dor-mod-18182-metadata-updates

Conversation

@dor-forer

@dor-forer dor-forer commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

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

  1. MOD-18182

Main objects this PR modified

  1. Hash notification dispatch: distinguish skipped, score/payload-only, and full index updates; read only changed metadata fields.
  2. Document table: payload capacity, clear operation, allocation accounting, and release/acquire ordering for the uniqueness check across C/Rust reference returns.
  3. Regression tests: metadata lifecycle and index preservation, combined/shared fields, full-reindex fallbacks, old-RDB allocation behavior, and deterministic retained-reader payload safety.

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

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

Release Notes

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

If a release note is required (bug fix / new feature / enhancement), describe the user impact of this PR in the title.

@dor-forer
dor-forer marked this pull request as ready for review September 17, 2026 07:28
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 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-09-23T08:06:31.869257Z 7526ad4 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: 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".

Comment thread src/document.c Resolved
@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.50%. Comparing base (ffdecf9) to head (7526ad4).
⚠️ Report is 37 commits behind head on master.

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     
Flag Coverage Δ
flow 84.68% <98.92%> (+0.14%) ⬆️
unit 58.58% <97.89%> (+0.42%) ⬆️

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.

Comment thread src/doc_table.h Outdated
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)) {

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.

Why do we need the strongest memory order now? It used to be safe to use RELAXED, no?

@GuyAv46 GuyAv46 Sep 17, 2026 •

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.

Can we reduce it to RELEASE + a fence ACQUIRE inside the if block?

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

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.

Is this reachable code?

Comment thread src/indexes.c Outdated
return alreadyIndexed ? IndexUpdate_Skip : IndexUpdate_Full;
}

static bool updateHashMetadata(IndexSpec *spec, RedisModuleCtx *ctx, RedisModuleString *key) {

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.

Add a short description for this helper, what it does, and what it returns

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

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.

Why not replace the DMD, leaving the old one untouched for those who may read it? And then this condition can be relaxed

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.

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.

Comment thread src/indexes.c Outdated
// 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 ||

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.

Some of these checks can be replaced with asserts - can we get here with a non-hash key?

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.

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.

Comment thread src/indexes.c
updated = true;
}
if (updated) {
dmd->score = score;

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.

Why update the score only if the payload was updated? Can't a user update only the score?

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.

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.

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

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.

Some of these checks can be asserted or dropped

Comment thread src/indexes.c
DMD_Return(dmd);
RedisSearchCtx_UnlockSpec(&sctx);
if (payload) {
RedisModule_FreeString(ctx, payload);

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.

Is the payload string owned? Can't we get a reference?

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.

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?

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.

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?

@dor-forer
dor-forer requested a review from GuyAv46 September 22, 2026 06:57
@github-actions github-actions Bot added size:XL and removed size:L labels Sep 22, 2026

@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: 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".

Comment thread src/indexes.c Outdated
if (!k) {
goto cleanup;
}
RS_ASSERT(RedisModule_KeyType(k) == REDISMODULE_KEYTYPE_HASH);

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

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.

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.

Comment thread src/result_processor.c Outdated
Comment on lines +1019 to +1023
// 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);

@GuyAv46 GuyAv46 Sep 22, 2026 •

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

Comment thread src/result_processor.c Outdated
SearchResult *curr_res;

// The GIL is already held; protect document-ID validation while loading buffered snapshots.
RedisSearchCtx_LockSpecRead(self->sctx);

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.

would be nice to avoid

@dor-forer dor-forer changed the title [MOD-18182] Avoid reindexing for score/payload-only Hash updates [MOD-18182] Avoid reindexing for score-only Hash updates Sep 22, 2026
@github-actions github-actions Bot added size:L and removed size:XL labels Sep 22, 2026
@dor-forer dor-forer changed the title [MOD-18182] Avoid reindexing for score-only Hash updates [MOD-18182] Avoid reindexing for score/payload-only Hash updates Sep 22, 2026
@github-actions github-actions Bot added size:XL and removed size:L labels Sep 22, 2026
@dor-forer

Copy link
Copy Markdown
Collaborator Author

@GuyAv46 Ready for another look.
I removed the metadata cloning and the extra lookup/borrow/lock added to result loading. Score and payload updates now modify the existing metadata only when no query retains it. Otherwise, they use normal reindexing, leaving the old metadata alive for existing readers.
I also retained the fixes from your earlier review:

  • Score-only updates leave payload untouched, and vice versa.
  • Proven type invariants use assertions; legitimate fallback conditions remain runtime checks.
  • Reference returns use release ordering, with an acquire fence only on final destruction, in both C and Rust.
  • Payload-capable indexes reserve a pointer slot so adding a payload later can avoid reindexing.

Comment thread src/indexes.c Outdated
RedisModuleString *key, DocumentType type,
RedisModuleString **changedFields,
size_t numChangedFields) {
if (!changedFields || !numChangedFields || type != DocumentType_Hash || spec->diskSpec ||

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.

  1. Avoid checking both array and its length.
  2. why 0 field changes requires full reindex? When does it happen?
  3. JSON is a future optimization? Why it has to be explicitly skipped? Isn’t that field array covers it?

@sonarqubecloud

Copy link
Copy Markdown

❌ The last analysis has failed.

See analysis details on SonarQube Cloud

@dor-forer
dor-forer enabled auto-merge September 23, 2026 09:20
@dor-forer
dor-forer added this pull request to the merge queue Sep 23, 2026
Merged via the queue into master with commit ff4237c Sep 23, 2026
109 of 111 checks passed
@dor-forer
dor-forer deleted the dor-mod-18182-metadata-updates branch September 23, 2026 10:27
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.

2 participants