Skip to content

Invalidate read-index cache when local lock is found#10986

Merged
ti-chi-bot[bot] merged 5 commits into
pingcap:feature/release-8.5-materialized-viewfrom
windtalker:not_cache_read_index_if_meet_lock
Jul 18, 2026
Merged

Invalidate read-index cache when local lock is found#10986
ti-chi-bot[bot] merged 5 commits into
pingcap:feature/release-8.5-materialized-viewfrom
windtalker:not_cache_read_index_if_meet_lock

Conversation

@windtalker

@windtalker windtalker commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: ref #10985

Problem Summary:

TiFlash can repeatedly reuse a stale read-index cache after a local LockCF lock is found and the caller resolves the lock on TiKV. The next retry may skip fetching a fresh read index, so it may not wait for the resolve-lock raft log to be applied on the TiFlash learner and can hit the same lock again.

What is changed and how it works?

Invalidate read index cache when lock is found

When RegionTable::resolveLocksAndWriteRegion still finds a local lock after wait-index succeeds, TiFlash now invalidates the read-index worker history cache for that region and removes the current query-level read-index cache entry. The next retry will request a fresh read index instead of reusing the stale one.

A read-index worker unit test is added to verify that invalidating the cache forces a new read-index request for a smaller read ts that would otherwise use history.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No code

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Fix a potential repeated TiFlash remote cop retry caused by reusing a stale read-index cache after resolving locks.

Summary by CodeRabbit

  • New Features
    • Added a way to explicitly invalidate per-region read-index caches.
  • Bug Fixes
    • Improved cache consistency by clearing both read-index caches and related read-index result caches when lock resolution indicates cached data may be stale.
  • Tests
    • Extended read-index tests to confirm cache invalidation returns the latest commit index while preserving expected history-success task behavior.
    • Disabled one fast-add peer test case.
  • Chores
    • Enhanced lock exception debug messaging with more contextual details.
    • Updated the bundled C client submodule revision.

Signed-off-by: xufei <xufeixw@mail.ustc.edu.cn>
@ti-chi-bot ti-chi-bot Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds region-scoped invalidation through KVStore and read-index workers, clears history-success and MVCC result caches when locks are detected, enhances lock diagnostics, updates a client submodule, and disables one fast add-peer test.

Changes

Read-index cache invalidation

Layer / File(s) Summary
Invalidation API and worker pipeline
dbms/src/Storages/KVStore/KVStore.h, dbms/src/Storages/KVStore/Read/ReadIndex*
Adds region-scoped invalidation from KVStore through the worker manager and worker to the per-region data node, clearing history_success_tasks.
Lock-triggered invalidation and validation
dbms/src/Storages/KVStore/Read/LearnerReadWorker.cpp, dbms/src/Storages/RegionQueryInfo.h, dbms/src/Storages/KVStore/tests/gtest_read_index_worker.cpp
Invalidates read-index and MVCC result caches when a lock is detected, then verifies a subsequent read returns the updated commit index.

Lock diagnostic details

Layer / File(s) Summary
First-lock diagnostic formatting
dbms/src/Storages/KVStore/Read/LockException.h
Adds first-lock region and debug information to LockException messages, including null and empty-input cases.

Maintenance updates

Layer / File(s) Summary
Client submodule reference
contrib/client-c
Advances the submodule reference to a newer commit.
Disabled fast add-peer test
dbms/src/Storages/KVStore/tests/gtest_kvstore_fast_add_peer.cpp
Comments out the RegionKVStoreTestFAP.Cancel5 test.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LearnerReadWorker
  participant KVStore
  participant ReadIndexWorkerManager
  participant ReadIndexWorker
  participant ReadIndexDataNode
  participant MvccQueryInfo
  LearnerReadWorker->>KVStore: invalidateReadIndexCache(region_id)
  KVStore->>ReadIndexWorkerManager: invalidateReadIndexCache(region_id)
  ReadIndexWorkerManager->>ReadIndexWorker: route region_id
  ReadIndexWorker->>ReadIndexDataNode: invalidateReadIndexCache()
  ReadIndexDataNode->>ReadIndexDataNode: clear history_success_tasks
  LearnerReadWorker->>MvccQueryInfo: invalidateReadIndexResCache(region_id)
  LearnerReadWorker->>LearnerReadWorker: mark region unavailable
Loading

Possibly related issues

Suggested reviewers: jayson-huang

Poem

A bunny found stale reads in the hay,
So caches were cleared without delay.
The lock hopped past, the index grew,
Fresh commit numbers came into view.
“Thump, thump!” cried the rabbit with glee!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: invalidating read-index cache when a local lock is found.
Description check ✅ Passed The description covers the problem, change summary, test checklist, and release note, with only minor checklist items left unchecked.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@windtalker

Copy link
Copy Markdown
Contributor Author

/hold

@ti-chi-bot ti-chi-bot Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jul 16, 2026
@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Jul 16, 2026
Signed-off-by: xufei <xufeixw@mail.ustc.edu.cn>
Signed-off-by: xufei <xufeixw@mail.ustc.edu.cn>
Signed-off-by: xufei <xufeixw@mail.ustc.edu.cn>

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
dbms/src/Storages/KVStore/Read/LockException.h (1)

