Skip to content

core: region heartbeat with bucket meta#10120

Merged
ti-chi-bot[bot] merged 3 commits intotikv:masterfrom
bufferflies:feat/region_heartbeat_with_bucket_meta
Jan 28, 2026
Merged

core: region heartbeat with bucket meta#10120
ti-chi-bot[bot] merged 3 commits intotikv:masterfrom
bufferflies:feat/region_heartbeat_with_bucket_meta

Conversation

@bufferflies
Copy link
Contributor

@bufferflies bufferflies commented Dec 25, 2025

What problem does this PR solve?

Issue Number: Close #10117

What is changed and how does it work?

Check List

Tests

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

Code changes

Side effects

  • Possible performance regression
  • Increased code complexity
  • Breaking backward compatibility

Related changes

Release note

None.

Summary by CodeRabbit

  • New Features

    • Regions now support bucket metadata handling, enabling improved synchronization of bucket information from cluster heartbeats. Bucket metadata is now preserved during region initialization and inheritance operations.
  • Dependencies

    • Updated core protobuf dependencies across multiple modules to support enhanced region metadata capabilities.

✏️ Tip: You can customize this high-level summary in your review settings.

Signed-off-by: tongjian <[email protected]>
@ti-chi-bot
Copy link
Contributor

ti-chi-bot bot commented Dec 25, 2025

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@ti-chi-bot ti-chi-bot bot added do-not-merge/needs-linked-issue release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. dco-signoff: yes Indicates the PR's author has signed the dco. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. labels Dec 25, 2025
@bufferflies bufferflies changed the title core: region with bucket meta core: region heartbeat with bucket meta Dec 26, 2025
Signed-off-by: bufferflies <[email protected]>
@codecov
Copy link

codecov bot commented Dec 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.58%. Comparing base (6bfdb20) to head (fcb8617).
⚠️ Report is 33 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #10120      +/-   ##
==========================================
+ Coverage   78.42%   78.58%   +0.15%     
==========================================
  Files         518      520       +2     
  Lines       69493    69670     +177     
==========================================
+ Hits        54503    54752     +249     
+ Misses      11042    10969      -73     
- Partials     3948     3949       +1     
Flag Coverage Δ
unittests 78.58% <100.00%> (+0.15%) ⬆️

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

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

@bufferflies bufferflies marked this pull request as ready for review December 29, 2025 07:08
@ti-chi-bot ti-chi-bot bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Dec 29, 2025
@@ -246,6 +246,7 @@
if hasBuckets {
if old := origin.GetBuckets(); buckets[i].GetVersion() > old.GetVersion() {
region.UpdateBuckets(buckets[i], old)
Copy link
Member

Choose a reason for hiding this comment

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

If we use SetBucketMeta, do we still need UpdateBuckets?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No need, but currently, we must keep compatibility; we need to update the bucket also. We can remove this update in a higher version.

@bufferflies bufferflies requested a review from lhy1024 January 6, 2026 06:50
Copy link
Contributor

@lhy1024 lhy1024 left a comment

Choose a reason for hiding this comment

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

the rest LGTM

// no limit for followers.
}
saveKV, _, _, _ := regionGuide(cctx, region, origin)
overlaps := bc.PutRegion(region)
Copy link
Contributor

Choose a reason for hiding this comment

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

We firstly call putRegion, and then UpdateBuckets, will this order introduce data race?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, UpdateBuckets will only update the point, not affect the bucket meta.

Comment on lines 89 to +95
buckets unsafe.Pointer
// source is used to indicate region's source, such as Storage/Sync/Heartbeat.
source RegionSource
// ref is used to indicate the reference count of the region in root-tree and sub-tree.
ref atomic.Int32
// bucketMeta is used to store the bucket meta reported by tikv.
bucketMeta *metapb.BucketMeta
Copy link
Contributor

Choose a reason for hiding this comment

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

If buckets and bucketMeta are both nil, which one will we use?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It will return nil.

Copy link
Contributor

Choose a reason for hiding this comment

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

What if either buckets or bucketMeta is nil?

Signed-off-by: bufferflies <[email protected]>
@ti-chi-bot ti-chi-bot bot added size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. labels Jan 6, 2026
@rleungx
Copy link
Member

rleungx commented Jan 8, 2026

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Jan 8, 2026

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link

coderabbitai bot commented Jan 8, 2026

📝 Walkthrough

Walkthrough

The PR introduces bucket metadata handling in region data structures to reduce costs and data race risks from separate bucket report streams. The kvproto dependency is updated across all modules, and RegionInfo now extracts, stores, and propagates bucket metadata from region heartbeats to the syncer client.

Changes

Cohort / File(s) Summary
Dependency Updates
client/go.mod, go.mod, tests/integrations/go.mod, tools/go.mod
Bumped github.com/pingcap/kvproto from v0.0.0-20251202064041-b6fd818387cd to v0.0.0-20260106110113-438649d89ee7 across all modules.
Region Bucket Metadata Implementation
pkg/core/region.go
Added bucketMeta field to RegionInfo to store bucket metadata from heartbeats. Extended RegionHeartbeatRequest interface with GetBucketMeta(). Modified RegionFromHeartbeat() to populate bucketMeta, Inherit() to guard bucket propagation based on bucketMeta presence, Clone() to copy bucketMeta, and GetBuckets() to return bucketMeta when available. Added public SetBucketMeta(buckets *metapb.Buckets) method.
Bucket Metadata Test
pkg/core/region_test.go
Added TestGetBucketMeta to validate bucket metadata inheritance behavior with and without pre-existing bucketMeta, including version preservation and override scenarios.
Syncer Client Integration
pkg/syncer/client.go
Calls region.SetBucketMeta(buckets[i]) immediately after region.UpdateBuckets() when a newer bucket version is detected during the leader sync flow.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 ✨ Buckets now hop in heartbeats, no longer alone,
Metadata travels where once it was strewn,
Region inheritance dances with grace,
Less cost, less race, a swifter embrace! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 'core: region heartbeat with bucket meta' clearly and specifically describes the main change—adding bucket meta handling to region heartbeats.
Description check ✅ Passed The PR description follows the repository template and includes the required 'Issue Number: Close #10117' linking and checklist sections, though specific implementation details are minimal.
Linked Issues check ✅ Passed The code changes successfully implement the objective from issue #10117 by adding bucket meta propagation through region heartbeats, reducing dependency on the bucket report stream.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue's objective: kvproto dependency updates align with new bucket meta features, and code changes implement bucket metadata handling in region heartbeats.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @pkg/syncer/client.go:
- Around line 246-250: The write to region.bucketMeta via SetBucketMeta after
bc.PutRegion(region) is not synchronized and can race with concurrent readers;
either make bucketMeta access atomic like buckets (use
atomic.StorePointer/atomic.LoadPointer or an atomic.Value inside
SetBucketMeta/GetBucketMeta), or protect bucketMeta with the same mutex used for
buckets, or move the SetBucketMeta call to before bc.PutRegion(region) so the
cached reference is initialized consistently; update SetBucketMeta/GetBucketMeta
and any callers (e.g., UpdateBuckets, GetBuckets, bc.PutRegion) to use the
chosen synchronization mechanism to eliminate the race.
🧹 Nitpick comments (1)
pkg/core/region_test.go (1)

1488-1489: Incomplete comment.

The comment on line 1488 appears to be truncated. Consider completing it for clarity.

📝 Suggested fix
-	// Inherit false if region
+	// bucket inheritance is skipped when region has bucketMeta set
 	re.Equal(uint64(1), region.GetBuckets().GetVersion())
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fe5653 and fcb8617.

⛔ Files ignored due to path filters (4)
  • client/go.sum is excluded by !**/*.sum
  • go.sum is excluded by !**/*.sum
  • tests/integrations/go.sum is excluded by !**/*.sum
  • tools/go.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • client/go.mod
  • go.mod
  • pkg/core/region.go
  • pkg/core/region_test.go
  • pkg/syncer/client.go
  • tests/integrations/go.mod
  • tools/go.mod
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/core/region.go (1)
pkg/response/region.go (1)
  • RegionInfo (113-136)
🔇 Additional comments (12)
tests/integrations/go.mod (1)

17-17: Consistent kvproto version with client/go.mod.

The kvproto version is properly aligned with the version used in client/go.mod, ensuring test infrastructure uses the same protobuf definitions.

go.mod (1)

38-38: Consistent and coordinated kvproto version across all modules.

The root module kvproto version matches client/go.mod and tests/integrations/go.mod, confirming a coordinated dependency update. The file's own documentation (lines 5–8) indicates this follows the project's established pattern for kvproto coordination. No other dependencies were inadvertently modified.

client/go.mod (1)

13-13: Verify kvproto dependency update for proto API compatibility.

The kvproto dependency is updated from a December 2, 2025 commit to a January 6, 2026 commit. Confirm that this version change does not introduce breaking changes to the RegionHeartbeatRequest, RegionHeartbeatResponse, and BucketStats proto messages that the client library depends on.

pkg/core/region_test.go (1)

1460-1490: Test coverage for bucket meta inheritance looks good.

The test properly validates:

  1. Initial state with nil buckets
  2. Bucket updates via UpdateBuckets
  3. Bucket inheritance behavior with and without bucketMeta

The test confirms that when bucketMeta is set on a region, the Inherit method correctly skips bucket inheritance from the origin, which aligns with the PR objective of using heartbeat-based bucket metadata.

pkg/core/region.go (7)

629-635: Consider thread-safety for SetBucketMeta.

Unlike UpdateBuckets which uses atomic.CompareAndSwapPointer, SetBucketMeta directly assigns to r.bucketMeta. If this method is called concurrently with GetBuckets() reads on the same region, the Go memory model doesn't guarantee visibility without synchronization.

While pointer assignment is atomic at the CPU level for aligned pointers (no torn reads), the lack of synchronization means readers might not see the update immediately or could observe a partially initialized object.

If concurrent access is possible, consider using atomic.Pointer or unsafe.Pointer with atomic operations similar to the buckets field:

♻️ Optional: Atomic access pattern
// Field change in RegionInfo struct:
// bucketMeta unsafe.Pointer  // *metapb.BucketMeta

func (r *RegionInfo) SetBucketMeta(buckets *metapb.Buckets) {
    meta := &metapb.BucketMeta{
        Version: buckets.GetVersion(),
        Keys:    buckets.GetKeys(),
    }
    atomic.StorePointer(&r.bucketMeta, unsafe.Pointer(meta))
}

// In GetBuckets:
// meta := (*metapb.BucketMeta)(atomic.LoadPointer(&r.bucketMeta))

652-666: GetBuckets implementation with bucketMeta fallback looks correct.

The logic correctly prioritizes bucketMeta (from heartbeat) over the legacy buckets pointer (from bucket report stream), which aligns with the PR objective. The atomic load for the fallback buckets field is preserved.

Note: A new metapb.Buckets object is created on each call when bucketMeta is set. If GetBuckets() is called frequently, consider caching the result. However, this is likely acceptable given typical usage patterns.


301-304: Inherit logic correctly guards bucket inheritance with bucketMeta check.

The updated condition ensures that bucket inheritance from the origin region is skipped when the current region already has bucketMeta populated from the heartbeat. This properly prioritizes heartbeat-based bucket metadata over inherited values.


221-221: Interface extension for bucket metadata.

The GetBucketMeta() method is added to support retrieving bucket metadata from region heartbeat requests, enabling the new bucket metadata flow.


248-251: RegionFromHeartbeat correctly populates bucketMeta.

The new bucketMeta field is properly initialized from the heartbeat request during region construction.


94-96: New bucketMeta field properly documented.

The field is correctly placed and commented to explain it stores bucket metadata reported by TiKV via heartbeats.


337-337: Clone correctly copies bucketMeta.

Shallow copy of the pointer is appropriate since bucketMeta is treated as immutable once set.

tools/go.mod (1)

26-26: Kvproto version is valid and includes the required BucketMeta type.

The dependency update to v0.0.0-20260106110113-438649d89ee7 is confirmed to contain the BucketMeta message in pkg/metapb, which provides the version and keys fields needed for the bucket metadata feature in region heartbeats.

@bufferflies
Copy link
Contributor Author

/retest

@bufferflies
Copy link
Contributor Author

/ping @lhy1024 @rleungx

@ti-chi-bot ti-chi-bot bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Jan 22, 2026
@ti-chi-bot ti-chi-bot bot added the lgtm label Jan 27, 2026
@ti-chi-bot
Copy link
Contributor

ti-chi-bot bot commented Jan 27, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: lhy1024, rleungx

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 removed the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jan 27, 2026
@ti-chi-bot
Copy link
Contributor

ti-chi-bot bot commented Jan 27, 2026

[LGTM Timeline notifier]

Timeline:

  • 2026-01-22 07:57:11.144600374 +0000 UTC m=+653458.758557230: ☑️ agreed by lhy1024.
  • 2026-01-27 02:23:58.932062748 +0000 UTC m=+1065466.546019603: ☑️ agreed by rleungx.

@bufferflies
Copy link
Contributor Author

/test pull-unit-test-next-gen-1

@ti-chi-bot ti-chi-bot bot merged commit 7a66bfb into tikv:master Jan 28, 2026
58 of 65 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved dco-signoff: yes Indicates the PR's author has signed the dco. lgtm release-note-none Denotes a PR that doesn't merit a release note. 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.

Region heartbeat should carry with the region bucket meta

3 participants