56-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer fmt::format for simple string construction.

Using fmt::format directly is more concise and aligns with the coding guidelines for string construction in C++, avoiding the need for a mutable FmtBuffer.
(Note: If you apply this, you may also be able to remove #include <Common/FmtUtils.h> at line 18 if it is not required for formatting locked_regions.)

♻️ Proposed refactor
-        FmtBuffer buffer;
-        const auto & lock = locks.front();
-        buffer.fmtAppend("{}(", lock.first);
-        if (lock.second)
-            buffer.append(lock.second->ShortDebugString());
-        else
-            buffer.append("<null>");
-        buffer.append(")");
-        return buffer.toString();
+        const auto & lock = locks.front();
+        if (lock.second)
+            return fmt::format("{}({})", lock.first, lock.second->ShortDebugString());
+        return fmt::format("{}(<null>)", lock.first);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@dbms/src/Storages/KVStore/Read/LockException.h` around lines 56 - 64, In the
lock string construction within the relevant exception formatting method,
replace the mutable FmtBuffer sequence with a direct fmt::format expression that
preserves the lock name, ShortDebugString() value, and "<null>" fallback. Remove
the Common/FmtUtils.h include if it is no longer needed elsewhere, including for
locked_regions formatting.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@dbms/src/Storages/KVStore/Read/LockException.h`:
- Around line 56-64: In the lock string construction within the relevant
exception formatting method, replace the mutable FmtBuffer sequence with a
direct fmt::format expression that preserves the lock name, ShortDebugString()
value, and "<null>" fallback. Remove the Common/FmtUtils.h include if it is no
longer needed elsewhere, including for locked_regions formatting.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9e94e57e-abd1-4523-b60a-524f163ffc3d

📥 Commits

Reviewing files that changed from the base of the PR and between 420deeb and 61ef2f0.

📒 Files selected for processing (3)
  • dbms/src/Storages/KVStore/Read/LockException.h
  • dbms/src/Storages/KVStore/Read/ReadIndexWorker.cpp
  • dbms/src/Storages/KVStore/Read/ReadIndexWorker.h
🚧 Files skipped from review as they are similar to previous changes (2)
  • dbms/src/Storages/KVStore/Read/ReadIndexWorker.cpp
  • dbms/src/Storages/KVStore/Read/ReadIndexWorker.h

@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

@windtalker

Copy link
Copy Markdown
Contributor Author

/hold cancel

@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jul 17, 2026
@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

1 similar comment
@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

@gengliqi gengliqi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@ti-chi-bot

ti-chi-bot Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: gengliqi, solotzg

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jul 17, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

[LGTM Timeline notifier]

Timeline:

  • 2026-07-16 10:02:13.454591911 +0000 UTC m=+880719.490686967: ☑️ agreed by solotzg.
  • 2026-07-17 09:53:59.658361775 +0000 UTC m=+966625.694456841: ☑️ agreed by gengliqi.

@gengliqi

Copy link
Copy Markdown
Contributor

/test pull-unit-test

2 similar comments
@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

Signed-off-by: xufei <xufeixw@mail.ustc.edu.cn>

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
dbms/src/Storages/KVStore/tests/gtest_kvstore_fast_add_peer.cpp (1)

859-921: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the unstable test compilable.

The block comment removes Cancel5 from the translation unit, so future changes can silently break this cancellation path without any compile-time signal. Prefer GoogleTest’s DISABLED_ convention (or GTEST_SKIP() with a tracking reference) and retain the test body.

Proposed fix
-/*
-TEST_F(RegionKVStoreTestFAP, Cancel5)
+TEST_F(RegionKVStoreTestFAP, DISABLED_Cancel5)
...
-CATCH
-*/
+CATCH
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@dbms/src/Storages/KVStore/tests/gtest_kvstore_fast_add_peer.cpp` around lines
859 - 921, Restore the RegionKVStoreTestFAP test named Cancel5 to the
translation unit and disable it using GoogleTest’s DISABLED_ naming convention,
preserving its existing body and cancellation assertions. Do not leave the test
inside a block comment; ensure it remains compilable and discoverable as a
disabled test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@dbms/src/Storages/KVStore/tests/gtest_kvstore_fast_add_peer.cpp`:
- Around line 859-921: Restore the RegionKVStoreTestFAP test named Cancel5 to
the translation unit and disable it using GoogleTest’s DISABLED_ naming
convention, preserving its existing body and cancellation assertions. Do not
leave the test inside a block comment; ensure it remains compilable and
discoverable as a disabled test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d3dcb1c1-8c48-4bd2-b781-bd836b875a07

📥 Commits

Reviewing files that changed from the base of the PR and between 61ef2f0 and c712a23.

📒 Files selected for processing (1)
  • dbms/src/Storages/KVStore/tests/gtest_kvstore_fast_add_peer.cpp

@windtalker

Copy link
Copy Markdown
Contributor Author

/test pull-unit-test

@ti-chi-bot
ti-chi-bot Bot merged commit 8fe3056 into pingcap:feature/release-8.5-materialized-view Jul 18, 2026
5 checks passed
@windtalker
windtalker deleted the not_cache_read_index_if_meet_lock branch July 18, 2026 05:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants