From a3b283a643b2356ed6d998517a23b124919a2722 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 17:52:08 +0000 Subject: [PATCH 01/18] ring: simplify zonal ownership and report duplicate tokens ZonalOwnership took the write operation and left out the tokens of every instance it extends the replica set past. Its only caller, added with it in #7954 and unreleased, now asks for one rule, so drop the parameter: every instance owns the ranges of its tokens except READONLY instances, whose ranges go to the next instance in their zone. The cache becomes one map, cleared when tokens change or an instance becomes or stops being READONLY, which RingCompare reports as EqualButReadOnly. A heartbeat or any other state change no longer clears it. Add HasDuplicateTokens, read from the ring's existing token lists. A token maps to one instance ring-wide, so when instances of two zones share one, one zone's ownership and shuffle-shard picks depend on an instance of the other. Signed-off-by: Alan Protasio --- integration/ingester_ownership_limits_test.go | 2 +- pkg/ingester/ownership.go | 2 +- pkg/ingester/ownership_test.go | 6 +- pkg/ring/ring.go | 12 +- pkg/ring/ring_desc_fed_test.go | 11 +- pkg/ring/ring_zonal_ownership.go | 70 +++---- pkg/ring/ring_zonal_ownership_test.go | 197 +++++++++++------- 7 files changed, 177 insertions(+), 123 deletions(-) diff --git a/integration/ingester_ownership_limits_test.go b/integration/ingester_ownership_limits_test.go index a9bb4dbb2d..1c3f5d83c7 100644 --- a/integration/ingester_ownership_limits_test.go +++ b/integration/ingester_ownership_limits_test.go @@ -338,7 +338,7 @@ func ownershipLimitsShares(t *testing.T, instances []struct { } shares := map[string]float64{} - for id, share := range scoped.(ring.ZonalOwnershipRing).ZonalOwnership(ring.Write) { + for id, share := range scoped.(ring.ZonalOwnershipRing).ZonalOwnership() { if share > 0 { shares[id] = share } diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 006789ebfd..9eef2563bd 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -101,7 +101,7 @@ func (o *ownershipRefresher) refresh(userIDs []string) { if !ok || zonal.ZonesCount() != o.ring.ReplicationFactor() { continue } - shares[userID] = zonal.ZonalOwnership(o.writeOp)[o.instanceID] + shares[userID] = zonal.ZonalOwnership()[o.instanceID] } o.ownership.shares.Store(&shares) diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 845a12fce2..81063d656d 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -91,7 +91,7 @@ func TestRingOwnershipDelegate_FeedsACopyOfTheDesc(t *testing.T) { assert.Contains(t, desc.Ingesters, "b-1") assert.Equal(t, []uint32{300, 100}, desc.Ingesters["a-1"].Tokens) - ownership := r.ZonalOwnership(ring.Write) + ownership := r.ZonalOwnership() assert.NotContains(t, ownership, "b-1") assert.Positive(t, ownership["a-1"]) assert.Positive(t, ownership["a-2"]) @@ -131,9 +131,9 @@ func TestOwnershipRefresher(t *testing.T) { share, ok := refresher.ownership.share(unshuffledTenant) require.True(t, ok) - assert.InDelta(t, r.ZonalOwnership(ring.Write)[ingesterID], share, ownershipTestTolerance) + assert.InDelta(t, r.ZonalOwnership()[ingesterID], share, ownershipTestTolerance) - subOwnership := r.ShuffleShard(shuffledTenant, shardSize).(ring.ZonalOwnershipRing).ZonalOwnership(ring.Write) + subOwnership := r.ShuffleShard(shuffledTenant, shardSize).(ring.ZonalOwnershipRing).ZonalOwnership() share, ok = refresher.ownership.share(shuffledTenant) if want, inShard := subOwnership[ingesterID]; inShard { require.True(t, ok) diff --git a/pkg/ring/ring.go b/pkg/ring/ring.go index 700592bcaa..3d87f2d8bc 100644 --- a/pkg/ring/ring.go +++ b/pkg/ring/ring.go @@ -208,9 +208,9 @@ type Ring struct { // If set to nil, no caching is done (used by tests, and subrings). shuffledSubringCache map[subringCacheKey]*cachedSubring - // Cached result of ZonalOwnership, per operation. Nil when not computed or - // invalidated by a change of tokens or instance states. Guarded by mtx. - zonalOwnershipByOp map[Operation]map[string]float64 + // Cached result of ZonalOwnership. Nil when not computed, or after a change + // of tokens or of which instances are READONLY. Guarded by mtx. + zonalOwnership map[string]float64 memberOwnershipGaugeVec *prometheus.GaugeVec memberZonalOwnershipGaugeVec *prometheus.GaugeVec @@ -377,7 +377,8 @@ func (r *Ring) updateRingState(ringDesc *Desc) { // when watching the ring for updates). r.mtx.Lock() r.ringDesc = ringDesc - if rc != Equal { + if rc == EqualButReadOnly { + // An instance became or stopped being READONLY. r.invalidateZonalOwnership() } if rc == EqualButReadOnly && r.shuffledSubringCache != nil { @@ -1062,9 +1063,6 @@ func (r *Ring) getCachedShuffledSubring(identifier string, size int, lookbackPer // so zones and tokens are equal. for name, cachedIng := range subring.ringDesc.Ingesters { ing := r.ringDesc.Ingesters[name] - if cachedIng.State != ing.State { - subring.invalidateZonalOwnership() - } cachedIng.State = ing.State cachedIng.Timestamp = ing.Timestamp subring.ringDesc.Ingesters[name] = cachedIng diff --git a/pkg/ring/ring_desc_fed_test.go b/pkg/ring/ring_desc_fed_test.go index ae95b951c2..2cea1fcaa1 100644 --- a/pkg/ring/ring_desc_fed_test.go +++ b/pkg/ring/ring_desc_fed_test.go @@ -18,8 +18,7 @@ func TestDescFedRing_ZonalOwnershipMatchesWatchedRing(t *testing.T) { require.NoError(t, err) fed.UpdateDesc(newOwnershipTestDesc(instances)) - assert.Equal(t, watched.ZonalOwnership(Write), fed.ZonalOwnership(Write)) - assert.Equal(t, watched.ZonalOwnership(WriteNoExtend), fed.ZonalOwnership(WriteNoExtend)) + assert.Equal(t, watched.ZonalOwnership(), fed.ZonalOwnership()) } func TestDescFedRing_UpdateDescReplacesState(t *testing.T) { @@ -28,10 +27,10 @@ func TestDescFedRing_UpdateDescReplacesState(t *testing.T) { require.NoError(t, err) fed.UpdateDesc(newOwnershipTestDesc(handPickedInstances(nil))) - require.InDelta(t, 0.25, fed.ZonalOwnership(Write)["a2"], ownershipTolerance) + require.InDelta(t, 0.25, fed.ZonalOwnership()["a2"], ownershipTolerance) - fed.UpdateDesc(newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){"a2": withState(LEAVING)}))) - assert.Zero(t, fed.ZonalOwnership(Write)["a2"]) + fed.UpdateDesc(newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){"a2": withState(READONLY)}))) + assert.Zero(t, fed.ZonalOwnership()["a2"]) } func TestDescFedRing_UpdateDescLeavesDescUnchanged(t *testing.T) { @@ -48,7 +47,7 @@ func TestDescFedRing_UpdateDescLeavesDescUnchanged(t *testing.T) { // updateRingState deletes excluded zones and sorts tokens in place. assert.Contains(t, desc.Ingesters, "b-1") assert.Equal(t, []uint32{300, 100}, desc.Ingesters["a-1"].Tokens) - assert.NotContains(t, fed.ZonalOwnership(Write), "b-1") + assert.NotContains(t, fed.ZonalOwnership(), "b-1") } func TestDescFedRing_DoesNotRegisterMetrics(t *testing.T) { diff --git a/pkg/ring/ring_zonal_ownership.go b/pkg/ring/ring_zonal_ownership.go index def06b709b..36c4f64300 100644 --- a/pkg/ring/ring_zonal_ownership.go +++ b/pkg/ring/ring_zonal_ownership.go @@ -7,9 +7,9 @@ const ringHashSpaceSize = float64(maxTokenValue) + 1 // the hash space each instance owns within its own zone. type ZonalOwnershipRing interface { // ZonalOwnership returns, for every instance in the ring, the fraction - // of its zone's hash space it owns for writes made with op. See - // (*Ring).ZonalOwnership for the exact semantics. - ZonalOwnership(op Operation) map[string]float64 + // of its zone's hash space it owns. See (*Ring).ZonalOwnership for the + // exact semantics. + ZonalOwnership() map[string]float64 // ZonesCount returns the number of zones with at least one instance with // tokens. Only when it equals the replication factor does each zone hold @@ -24,54 +24,57 @@ func (r *Ring) ZonesCount() int { return len(r.ringZones) } +// HasDuplicateTokens reports whether two instances of the ring hold the same +// token. A token maps to one instance ring-wide, so when the two are in +// different zones, one zone's ownership and shuffle-shard picks depend on an +// instance of another zone. +func (r *Ring) HasDuplicateTokens() bool { + r.mtx.RLock() + defer r.mtx.RUnlock() + return len(r.ringTokens) != len(r.ringInstanceByToken) +} + // ZonalOwnership returns, for every instance in the ring, the fraction of its -// zone's hash space that op routes to that instance. +// zone's hash space it owns. // -// Tokens of instances for which op extends the replica set (for example -// JOINING or LEAVING instances with Write, or READONLY instances with either -// write operation) are left out: their ranges fall to the next remaining token -// in the same zone, which is the instance Get extends to. Instances excluded -// this way report 0. Instances that Get keeps but Filter drops without -// replacement (such as an ACTIVE instance with a stale heartbeat) keep their -// tokens, because no other instance in the zone receives those keys. +// Every instance owns the ranges of its tokens, except READONLY instances: +// writes skip them, and their ranges fall to the next instance in the same +// zone, which is the instance Get extends to. READONLY instances report 0. +// This is where writes go with -distributor.extend-writes=false. With it on, +// writes also skip JOINING, LEAVING and PENDING instances, which this does not +// model. // // The values are the fraction of keys each instance receives only with // zone-aware replication and a replication factor equal to ZonesCount. With // more replicas than zones, Get puts a second copy in some zones, and with // fewer it skips some zones, so callers should not use the values then. // -// The returned map is cached until the ring's tokens or instance states -// change, and must not be modified. -func (r *Ring) ZonalOwnership(op Operation) map[string]float64 { +// The returned map is cached until the ring's tokens change or an instance +// becomes or stops being READONLY, and must not be modified. +func (r *Ring) ZonalOwnership() map[string]float64 { r.mtx.RLock() - cached, ok := r.zonalOwnershipByOp[op] + cached := r.zonalOwnership r.mtx.RUnlock() - if ok { + if cached != nil { return cached } r.mtx.Lock() defer r.mtx.Unlock() - if cached, ok := r.zonalOwnershipByOp[op]; ok { - return cached + if r.zonalOwnership == nil { + r.zonalOwnership = r.computeZonalOwnership() } - - ownership := r.computeZonalOwnership(op) - if r.zonalOwnershipByOp == nil { - r.zonalOwnershipByOp = map[Operation]map[string]float64{} - } - r.zonalOwnershipByOp[op] = ownership - return ownership + return r.zonalOwnership } // invalidateZonalOwnership drops the cached ownership. The caller must hold // r.mtx for writing. func (r *Ring) invalidateZonalOwnership() { - r.zonalOwnershipByOp = nil + r.zonalOwnership = nil } // computeZonalOwnership must be called with r.mtx held. -func (r *Ring) computeZonalOwnership(op Operation) map[string]float64 { +func (r *Ring) computeZonalOwnership() map[string]float64 { ownership := make(map[string]float64, len(r.ringDesc.Ingesters)) for id := range r.ringDesc.Ingesters { ownership[id] = 0 @@ -81,7 +84,7 @@ func (r *Ring) computeZonalOwnership(op Operation) map[string]float64 { // Tokens are sorted, so the remaining tokens stay sorted. remaining := make([]uint32, 0, len(zoneTokens)) for _, token := range zoneTokens { - if r.ownsTokenForWrites(token, op) { + if r.ownsToken(token) { remaining = append(remaining, token) } } @@ -96,18 +99,15 @@ func (r *Ring) computeZonalOwnership(op Operation) map[string]float64 { return ownership } -// ownsTokenForWrites reports whether writes made with op stop at the instance -// holding token, rather than extending past it. -func (r *Ring) ownsTokenForWrites(token uint32, op Operation) bool { +// ownsToken reports whether the instance holding token owns its range, that +// is, whether it is not READONLY. +func (r *Ring) ownsToken(token uint32) bool { info, ok := r.ringInstanceByToken[token] if !ok { return false } instance, ok := r.ringDesc.Ingesters[info.InstanceID] - if !ok { - return false - } - return !op.ShouldExtendReplicaSetOnState(instance.State) + return ok && instance.State != READONLY } // ownedRange returns the number of token values in (prev, token], the range diff --git a/pkg/ring/ring_zonal_ownership_test.go b/pkg/ring/ring_zonal_ownership_test.go index b8cac7f4d1..5b6da351ab 100644 --- a/pkg/ring/ring_zonal_ownership_test.go +++ b/pkg/ring/ring_zonal_ownership_test.go @@ -83,43 +83,35 @@ func TestRing_ZonalOwnership_HandPickedTokens(t *testing.T) { tests := map[string]struct { override map[string]func(*ownershipTestInstance) - op Operation expected map[string]float64 }{ "all ACTIVE": { - op: Write, expected: map[string]float64{"a1": 0.25, "a2": 0.25, "a3": 0.5}, }, - "JOINING instance is left out with Write": { + "JOINING instance keeps its range": { override: map[string]func(*ownershipTestInstance){"a2": withState(JOINING)}, - op: Write, - expected: map[string]float64{"a1": 0.25, "a2": 0, "a3": 0.75}, + expected: map[string]float64{"a1": 0.25, "a2": 0.25, "a3": 0.5}, }, - "JOINING instance keeps its range with WriteNoExtend": { - override: map[string]func(*ownershipTestInstance){"a2": withState(JOINING)}, - op: WriteNoExtend, + "LEAVING and PENDING instances keep their ranges": { + override: map[string]func(*ownershipTestInstance){"a1": withState(LEAVING), "a2": withState(PENDING)}, expected: map[string]float64{"a1": 0.25, "a2": 0.25, "a3": 0.5}, }, - "READONLY instance is left out with WriteNoExtend": { + "READONLY instance is left out": { override: map[string]func(*ownershipTestInstance){"a2": withState(READONLY)}, - op: WriteNoExtend, expected: map[string]float64{"a1": 0.25, "a2": 0, "a3": 0.75}, }, "only one instance left in the zone owns all of it": { - override: map[string]func(*ownershipTestInstance){"a1": withState(LEAVING), "a2": withState(PENDING)}, - op: Write, + override: map[string]func(*ownershipTestInstance){"a1": withState(READONLY), "a2": withState(READONLY)}, expected: map[string]float64{"a1": 0, "a2": 0, "a3": 1}, }, "every instance in the zone left out": { override: map[string]func(*ownershipTestInstance){ "a1": withState(READONLY), "a2": withState(READONLY), "a3": withState(READONLY), }, - op: Write, expected: map[string]float64{"a1": 0, "a2": 0, "a3": 0}, }, "ACTIVE instance with a stale heartbeat keeps its range": { override: map[string]func(*ownershipTestInstance){"a2": func(i *ownershipTestInstance) { i.stale = true }}, - op: Write, expected: map[string]float64{"a1": 0.25, "a2": 0.25, "a3": 0.5}, }, } @@ -128,7 +120,7 @@ func TestRing_ZonalOwnership_HandPickedTokens(t *testing.T) { t.Run(name, func(t *testing.T) { r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(tc.override))) - got := r.ZonalOwnership(tc.op) + got := r.ZonalOwnership() expected := map[string]float64{} maps.Copy(expected, balancedZoneB) @@ -148,7 +140,7 @@ func TestRing_ZonalOwnership_DuplicateTokenOwnsNoExtraRange(t *testing.T) { }) r := newOwnershipTestRing(t, 1, desc) - got := r.ZonalOwnership(Write) + got := r.ZonalOwnership() assert.InDelta(t, 0.5, got["a1"], ownershipTolerance) assert.InDelta(t, 0.5, got["a2"], ownershipTolerance) @@ -209,11 +201,11 @@ func TestRing_ZonalOwnership_SumsToOnePerZone(t *testing.T) { instances := randomOwnershipInstances(rnd, zones, perZone, tokensPerInstance, joiningAndReadOnly) r := newOwnershipTestRing(t, zones, newOwnershipTestDesc(instances)) - got := r.ZonalOwnership(Write) + got := r.ZonalOwnership() sumByZone := map[string]float64{} for _, inst := range instances { - if inst.state != ACTIVE { + if inst.state == READONLY { assert.Zero(t, got[inst.id], "instance %s is %s", inst.id, inst.state) } sumByZone[inst.zone] += got[inst.id] @@ -224,87 +216,97 @@ func TestRing_ZonalOwnership_SumsToOnePerZone(t *testing.T) { } } -// The ownership must describe where Get actually sends keys: the fraction of -// random keys Get routes to an instance is its zonal ownership. +// The ownership must describe where Get sends keys without replica set +// extension: the fraction of random keys Get routes to an ACTIVE instance is +// its zonal ownership. func TestRing_ZonalOwnership_MatchesWriteRouting(t *testing.T) { const ( zones = 3 perZone = 6 tokensPerInstance = 16 ) + rnd := rand.New(rand.NewSource(ownershipTestSeed)) + instances := randomOwnershipInstances(rnd, zones, perZone, tokensPerInstance, joiningAndReadOnly) + r := newOwnershipTestRing(t, zones, newOwnershipTestDesc(instances)) + ownership := r.ZonalOwnership() - for name, op := range map[string]Operation{"Write": Write, "WriteNoExtend": WriteNoExtend} { - t.Run(name, func(t *testing.T) { - rnd := rand.New(rand.NewSource(ownershipTestSeed)) - instances := randomOwnershipInstances(rnd, zones, perZone, tokensPerInstance, joiningAndReadOnly) - r := newOwnershipTestRing(t, zones, newOwnershipTestDesc(instances)) - ownership := r.ZonalOwnership(op) - - idByAddr := map[string]string{} - for _, inst := range instances { - idByAddr[inst.id+"-addr"] = inst.id - } + idByAddr := map[string]string{} + for _, inst := range instances { + idByAddr[inst.id+"-addr"] = inst.id + } - received := map[string]int{} - bufDescs, bufHosts, bufZones := MakeBuffersForGet() - for range routingSampleKeys { - set, err := r.Get(rnd.Uint32(), op, bufDescs, bufHosts, bufZones) - require.NoError(t, err) - for _, ing := range set.Instances { - received[idByAddr[ing.Addr]]++ - } - } + received := map[string]int{} + bufDescs, bufHosts, bufZones := MakeBuffersForGet() + for range routingSampleKeys { + set, err := r.Get(rnd.Uint32(), WriteNoExtend, bufDescs, bufHosts, bufZones) + require.NoError(t, err) + for _, ing := range set.Instances { + received[idByAddr[ing.Addr]]++ + } + } - for _, inst := range instances { - fraction := float64(received[inst.id]) / routingSampleKeys - if inst.state != ACTIVE { - // Filter never sends writes to non-ACTIVE instances, whatever - // ownership says about the range they hold. - assert.Zero(t, received[inst.id], "instance %s is %s", inst.id, inst.state) - continue - } - assert.InDelta(t, ownership[inst.id], fraction, routingTolerance, "instance %s", inst.id) - } - }) + for _, inst := range instances { + fraction := float64(received[inst.id]) / routingSampleKeys + if inst.state != ACTIVE { + // Filter never sends writes to non-ACTIVE instances, whatever + // ownership says about the range they hold. + assert.Zero(t, received[inst.id], "instance %s is %s", inst.id, inst.state) + continue + } + assert.InDelta(t, ownership[inst.id], fraction, routingTolerance, "instance %s", inst.id) } } func TestRing_ZonalOwnership_Cached(t *testing.T) { r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(nil))) - first := r.ZonalOwnership(Write) - second := r.ZonalOwnership(Write) + first := r.ZonalOwnership() + second := r.ZonalOwnership() assert.Equal(t, reflect.ValueOf(first).Pointer(), reflect.ValueOf(second).Pointer()) } -func TestRing_ZonalOwnership_InvalidatedOnStateChange(t *testing.T) { +func TestRing_ZonalOwnership_InvalidatedOnReadOnlyChange(t *testing.T) { r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(nil))) - require.InDelta(t, 0.25, r.ZonalOwnership(Write)["a2"], ownershipTolerance) + require.InDelta(t, 0.25, r.ZonalOwnership()["a2"], ownershipTolerance) // Same tokens, different state: updateRingState takes its fast path. - r.updateRingState(newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){"a2": withState(JOINING)}))) + r.updateRingState(newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){"a2": withState(READONLY)}))) - got := r.ZonalOwnership(Write) + got := r.ZonalOwnership() assert.Zero(t, got["a2"]) assert.InDelta(t, 0.75, got["a3"], ownershipTolerance) } +func TestRing_ZonalOwnership_KeptOnOtherStateChangesAndHeartbeats(t *testing.T) { + r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(nil))) + first := reflect.ValueOf(r.ZonalOwnership()).Pointer() + + desc := newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){"a2": withState(LEAVING)})) + for id, instance := range desc.Ingesters { + instance.Timestamp++ + desc.Ingesters[id] = instance + } + r.updateRingState(desc) + + assert.Equal(t, first, reflect.ValueOf(r.ZonalOwnership()).Pointer()) +} + func TestRing_ZonalOwnership_InvalidatedOnTokenChange(t *testing.T) { r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(nil))) - require.InDelta(t, 0.25, r.ZonalOwnership(Write)["a1"], ownershipTolerance) + require.InDelta(t, 0.25, r.ZonalOwnership()["a1"], ownershipTolerance) // Moving a1's token from q to q/4 shrinks its range to 1/16 and grows a2's. r.updateRingState(newOwnershipTestDesc(handPickedInstances(map[string]func(*ownershipTestInstance){ "a1": func(i *ownershipTestInstance) { i.tokens = []uint32{quarterOfRing / 4} }, }))) - got := r.ZonalOwnership(Write) + got := r.ZonalOwnership() assert.InDelta(t, 0.0625, got["a1"], ownershipTolerance) assert.InDelta(t, 0.4375, got["a2"], ownershipTolerance) } -func TestRing_ZonalOwnership_CachedSubringInvalidatedOnStateChange(t *testing.T) { +func TestRing_ZonalOwnership_Subrings(t *testing.T) { const ( zones = 2 perZone = 4 @@ -317,7 +319,7 @@ func TestRing_ZonalOwnership_CachedSubringInvalidatedOnStateChange(t *testing.T) r := newOwnershipTestRing(t, zones, newOwnershipTestDesc(instances)) subring := r.ShuffleShard(tenant, shardSize) - subOwnership := subring.(ZonalOwnershipRing).ZonalOwnership(Write) + subOwnership := subring.(ZonalOwnershipRing).ZonalOwnership() require.Len(t, subOwnership, shardSize) sumByZone := map[string]float64{} @@ -337,16 +339,71 @@ func TestRing_ZonalOwnership_CachedSubringInvalidatedOnStateChange(t *testing.T) } require.Positive(t, subOwnership[target]) - // Change only the target's state in the parent ring. The subring is served - // from the cache with refreshed states, so its ownership must be recomputed. - for i := range instances { - if instances[i].id == target { - instances[i].state = JOINING + setTarget := func(state InstanceState) { + for i := range instances { + if instances[i].id == target { + instances[i].state = state + } } + r.updateRingState(newOwnershipTestDesc(instances)) } - r.updateRingState(newOwnershipTestDesc(instances)) - cachedSubring := r.ShuffleShard(tenant, shardSize) - require.Same(t, subring, cachedSubring, "expected the cached subring") - assert.Zero(t, cachedSubring.(ZonalOwnershipRing).ZonalOwnership(Write)[target]) + // A state change other than READONLY keeps the cached subring and its + // ownership. + setTarget(LEAVING) + cached := r.ShuffleShard(tenant, shardSize) + require.Same(t, subring, cached) + assert.Equal(t, reflect.ValueOf(subOwnership).Pointer(), reflect.ValueOf(cached.(ZonalOwnershipRing).ZonalOwnership()).Pointer()) + + // READONLY resets the subring cache, and the new subring leaves it out. + setTarget(READONLY) + rebuilt := r.ShuffleShard(tenant, shardSize) + require.NotSame(t, subring, rebuilt) + assert.Zero(t, rebuilt.(ZonalOwnershipRing).ZonalOwnership()[target]) +} + +func TestRing_HasDuplicateTokens(t *testing.T) { + tests := map[string]struct { + instances []ownershipTestInstance + expected bool + }{ + "no shared token": { + instances: []ownershipTestInstance{ + {id: "a1", zone: "a", tokens: []uint32{1, 2}, state: ACTIVE}, + {id: "b1", zone: "b", tokens: []uint32{3}, state: ACTIVE}, + }, + }, + "a token shared across zones": { + instances: []ownershipTestInstance{ + {id: "a1", zone: "a", tokens: []uint32{1, 2}, state: ACTIVE}, + {id: "b1", zone: "b", tokens: []uint32{2}, state: ACTIVE}, + }, + expected: true, + }, + "a token shared within a zone": { + instances: []ownershipTestInstance{ + {id: "a1", zone: "a", tokens: []uint32{1}, state: ACTIVE}, + {id: "a2", zone: "a", tokens: []uint32{1}, state: ACTIVE}, + }, + expected: true, + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + r := newOwnershipTestRing(t, 1, newOwnershipTestDesc(tc.instances)) + assert.Equal(t, tc.expected, r.HasDuplicateTokens()) + }) + } +} + +// Callers tell whether ShuffleShard used the whole ring by comparing the result +// with the ring itself, so it must return the receiver, not a copy. +func TestRing_ShuffleShardReturnsTheRingItselfWhenItCoversTheRing(t *testing.T) { + r := newOwnershipTestRing(t, 2, newOwnershipTestDesc(handPickedInstances(nil))) + instances := r.InstancesCount() + + for _, size := range []int{-1, 0, instances, instances + 1} { + assert.Same(t, r, r.ShuffleShard("tenant", size), "shard size %d", size) + } + assert.NotSame(t, r, r.ShuffleShard("tenant", instances-1)) } From 91f3c91e1d560da6de5ea7e3cff723cd4e19997e Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 17:52:09 +0000 Subject: [PATCH 02/18] ingester: keep only each tenant's ownership share The refresher computed every tenant's share on each 10s refresh by building a shuffle-shard subring per tenant, and the ring it read from cached every subring. A READONLY or topology change in any zone clears that cache, and the next refresh rebuilt and recomputed every tenant: over a second per 1,000 tenants with shard size 30 at 3,000 ingesters, plus the cached subrings, 43 to 401 MB. Keep one share per tenant, with a fingerprint of the subring it was computed from: each member's zone, tokens and whether it is READONLY. The heartbeat delegate bumps a generation when an instance joins or leaves, changes zone or tokens, or becomes or stops being READONLY, in any zone: the only changes that can move a shuffle-shard pick or zonal ownership. After a bump, the refresher builds each tenant's subring and computes ownership only if its fingerprint changed. Heartbeats and other state changes cost nothing. While two zones share a token, an instance outside a subring can change its ownership, so every tenant is recomputed after a bump. The ring is built with SubringCacheDisabled, since a subring is built only to check or compute one share. The delegate updates the ring and its record under one lock: heartbeat callbacks can overlap, and otherwise the ring could hold one desc while the record held another. Shares now count every instance's tokens except READONLY instances'. With -distributor.extend-writes=true, the default, the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. The ingester no longer needs the distributor's extend-writes setting. Signed-off-by: Alan Protasio --- CHANGELOG.md | 1 + pkg/cortex/modules.go | 1 - pkg/ingester/ingester.go | 5 +- pkg/ingester/ownership.go | 202 ++++++++++- pkg/ingester/ownership_test.go | 644 ++++++++++++++++++++++++++++++++- 5 files changed, 828 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bea11a112..5ed5e82676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`. With zone-aware replication, global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share. Requires zone-aware replication; while the number of zones in the ring differs from the replication factor, the equal-share conversion is used. On an unevenly balanced ring the equal-share assumption throttles tenants on the ingesters with the largest share well before they reach their global limit. The ring is read from the ingester's own heartbeats, so no KV store traffic is added. The share in use is exposed as `cortex_ingester_ring_ownership_share{user}`. #7954 +* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cost anything. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while tokens are shared across zones, every tenant is. Shares now count every instance's tokens except READONLY instances'; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 diff --git a/pkg/cortex/modules.go b/pkg/cortex/modules.go index 02dc162a17..d787a6b242 100644 --- a/pkg/cortex/modules.go +++ b/pkg/cortex/modules.go @@ -524,7 +524,6 @@ func (t *Cortex) initIngesterService() (serv services.Service, err error) { t.Cfg.Ingester.LifecyclerConfig.ListenPort = t.Cfg.Server.GRPCListenPort t.Cfg.Ingester.DistributorShardingStrategy = t.Cfg.Distributor.ShardingStrategy t.Cfg.Ingester.DistributorShardByAllLabels = t.Cfg.Distributor.ShardByAllLabels - t.Cfg.Ingester.DistributorExtendWrites = t.Cfg.Distributor.ExtendWrites t.Cfg.Ingester.InstanceLimitsFn = ingesterInstanceLimits(t.RuntimeConfig) t.tsdbIngesterConfig() diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index f08131c8a5..199a81f141 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -154,7 +154,6 @@ type Config struct { // to accurately apply global limits. DistributorShardingStrategy string `yaml:"-"` DistributorShardByAllLabels bool `yaml:"-"` - DistributorExtendWrites bool `yaml:"-"` UseRingOwnershipForLimits bool `yaml:"use_ring_ownership_for_limits"` @@ -918,12 +917,12 @@ func New(cfg Config, limits *validation.Overrides, registerer prometheus.Registe ) if cfg.UseRingOwnershipForLimits { - ownershipRing, err := ring.NewDescFedRing(cfg.LifecyclerConfig.RingConfig, "ingester-ownership", RingKey, i.lifecycler.KVStore, logger) + ownershipRing, err := newOwnershipRing(cfg.LifecyclerConfig.RingConfig, i.lifecycler.KVStore, logger) if err != nil { return nil, errors.Wrap(err, "failed to create the ring for ownership-based limits") } ownershipDelegate.ring.Store(ownershipRing) - i.ownershipRefresher = newOwnershipRefresher(ownershipRing, i.lifecycler.ID, cfg.DistributorExtendWrites, i.limiter.shuffleShardingEnabled, limits, registerer) + i.ownershipRefresher = newOwnershipRefresher(ownershipRing, i.lifecycler.ID, i.limiter.shuffleShardingEnabled, limits, registerer, ownershipDelegate.generation.Load) i.limiter.ownership = i.ownershipRefresher.ownership } diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 9eef2563bd..9ae11831c3 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -1,14 +1,18 @@ package ingester import ( + "maps" + "sync" "time" + "github.com/go-kit/log" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "go.uber.org/atomic" "github.com/cortexproject/cortex/pkg/ring" + "github.com/cortexproject/cortex/pkg/ring/kv" "github.com/cortexproject/cortex/pkg/util/validation" ) @@ -22,14 +26,70 @@ const ownershipRefreshPeriod = 10 * time.Second // reads on every heartbeat, so tracking ownership adds no KV store traffic. type ringOwnershipDelegate struct { ring atomic.Pointer[ring.Ring] + + // Bumped after each ring update that can change a shuffle-shard pick or + // zonal ownership anywhere in the ring. + generation atomic.Uint64 + + mtx sync.Mutex + instances map[string]instanceRecord +} + +// instanceRecord is what shuffle-shard picks and zonal ownership read of an +// instance. +type instanceRecord struct { + zone string + readOnly bool + tokens uint64 } // OnRingInstanceHeartbeat runs inside the Lifecycler's CAS callback, with the // ring about to be written to the KV store. UpdateDesc copies it. func (d *ringOwnershipDelegate) OnRingInstanceHeartbeat(_ *ring.Lifecycler, ringDesc *ring.Desc) { - if r := d.ring.Load(); r != nil { - r.UpdateDesc(ringDesc) + r := d.ring.Load() + if r == nil { + return + } + // Callbacks can overlap, so the ring and the record are updated together. + d.mtx.Lock() + defer d.mtx.Unlock() + // Update the ring before bumping the generation, so a refresh that reads + // the new generation computes from the new ring. + r.UpdateDesc(ringDesc) + + // Shuffle-shard picks skip READONLY instances and zonal ownership leaves + // them out, so only instances, zones, tokens and READONLY matter. + // Heartbeats and other state changes do not. + instances := make(map[string]instanceRecord, len(ringDesc.Ingesters)) + for id, instance := range ringDesc.Ingesters { + instances[id] = instanceRecord{ + zone: instance.Zone, + readOnly: instance.State == ring.READONLY, + tokens: hashTokens(instance.Tokens), + } + } + if d.instances == nil || !maps.Equal(d.instances, instances) { + d.instances = instances + d.generation.Inc() + } +} + +// hashTokens returns a 64-bit FNV-1a hash of tokens. +func hashTokens(tokens []uint32) uint64 { + h := uint64(14695981039346656037) + for _, token := range tokens { + h ^= uint64(token) + h *= 1099511628211 } + return h +} + +// newOwnershipRing returns the ring the ownership shares are computed from. It +// is fed by ringOwnershipDelegate and only a share per tenant is kept, so +// subrings are not cached. +func newOwnershipRing(cfg ring.Config, kvClient kv.Client, logger log.Logger) (*ring.Ring, error) { + cfg.SubringCacheDisabled = true + return ring.NewDescFedRing(cfg, "ingester-ownership", RingKey, kvClient, logger) } // tenantOwnership holds this ingester's share of each tenant's hash space @@ -54,24 +114,32 @@ func (t *tenantOwnership) share(userID string) (float64, bool) { type ownershipRefresher struct { ring *ring.Ring instanceID string - writeOp ring.Operation shuffleShardingEnabled bool limits *validation.Overrides ownership *tenantOwnership shareGauge *prometheus.GaugeVec + computations prometheus.Counter + + // generation returns a value that changes whenever the ring may give this + // ingester a different share. Nil recomputes every share on each refresh. + generation func() uint64 + + // The last share computed per tenant. Only touched by refresh. + tenants map[string]tenantShare } -func newOwnershipRefresher(r *ring.Ring, instanceID string, extendWrites, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer) *ownershipRefresher { - // Must match the operation the distributor writes with, or the shares - // would not describe where series are sent. - writeOp := ring.WriteNoExtend - if extendWrites { - writeOp = ring.Write - } +type tenantShare struct { + generation uint64 + shardSize int + fingerprint uint64 + share float64 + zones int +} + +func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer, generation func() uint64) *ownershipRefresher { return &ownershipRefresher{ ring: r, instanceID: instanceID, - writeOp: writeOp, shuffleShardingEnabled: shuffleShardingEnabled, limits: limits, ownership: &tenantOwnership{}, @@ -79,6 +147,11 @@ func newOwnershipRefresher(r *ring.Ring, instanceID string, extendWrites, shuffl Name: "cortex_ingester_ring_ownership_share", Help: "Share of the tenant's hash space this ingester owns within its zone, used to convert global limits to local ones. Only reported for tenants whose limits use it.", }, []string{"user"}), + computations: promauto.With(registerer).NewCounter(prometheus.CounterOpts{ + Name: "cortex_ingester_ring_ownership_computations_total", + Help: "Number of times a tenant's ring ownership share was computed.", + }), + generation: generation, } } @@ -87,22 +160,56 @@ func (o *ownershipRefresher) refresh(userIDs []string) { // No heartbeat has fed the ring yet. return } + // Read before computing, so a ring change during the refresh makes the next + // one recompute. + var generation uint64 + if o.generation != nil { + generation = o.generation() + } + // A token shared by two zones lets an instance outside a tenant's subring + // decide this zone's ownership, which the fingerprint does not cover. + duplicates := o.ring.HasDuplicateTokens() + + var wholeRingFingerprint *uint64 + tenants := make(map[string]tenantShare, len(userIDs)) shares := make(map[string]float64, len(userIDs)) for _, userID := range userIDs { - var sub ring.ReadRing = o.ring - if size := o.limits.IngestionTenantShardSize(userID); o.shuffleShardingEnabled && size > 0 { - // Same subring the distributor routes the tenant's writes with. - sub = o.ring.ShuffleShard(userID, size) + size := 0 + if o.shuffleShardingEnabled { + size = o.limits.IngestionTenantShardSize(userID) + } + t, ok := o.tenants[userID] + if o.generation == nil || !ok || t.generation != generation || t.shardSize != size { + sub := o.subring(userID, size) + var fingerprint uint64 + if sub == ring.ReadRing(o.ring) { + // Every whole-ring tenant has the same one. + if wholeRingFingerprint == nil { + f := subringFingerprint(sub) + wholeRingFingerprint = &f + } + fingerprint = *wholeRingFingerprint + } else { + fingerprint = subringFingerprint(sub) + } + if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != fingerprint || duplicates { + t = o.computeShare(sub) + t.shardSize = size + t.fingerprint = fingerprint + } + t.generation = generation } - zonal, ok := sub.(ring.ZonalOwnershipRing) + tenants[userID] = t + // Shares describe one copy per zone. When a zone is missing from the // ring, Get puts a second copy in another zone, so leave the tenant out // and let the limiter use the even split, which accounts for it. - if !ok || zonal.ZonesCount() != o.ring.ReplicationFactor() { + if t.zones != o.ring.ReplicationFactor() { continue } - shares[userID] = zonal.ZonalOwnership()[o.instanceID] + shares[userID] = t.share } + o.tenants = tenants o.ownership.shares.Store(&shares) o.shareGauge.Reset() @@ -110,3 +217,62 @@ func (o *ownershipRefresher) refresh(userIDs []string) { o.shareGauge.WithLabelValues(userID).Set(share) } } + +// subring returns the ring the distributor routes the tenant's writes with. +func (o *ownershipRefresher) subring(userID string, shardSize int) ring.ReadRing { + if shardSize <= 0 { + return o.ring + } + return o.ring.ShuffleShard(userID, shardSize) +} + +func (o *ownershipRefresher) computeShare(sub ring.ReadRing) tenantShare { + o.computations.Inc() + zonal, ok := sub.(ring.ZonalOwnershipRing) + if !ok { + return tenantShare{} + } + return tenantShare{ + share: zonal.ZonalOwnership()[o.instanceID], + zones: zonal.ZonesCount(), + } +} + +// subringFingerprint hashes what zonal ownership reads of a subring's members: +// each member's zone, tokens and whether it is READONLY, combined in any order. +// It does not cover the ring-wide token map, which a token shared with an +// instance outside the subring changes. +func subringFingerprint(sub ring.ReadRing) uint64 { + healthy, unhealthy, _ := sub.GetAllInstanceDescs(ring.Reporting) + var h uint64 + for _, members := range [][]ring.InstanceDesc{healthy, unhealthy} { + for _, member := range members { + m := hashTokens(member.Tokens) ^ hashString(member.Zone) + if member.State == ring.READONLY { + m = ^m + } + h += mix64(m) + } + } + return h +} + +func hashString(s string) uint64 { + h := uint64(14695981039346656037) + for i := 0; i < len(s); i++ { + h ^= uint64(s[i]) + h *= 1099511628211 + } + return h +} + +// mix64 is the splitmix64 finalizer, so that summing member hashes does not +// let similar members cancel out. +func mix64(x uint64) uint64 { + x ^= x >> 30 + x *= 0xbf58476d1ce4e5b9 + x ^= x >> 27 + x *= 0x94d049bb133111eb + x ^= x >> 31 + return x +} diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 81063d656d..6b7d375a84 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -2,13 +2,16 @@ package ingester import ( "fmt" + "maps" "math" "math/rand" "slices" + "sync" "testing" "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -119,7 +122,7 @@ func TestOwnershipRefresher(t *testing.T) { overrides := validation.NewOverrides(limits, tenantLimits) ingesterID := ownershipTestInstanceID(0, 0) - refresher := newOwnershipRefresher(r, ingesterID, true, true, overrides, nil) + refresher := newOwnershipRefresher(r, ingesterID, true, overrides, nil, nil) // Nothing is known before the ring has been fed. refresher.refresh([]string{shuffledTenant, unshuffledTenant}) @@ -154,7 +157,7 @@ func TestOwnershipRefresher_ZoneMissingFromRing(t *testing.T) { r := newOwnershipTestRing(t, 3, nil) r.UpdateDesc(newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) - refresher := newOwnershipRefresher(r, ownershipTestInstanceID(0, 0), true, false, validation.NewOverrides(validation.Limits{}, nil), nil) + refresher := newOwnershipRefresher(r, ownershipTestInstanceID(0, 0), false, validation.NewOverrides(validation.Limits{}, nil), nil, nil) refresher.refresh([]string{tenant}) _, ok := refresher.ownership.share(tenant) @@ -272,7 +275,7 @@ func TestLimiter_OwnershipAvoidsThrottlingOnUnevenRing(t *testing.T) { throttledByEvenSplit++ } - refresher := newOwnershipRefresher(r, id, true, false, overrides, nil) + refresher := newOwnershipRefresher(r, id, false, overrides, nil, nil) refresher.refresh([]string{tenant}) byOwnership := NewLimiter(overrides, ringCount, util.ShardingStrategyDefault, true, layout.zones, true, "") byOwnership.ownership = refresher.ownership @@ -294,3 +297,638 @@ func (s *staticTenantLimits) ByUserID(userID string) *validation.Limits { func (s *staticTenantLimits) AllByUserID() map[string]*validation.Limits { return s.limits } + +func newOwnershipTestDelegate(t *testing.T, _ string, replicationFactor int) (*ringOwnershipDelegate, *ring.Ring) { + t.Helper() + kvClient, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) + t.Cleanup(func() { _ = closer.Close() }) + r, err := newOwnershipRing(ring.Config{HeartbeatTimeout: time.Minute, ReplicationFactor: replicationFactor, ZoneAwarenessEnabled: true}, kvClient, log.NewNopLogger()) + require.NoError(t, err) + + d := &ringOwnershipDelegate{} + d.ring.Store(r) + return d, r +} + +// cloneOwnershipTestDesc returns a copy of desc that a test can modify. +func cloneOwnershipTestDesc(desc *ring.Desc) *ring.Desc { + out := ring.NewDesc() + for id, instance := range desc.Ingesters { + instance.Tokens = slices.Clone(instance.Tokens) + out.Ingesters[id] = instance + } + return out +} + +func setOwnershipTestState(id string, state ring.InstanceState) func(*ring.Desc) { + return func(d *ring.Desc) { + instance := d.Ingesters[id] + instance.State = state + d.Ingesters[id] = instance + } +} + +func TestNewOwnershipRing_DoesNotCacheSubrings(t *testing.T) { + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + d, r := newOwnershipTestDelegate(t, ownershipTestInstanceID(0, 0), layout.zones) + d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) + + assert.NotSame(t, r.ShuffleShard("tenant", 6), r.ShuffleShard("tenant", 6)) +} + +func TestRingOwnershipDelegate_Generation(t *testing.T) { + me := ownershipTestInstanceID(0, 0) + neighbour := ownershipTestInstanceID(0, 1) + other := ownershipTestInstanceID(1, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 3, tokensPerInstance: 4} + changeTokens := func(id string) func(*ring.Desc) { + return func(d *ring.Desc) { + instance := d.Ingesters[id] + instance.Tokens[0]++ + d.Ingesters[id] = instance + } + } + + tests := map[string]struct { + prepare func(*ring.Desc) + change func(*ring.Desc) + bumped bool + }{ + "heartbeat only": {change: func(d *ring.Desc) { + for id, instance := range d.Ingesters { + instance.Timestamp++ + d.Ingesters[id] = instance + } + }}, + "a state change other than READONLY in my zone": {change: setOwnershipTestState(neighbour, ring.LEAVING)}, + "a state change other than READONLY in other zone": {change: setOwnershipTestState(other, ring.JOINING)}, + "my own state change": {change: setOwnershipTestState(me, ring.LEAVING)}, + "an instance becomes READONLY in my zone": {change: setOwnershipTestState(neighbour, ring.READONLY), bumped: true}, + "an instance becomes READONLY in another zone": {change: setOwnershipTestState(other, ring.READONLY), bumped: true}, + "an instance stops being READONLY": { + prepare: setOwnershipTestState(other, ring.READONLY), change: setOwnershipTestState(other, ring.ACTIVE), bumped: true, + }, + "an instance joins": { + change: func(d *ring.Desc) { d.AddIngester("new", "new", "zone-1", []uint32{42}, ring.JOINING, time.Time{}) }, bumped: true, + }, + "an instance leaves": {change: func(d *ring.Desc) { d.RemoveIngester(other) }, bumped: true}, + "tokens change": {change: changeTokens(other), bumped: true}, + "a tokenless instance gets tokens": { + prepare: func(d *ring.Desc) { d.AddIngester("new", "new", "zone-new", nil, ring.PENDING, time.Time{}) }, + change: func(d *ring.Desc) { + instance := d.Ingesters["new"] + instance.Tokens = []uint32{42} + d.Ingesters["new"] = instance + }, + bumped: true, + }, + "an instance changes zone": { + change: func(d *ring.Desc) { + instance := d.Ingesters[other] + instance.Zone = "zone-2" + d.Ingesters[other] = instance + }, + bumped: true, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + d, _ := newOwnershipTestDelegate(t, me, layout.zones) + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + if tc.prepare != nil { + tc.prepare(desc) + } + d.OnRingInstanceHeartbeat(nil, desc) + require.Equal(t, uint64(1), d.generation.Load(), "the first ring is a change") + + next := cloneOwnershipTestDesc(desc) + tc.change(next) + d.OnRingInstanceHeartbeat(nil, next) + + assert.Equal(t, tc.bumped, d.generation.Load() != 1) + }) + } +} + +func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testing.T) { + const ( + tenant = "tenant" + shardSize = 6 + ) + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + + limits := &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}} + overrides := validation.NewOverrides(validation.Limits{}, limits) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + require.Equal(t, 1.0, testutil.ToFloat64(refresher.computations)) + + // An instance outside the tenant's subring and one in it. + members := map[string]bool{} + healthy, unhealthy, err := r.ShuffleShard(tenant, shardSize).GetAllInstanceDescs(ring.Reporting) + require.NoError(t, err) + for _, member := range append(healthy, unhealthy...) { + members[member.Addr] = true + } + var outside, inside string + for _, id := range slices.Sorted(maps.Keys(desc.Ingesters)) { + if id == me { + continue + } + if members[desc.Ingesters[id].Addr] && inside == "" { + inside = id + } + if !members[desc.Ingesters[id].Addr] && outside == "" { + outside = id + } + } + require.NotEmpty(t, outside) + require.NotEmpty(t, inside) + + update := func(change func(*ring.Desc)) float64 { + before := testutil.ToFloat64(refresher.computations) + change(desc) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh([]string{tenant}) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants)) + return testutil.ToFloat64(refresher.computations) - before + } + + assert.Zero(t, update(setOwnershipTestState(inside, ring.LEAVING)), "not READONLY: the ring has not changed") + assert.Zero(t, update(setOwnershipTestState(outside, ring.READONLY)), "the ring changed, the tenant's subring did not") + assert.Equal(t, 1.0, update(setOwnershipTestState(inside, ring.READONLY)), "a member of the tenant's subring changed") + + limits.limits[tenant] = &validation.Limits{IngestionTenantShardSize: shardSize + 3} + refresher.refresh([]string{tenant}) + assert.Equal(t, shardSize+3, refresher.tenants[tenant].shardSize) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants)) + + refresher.refresh(nil) + assert.Empty(t, refresher.tenants, "a tenant gone from the ingester is dropped") +} + +// A neighbour going from LEAVING to READONLY moves this ingester's share, +// because shard picks skip READONLY instances. On this layout the share goes +// from 0 to about 0.54. +func TestOwnershipRefresher_ReadOnlyNeighbourChangesTheShardPick(t *testing.T) { + // The tenant name and the seed below pick a layout where this happens. + const tenant = "t" + me := ownershipTestInstanceID(0, 0) + neighbour := ownershipTestInstanceID(0, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 6, tokensPerInstance: 8} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(3)), layout) + limits := &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}} + overrides := validation.NewOverrides(validation.Limits{}, limits) + + setOwnershipTestState(neighbour, ring.LEAVING)(desc) + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, desc) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + before := refresher.tenants[tenant].share + + next := cloneOwnershipTestDesc(desc) + setOwnershipTestState(neighbour, ring.READONLY)(next) + d.OnRingInstanceHeartbeat(nil, next) + refresher.refresh([]string{tenant}) + + fresh := newOwnershipRefresher(r, me, true, overrides, nil, nil) + fresh.refresh([]string{tenant}) + require.NotEqual(t, before, fresh.tenants[tenant].share, "the layout must make the pick change") + assert.Equal(t, fresh.tenants[tenant].share, refresher.tenants[tenant].share) +} + +// unevenOwnershipTestDesc returns a ring of 12 instances, 6 in zone-0 and 3 +// in each other zone, so that a shard of 11 is a strict subset of zone-0. +func unevenOwnershipTestDesc() *ring.Desc { + desc := ring.NewDesc() + rnd := rand.New(rand.NewSource(ownershipTestSeed)) + for z, n := range []int{6, 3, 3} { + for i := range n { + tokens := make([]uint32, 16) + for k := range tokens { + tokens[k] = rnd.Uint32() + } + slices.Sort(tokens) + id := ownershipTestInstanceID(z, i) + desc.AddIngester(id, id+"-addr", fmt.Sprintf("zone-%d", z), tokens, ring.ACTIVE, time.Time{}) + } + } + return desc +} + +// A tenant whose shard size reaches the instance count uses the whole ring, so +// an instance leaving another zone changes its share. +func TestOwnershipRefresher_RecomputesWhenATenantSwitchesToTheWholeRing(t *testing.T) { + const shardSize = 11 + me := ownershipTestInstanceID(0, 0) + desc := unevenOwnershipTestDesc() + tenant := "" + for i := range 100 { + candidate := fmt.Sprintf("tenant-%d", i) + o := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{candidate: {IngestionTenantShardSize: shardSize}}}) + if freshOwnershipShares(t, desc, me, o, []string{candidate})[candidate].share > 0 { + tenant = candidate + break + } + } + require.NotEmpty(t, tenant) + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}}) + + d, r := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + before := refresher.tenants[tenant].share + + next := cloneOwnershipTestDesc(desc) + next.RemoveIngester(ownershipTestInstanceID(1, 0)) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) + refresher.refresh([]string{tenant}) + + fresh := freshOwnershipShares(t, next, me, overrides, []string{tenant}) + require.NotEqual(t, before, fresh[tenant].share, "the layout must make the switch move the share") + assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) +} + +// Through any sequence of ring changes, the shares a refresher reuses must +// equal those computed from scratch on a separate ring, so that a bug in the +// reuse or in the ring's caches cannot show on both sides. +func TestOwnershipRefresher_CachedSharesMatchFreshComputation(t *testing.T) { + for _, sharedTokens := range []bool{false, true} { + t.Run(fmt.Sprintf("shared tokens %t", sharedTokens), func(t *testing.T) { + testOwnershipRefresherCachedSharesMatchFreshComputation(t, sharedTokens) + }) + } +} + +func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, sharedTokens bool) { + const steps = 300 + states := []ring.InstanceState{ring.ACTIVE, ring.ACTIVE, ring.ACTIVE, ring.JOINING, ring.LEAVING, ring.PENDING, ring.READONLY} + me := ownershipTestInstanceID(0, 0) + rnd := rand.New(rand.NewSource(ownershipTestSeed)) + layout := ownershipTestRingLayout{zones: 3, perZone: 5, tokensPerInstance: 8} + desc := newOwnershipTestDesc(rnd, layout) + + tenantLimits := map[string]*validation.Limits{} + var tenants []string + for i, size := range []int{0, 3, 6, 9, 13, 14, 15, 16, 30} { + tenant := fmt.Sprintf("tenant-%d", i) + tenants = append(tenants, tenant) + tenantLimits[tenant] = &validation.Limits{IngestionTenantShardSize: size} + } + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: tenantLimits}) + + d, r := newOwnershipTestDelegate(t, me, layout.zones) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + added, bumps := 0, 0 + newToken := func(d *ring.Desc) uint32 { + if sharedTokens && rnd.Intn(3) == 0 { + // A token some instance of another zone already holds. + for _, instance := range d.Ingesters { + if len(instance.Tokens) > 0 { + return instance.Tokens[rnd.Intn(len(instance.Tokens))] + } + } + } + return rnd.Uint32() + } + + for step := range steps { + next := cloneOwnershipTestDesc(desc) + for id, instance := range next.Ingesters { + instance.Timestamp++ + next.Ingesters[id] = instance + } + ids := slices.Sorted(maps.Keys(next.Ingesters)) + id := ids[rnd.Intn(len(ids))] + instance := next.Ingesters[id] + switch rnd.Intn(12) { + case 0: // an instance leaves + if id != me { + next.RemoveIngester(id) + } + case 1: // an instance joins, sometimes in a new zone + added++ + zone := fmt.Sprintf("zone-%d", rnd.Intn(layout.zones+1)) + name := fmt.Sprintf("added-%d", added) + next.AddIngester(name, name+"-addr", zone, []uint32{newToken(next), newToken(next)}, ring.JOINING, time.Time{}) + case 2: // an instance joins without tokens + added++ + name := fmt.Sprintf("added-%d", added) + next.AddIngester(name, name+"-addr", fmt.Sprintf("zone-%d", rnd.Intn(layout.zones+1)), nil, ring.PENDING, time.Time{}) + case 3: // tokens change, including a tokenless instance getting its first + instance.Tokens = append(slices.Clone(instance.Tokens), newToken(next)) + slices.Sort(instance.Tokens) + next.Ingesters[id] = instance + case 4: // an instance moves zone + if id != me { + instance.Zone = fmt.Sprintf("zone-%d", rnd.Intn(layout.zones+1)) + next.Ingesters[id] = instance + } + case 5, 6, 7, 8: + instance.State = states[rnd.Intn(len(states))] + next.Ingesters[id] = instance + } + desc = next + before := d.generation.Load() + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + if d.generation.Load() != before { + bumps++ + } + refresher.refresh(tenants) + + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), withoutGeneration(refresher.tenants), "step %d", step) + } + // Not a correctness condition: shows the test exercises reuse. + t.Logf("the generation changed on %d of %d steps; ownership computed %v times", bumps, steps, testutil.ToFloat64(refresher.computations)) + assert.Less(t, bumps, steps) +} + +func withoutGeneration(tenants map[string]tenantShare) map[string]tenantShare { + out := make(map[string]tenantShare, len(tenants)) + for id, t := range tenants { + t.generation = 0 + out[id] = t + } + return out +} + +// Heartbeat callbacks can overlap: the Lifecycler's first heartbeat runs on its +// own goroutine. If the ring were updated outside the delegate's lock, one +// callback could update the ring after another, then compare first and find no +// change, leaving the ring and the recorded desc different for good. So a +// callback must not touch the ring while another holds the lock. +func TestRingOwnershipDelegate_UpdatesTheRingUnderTheLock(t *testing.T) { + const wait = 50 * time.Millisecond + me := ownershipTestInstanceID(0, 0) + neighbour := ownershipTestInstanceID(0, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 3, tokensPerInstance: 4} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + + readOnly := cloneOwnershipTestDesc(desc) + setOwnershipTestState(neighbour, ring.READONLY)(readOnly) + neighbourIsReadOnly := func() bool { + state, err := r.GetInstanceState(neighbour) + require.NoError(t, err) + return state == ring.READONLY + } + + d.mtx.Lock() + done := make(chan struct{}) + go func() { + defer close(done) + d.OnRingInstanceHeartbeat(nil, readOnly) + }() + time.Sleep(wait) + assert.False(t, neighbourIsReadOnly(), "the ring was updated while another callback held the lock") + d.mtx.Unlock() + + <-done + assert.True(t, neighbourIsReadOnly()) + assert.True(t, d.instances[neighbour].readOnly) +} + +// freshOwnershipShares computes the shares from scratch on a new ring, so a bug +// in the reuse or in the ring's caches cannot show on both sides. +func freshOwnershipShares(t *testing.T, desc *ring.Desc, me string, overrides *validation.Overrides, tenants []string) map[string]tenantShare { + t.Helper() + _, r := newOwnershipTestDelegate(t, me, 3) + r.UpdateDesc(desc) + fresh := newOwnershipRefresher(r, me, true, overrides, nil, nil) + fresh.refresh(tenants) + return withoutGeneration(fresh.tenants) +} + +// collidingOwnershipTestDesc returns a ring where an instance of zone-1 holds +// a token of a zone-0 neighbour of me, the one just before a token of me. The +// zone-1 instance's ID sorts after every zone-0 ID, so it wins the ring-wide +// token map, and its state decides who owns me's preceding range. +func collidingOwnershipTestDesc(t *testing.T, layout ownershipTestRingLayout, me, collider string) *ring.Desc { + t.Helper() + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + owner := map[uint32]string{} + var tokens []uint32 + for id, instance := range desc.Ingesters { + if instance.Zone == "zone-0" { + for _, token := range instance.Tokens { + owner[token] = id + tokens = append(tokens, token) + } + } + } + slices.Sort(tokens) + for i, token := range tokens { + if owner[token] != me && owner[tokens[(i+1)%len(tokens)]] == me { + instance := desc.Ingesters[collider] + instance.Tokens = append(slices.Clone(instance.Tokens[1:]), token) + slices.Sort(instance.Tokens) + desc.Ingesters[collider] = instance + return desc + } + } + t.Fatal("no token found") + return nil +} + +func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { + const tenant = "tenant" + me := ownershipTestInstanceID(0, 0) + collider := ownershipTestInstanceID(1, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + overrides := validation.NewOverrides(validation.Limits{}, nil) + tenants := []string{tenant} + + tests := map[string]struct { + // Starts from a ring without the shared token when false. + sharedFromStart bool + prepare func(*ring.Desc) + change func(*ring.Desc) + }{ + "the instance holding it in another zone becomes READONLY": { + sharedFromStart: true, + change: setOwnershipTestState(collider, ring.READONLY), + }, + "an instance joins another zone with it": { + change: func(d *ring.Desc) { + shared := collidingOwnershipTestDesc(t, layout, me, collider).Ingesters[collider].Tokens + d.AddIngester("zone-1-joined", "zone-1-joined-addr", "zone-1", shared, ring.READONLY, time.Time{}) + }, + }, + "the READONLY instance holding it in another zone leaves": { + sharedFromStart: true, + prepare: setOwnershipTestState(collider, ring.READONLY), + change: func(d *ring.Desc) { d.RemoveIngester(collider) }, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + if tc.sharedFromStart { + desc = collidingOwnershipTestDesc(t, layout, me, collider) + } + if tc.prepare != nil { + tc.prepare(desc) + } + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh(tenants) + before := refresher.tenants[tenant].share + + next := cloneOwnershipTestDesc(desc) + tc.change(next) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) + refresher.refresh(tenants) + + fresh := freshOwnershipShares(t, next, me, overrides, tenants) + require.NotEqual(t, before, fresh[tenant].share, "the layout must make the change move the share") + assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) + }) + } +} + +// hookedTenantLimits runs hook once, the first time ByUserID is called for +// user, standing in for a heartbeat that updates the ring during a refresh. +type hookedTenantLimits struct { + staticTenantLimits + user string + hook func() + once sync.Once +} + +func (h *hookedTenantLimits) ByUserID(userID string) *validation.Limits { + if userID == h.user && h.hook != nil { + h.once.Do(h.hook) + } + return h.staticTenantLimits.ByUserID(userID) +} + +// A heartbeat during a refresh can change the ring between the generation the +// refresh read and the subring it builds. The stored share must describe the +// ring it was computed from, so that the next refresh compares against the +// right one. +func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { + const shardSize = 11 + me := ownershipTestInstanceID(0, 0) + desc := unevenOwnershipTestDesc() + rnd := rand.New(rand.NewSource(ownershipTestSeed + 1)) + // A tenant whose subring includes this ingester. + tenant := "" + for i := range 100 { + candidate := fmt.Sprintf("tenant-%d", i) + o := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{candidate: {IngestionTenantShardSize: shardSize}}}) + if freshOwnershipShares(t, desc, me, o, []string{candidate})[candidate].share > 0 { + tenant = candidate + break + } + } + require.NotEmpty(t, tenant) + limits := &hookedTenantLimits{user: tenant} + limits.limits = map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}} + overrides := validation.NewOverrides(validation.Limits{}, limits) + + d, r := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh(nil) + + // During the refresh that first sees the tenant, an instance leaves zone-1, + // so ShuffleShard sees 11 instances and returns the whole ring. + shrunk := cloneOwnershipTestDesc(desc) + shrunk.RemoveIngester(ownershipTestInstanceID(1, 2)) + limits.hook = func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shrunk)) } + refresher.refresh([]string{tenant}) + require.Equal(t, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants), "the share comes from the ring ShuffleShard used") + + // An instance joins zone-2: 12 instances again. + grown := cloneOwnershipTestDesc(shrunk) + grown.AddIngester(ownershipTestInstanceID(2, 9), "zone-2-ingester-9-addr", "zone-2", []uint32{rnd.Uint32(), rnd.Uint32()}, ring.ACTIVE, time.Time{}) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(grown)) + refresher.refresh([]string{tenant}) + + fresh := freshOwnershipShares(t, grown, me, overrides, []string{tenant}) + require.NotEqual(t, fresh[tenant].share, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant})[tenant].share, "the layout must make the two rings differ") + assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) +} + +// The ring leaves excluded zones out, so changes there bump the generation +// but leave every tenant's subring, and so its share, as it was. +func TestOwnershipRefresher_ExcludedZones(t *testing.T) { + const tenant = "tenant" + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 4, perZone: 3, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + newRing := func() (*ringOwnershipDelegate, *ring.Ring) { + kvClient, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) + t.Cleanup(func() { _ = closer.Close() }) + r, err := newOwnershipRing(ring.Config{HeartbeatTimeout: time.Minute, ReplicationFactor: 3, ZoneAwarenessEnabled: true, ExcludedZones: []string{"zone-3"}}, kvClient, log.NewNopLogger()) + require.NoError(t, err) + d := &ringOwnershipDelegate{} + d.ring.Store(r) + return d, r + } + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) + + d, r := newRing() + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + require.Equal(t, 3, refresher.tenants[tenant].zones) + computed := testutil.ToFloat64(refresher.computations) + + setOwnershipTestState(ownershipTestInstanceID(3, 0), ring.READONLY)(desc) + desc.RemoveIngester(ownershipTestInstanceID(3, 1)) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh([]string{tenant}) + + assert.Equal(t, computed, testutil.ToFloat64(refresher.computations)) + _, fresh := newRing() + fresh.UpdateDesc(cloneOwnershipTestDesc(desc)) + want := newOwnershipRefresher(fresh, me, true, overrides, nil, nil) + want.refresh([]string{tenant}) + assert.Equal(t, withoutGeneration(want.tenants), withoutGeneration(refresher.tenants)) +} + +// An instance outside a tenant's subring that takes a token of this ingester +// changes the ring-wide token map the subring's ownership reads, without +// changing any subring member, so the fingerprint stays the same. The tenant, +// seed and token below were found by search to give that case. +func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { + const ( + tenant = "tenant-1" + token = uint32(1036751706) + ) + me := ownershipTestInstanceID(0, 0) + collider := ownershipTestInstanceID(1, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 6, tokensPerInstance: 8} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + require.Contains(t, desc.Ingesters[me].Tokens, token) + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) + + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + before := refresher.tenants[tenant] + + instance := desc.Ingesters[collider] + instance.Tokens = append(slices.Clone(instance.Tokens), token) + slices.Sort(instance.Tokens) + desc.Ingesters[collider] = instance + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh([]string{tenant}) + + fresh := freshOwnershipShares(t, desc, me, overrides, []string{tenant}) + require.Equal(t, before.fingerprint, fresh[tenant].fingerprint, "the layout must keep the subring the same") + require.NotEqual(t, before.share, fresh[tenant].share, "the layout must move the share") + assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) +} From 3c1ec990e2f8ae7d41afecada7ee5f20596667e9 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 20:39:45 +0000 Subject: [PATCH 03/18] ingester: recompute ownership shares computed from a changing ring Two cases kept a wrong share after the ring changed back: - While a token is shared across zones, a subring's ownership depends on an instance outside it. When the sharing ended, the subring's fingerprint was as before, so the share computed during the sharing was reused. - Whole-ring tenants read the live ring. The whole-ring fingerprint was taken once per refresh while each tenant's share was read later, so a heartbeat in between could store a share from one ring under the fingerprint of another, and a ring that returned to the old fingerprint reused it. Mark a share computed under shared tokens, or from a whole ring whose fingerprint moved during the computation, as unsure, and recompute it after the next change. Whole-ring tenants now share one share per refresh along with the fingerprint. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 34 ++++--- pkg/ingester/ownership_test.go | 172 +++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+), 12 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 9ae11831c3..8507d8e2c2 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -134,6 +134,9 @@ type tenantShare struct { fingerprint uint64 share float64 zones int + // Computed while tokens were shared across zones, or from a whole ring + // that changed during the computation: recompute after the next change. + unsure bool } func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer, generation func() uint64) *ownershipRefresher { @@ -170,7 +173,9 @@ func (o *ownershipRefresher) refresh(userIDs []string) { // decide this zone's ownership, which the fingerprint does not cover. duplicates := o.ring.HasDuplicateTokens() - var wholeRingFingerprint *uint64 + // The whole ring is read live, so its fingerprint and share are taken + // once per refresh and kept only if the ring did not change in between. + var wholeRing *tenantShare tenants := make(map[string]tenantShare, len(userIDs)) shares := make(map[string]float64, len(userIDs)) for _, userID := range userIDs { @@ -181,21 +186,26 @@ func (o *ownershipRefresher) refresh(userIDs []string) { t, ok := o.tenants[userID] if o.generation == nil || !ok || t.generation != generation || t.shardSize != size { sub := o.subring(userID, size) - var fingerprint uint64 if sub == ring.ReadRing(o.ring) { - // Every whole-ring tenant has the same one. - if wholeRingFingerprint == nil { + if wholeRing == nil { f := subringFingerprint(sub) - wholeRingFingerprint = &f + w := o.computeShare(sub) + w.fingerprint = f + w.unsure = duplicates || subringFingerprint(sub) != f + wholeRing = &w + } + if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != wholeRing.fingerprint || t.unsure || wholeRing.unsure { + t = *wholeRing + t.shardSize = size } - fingerprint = *wholeRingFingerprint } else { - fingerprint = subringFingerprint(sub) - } - if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != fingerprint || duplicates { - t = o.computeShare(sub) - t.shardSize = size - t.fingerprint = fingerprint + fingerprint := subringFingerprint(sub) + if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != fingerprint || duplicates || t.unsure { + t = o.computeShare(sub) + t.shardSize = size + t.fingerprint = fingerprint + t.unsure = duplicates + } } t.generation = generation } diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 6b7d375a84..d406a483ba 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -650,10 +650,13 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share assert.Less(t, bumps, steps) } +// withoutGeneration drops what only decides when a share is recomputed, so +// shares can be compared with ones computed from scratch. func withoutGeneration(tenants map[string]tenantShare) map[string]tenantShare { out := make(map[string]tenantShare, len(tenants)) for id, t := range tenants { t.generation = 0 + t.unsure = false out[id] = t } return out @@ -812,6 +815,11 @@ func (h *hookedTenantLimits) ByUserID(userID string) *validation.Limits { return h.staticTenantLimits.ByUserID(userID) } +// arm makes hook run the next time ByUserID is called for user. +func (h *hookedTenantLimits) arm(user string, hook func()) { + h.user, h.hook, h.once = user, hook, sync.Once{} +} + // A heartbeat during a refresh can change the ring between the generation the // refresh read and the subring it builds. The stored share must describe the // ring it was computed from, so that the next refresh compares against the @@ -932,3 +940,167 @@ func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { require.NotEqual(t, before.share, fresh[tenant].share, "the layout must move the share") assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) } + +// A share computed while a token was shared across zones depends on an +// instance outside the subring. When the sharing ends, the subring's members +// and so its fingerprint are as before, but the share is not: it must be +// recomputed. +func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { + const ( + tenant = "tenant-1" + token = uint32(1036751706) + ) + me := ownershipTestInstanceID(0, 0) + collider := ownershipTestInstanceID(1, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 6, tokensPerInstance: 8} + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) + tenants := []string{tenant} + + for name, end := range map[string]func(*ring.Desc){ + "the other instance drops the token": func(*ring.Desc) {}, + "the other instance leaves": func(d *ring.Desc) { d.RemoveIngester(collider) }, + } { + t.Run(name, func(t *testing.T) { + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + require.Contains(t, desc.Ingesters[me].Tokens, token) + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh(tenants) + before := refresher.tenants[tenant].share + + shared := cloneOwnershipTestDesc(desc) + instance := shared.Ingesters[collider] + instance.Tokens = append(slices.Clone(instance.Tokens), token) + slices.Sort(instance.Tokens) + shared.Ingesters[collider] = instance + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) + refresher.refresh(tenants) + require.True(t, r.HasDuplicateTokens()) + require.NotEqual(t, before, refresher.tenants[tenant].share, "the layout must make sharing move the share") + + after := cloneOwnershipTestDesc(desc) + end(after) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(after)) + require.False(t, r.HasDuplicateTokens()) + refresher.refresh(tenants) + + assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), withoutGeneration(refresher.tenants)) + }) + } +} + +// Whole-ring tenants read the live ring, which a heartbeat can change during a +// refresh. If the ring changes after the whole-ring fingerprint is taken and is +// back as it was by the next refresh, the fingerprint matches again, so the +// share stored with it must not come from the changed ring. +func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) { + const ( + first = "whole-1" + second = "whole-2" + ) + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + limits := &hookedTenantLimits{} + limits.limits = map[string]*validation.Limits{} + overrides := validation.NewOverrides(validation.Limits{}, limits) + tenants := []string{first, second} + + // A neighbour whose READONLY flip moves the whole-ring share. + baseline := freshOwnershipShares(t, desc, me, overrides, tenants)[first].share + readOnly := cloneOwnershipTestDesc(desc) + for i := 1; i < layout.perZone; i++ { + candidate := cloneOwnershipTestDesc(desc) + setOwnershipTestState(ownershipTestInstanceID(0, i), ring.READONLY)(candidate) + if freshOwnershipShares(t, candidate, me, overrides, tenants)[first].share != baseline { + readOnly = candidate + break + } + } + require.NotEqual(t, baseline, freshOwnershipShares(t, readOnly, me, overrides, tenants)[first].share) + + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + + // The neighbour becomes READONLY after the first whole-ring tenant, and + // is back to ACTIVE before the next refresh. + limits.arm(second, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(readOnly)) }) + refresher.refresh(tenants) + back := cloneOwnershipTestDesc(desc) + for id, instance := range back.Ingesters { + instance.Timestamp += 5 + back.Ingesters[id] = instance + } + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(back)) + refresher.refresh(tenants) + + assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), withoutGeneration(refresher.tenants)) +} + +// Randomized: each step a new ring bumps the generation, so the next refresh +// checks every tenant; during that refresh, at a random tenant, a second change +// lands, and it is undone before the following refresh. Tenants are refreshed +// in a random order. The shares must then equal those computed from scratch. +func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { + const steps = 300 + me := ownershipTestInstanceID(0, 0) + rnd := rand.New(rand.NewSource(ownershipTestSeed)) + layout := ownershipTestRingLayout{zones: 3, perZone: 5, tokensPerInstance: 8} + limits := &hookedTenantLimits{} + limits.limits = map[string]*validation.Limits{} + var tenants []string + for i, size := range []int{0, 0, 3, 6, 9, 14, 15, 16, 30} { + tenant := fmt.Sprintf("tenant-%d", i) + tenants = append(tenants, tenant) + limits.limits[tenant] = &validation.Limits{IngestionTenantShardSize: size} + } + overrides := validation.NewOverrides(validation.Limits{}, limits) + states := []ring.InstanceState{ring.ACTIVE, ring.JOINING, ring.LEAVING, ring.PENDING, ring.READONLY} + + d, r := newOwnershipTestDelegate(t, me, layout.zones) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + timestamp := int64(0) + heartbeat := func(desc *ring.Desc) { + timestamp++ + next := cloneOwnershipTestDesc(desc) + for id, instance := range next.Ingesters { + instance.Timestamp = timestamp + next.Ingesters[id] = instance + } + d.OnRingInstanceHeartbeat(nil, next) + } + + for step := range steps { + desc := newOwnershipTestDesc(rand.New(rand.NewSource(int64(step))), layout) + changed := cloneOwnershipTestDesc(desc) + ids := slices.Sorted(maps.Keys(changed.Ingesters)) + id := ids[rnd.Intn(len(ids))] + instance := changed.Ingesters[id] + switch rnd.Intn(4) { + case 0: + if id != me { + changed.RemoveIngester(id) + } + case 1: + changed.AddIngester("joined", "joined-addr", fmt.Sprintf("zone-%d", rnd.Intn(layout.zones)), []uint32{rnd.Uint32(), rnd.Uint32()}, ring.ACTIVE, time.Time{}) + case 2: + instance.Tokens = append(slices.Clone(instance.Tokens), rnd.Uint32()) + slices.Sort(instance.Tokens) + changed.Ingesters[id] = instance + case 3: + instance.State = states[rnd.Intn(len(states))] + changed.Ingesters[id] = instance + } + + heartbeat(desc) + rnd.Shuffle(len(tenants), func(i, j int) { tenants[i], tenants[j] = tenants[j], tenants[i] }) + limits.arm(tenants[rnd.Intn(len(tenants))], func() { heartbeat(changed) }) + refresher.refresh(tenants) + heartbeat(desc) + refresher.refresh(tenants) + + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), withoutGeneration(refresher.tenants), "step %d", step) + } +} From 294ea0d30255c11be9607fa0a0d5cdc26cee9c00 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 20:58:28 +0000 Subject: [PATCH 04/18] ingester: simplify the ownership refresher No change in behaviour. The refresher keeps the ring generation once rather than per tenant, since every refresh visits every tenant, and the loop now reads as three cases: nothing changed, the tenant's subring is as before, or the share is computed. Computing the whole ring's fingerprint and share once per refresh moves into wholeRingMemo, and publishing the shares into publish. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 140 +++++++++++++++++++++------------ pkg/ingester/ownership_test.go | 31 ++++---- 2 files changed, 105 insertions(+), 66 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 8507d8e2c2..83cc5e54fe 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -120,16 +120,16 @@ type ownershipRefresher struct { shareGauge *prometheus.GaugeVec computations prometheus.Counter - // generation returns a value that changes whenever the ring may give this - // ingester a different share. Nil recomputes every share on each refresh. + // generation returns a value that changes whenever the ring changes in a + // way that can move a shuffle-shard pick or a share. generation func() uint64 - // The last share computed per tenant. Only touched by refresh. - tenants map[string]tenantShare + // Only touched by refresh. + lastGeneration uint64 + tenants map[string]tenantShare } type tenantShare struct { - generation uint64 shardSize int fingerprint uint64 share float64 @@ -139,7 +139,13 @@ type tenantShare struct { unsure bool } +// newOwnershipRefresher returns a refresher reading generation to tell whether +// the ring changed. A nil generation makes every refresh check every tenant. func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer, generation func() uint64) *ownershipRefresher { + if generation == nil { + var n uint64 + generation = func() uint64 { n++; return n } + } return &ownershipRefresher{ ring: r, instanceID: instanceID, @@ -152,7 +158,7 @@ func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabl }, []string{"user"}), computations: promauto.With(registerer).NewCounter(prometheus.CounterOpts{ Name: "cortex_ingester_ring_ownership_computations_total", - Help: "Number of times a tenant's ring ownership share was computed.", + Help: "Number of times a ring ownership share was computed.", }), generation: generation, } @@ -160,66 +166,51 @@ func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabl func (o *ownershipRefresher) refresh(userIDs []string) { if o.ring.InstancesCount() == 0 { - // No heartbeat has fed the ring yet. - return - } - // Read before computing, so a ring change during the refresh makes the next - // one recompute. - var generation uint64 - if o.generation != nil { - generation = o.generation() + return // No heartbeat has fed the ring yet. } + // Read first, so a change during this refresh is seen by the next one. + generation := o.generation() + ringChanged := generation != o.lastGeneration + o.lastGeneration = generation // A token shared by two zones lets an instance outside a tenant's subring // decide this zone's ownership, which the fingerprint does not cover. duplicates := o.ring.HasDuplicateTokens() - // The whole ring is read live, so its fingerprint and share are taken - // once per refresh and kept only if the ring did not change in between. - var wholeRing *tenantShare + w := wholeRingMemo{o: o} tenants := make(map[string]tenantShare, len(userIDs)) - shares := make(map[string]float64, len(userIDs)) for _, userID := range userIDs { - size := 0 - if o.shuffleShardingEnabled { - size = o.limits.IngestionTenantShardSize(userID) + size := o.shardSize(userID) + prev, ok := o.tenants[userID] + known := ok && prev.shardSize == size + if known && !ringChanged { + tenants[userID] = prev // Nothing that can move a share changed. + continue } - t, ok := o.tenants[userID] - if o.generation == nil || !ok || t.generation != generation || t.shardSize != size { - sub := o.subring(userID, size) - if sub == ring.ReadRing(o.ring) { - if wholeRing == nil { - f := subringFingerprint(sub) - w := o.computeShare(sub) - w.fingerprint = f - w.unsure = duplicates || subringFingerprint(sub) != f - wholeRing = &w - } - if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != wholeRing.fingerprint || t.unsure || wholeRing.unsure { - t = *wholeRing - t.shardSize = size - } - } else { - fingerprint := subringFingerprint(sub) - if o.generation == nil || !ok || t.shardSize != size || t.fingerprint != fingerprint || duplicates || t.unsure { - t = o.computeShare(sub) - t.shardSize = size - t.fingerprint = fingerprint - t.unsure = duplicates - } - } - t.generation = generation + sub := o.subring(userID, size) + fingerprint := w.fingerprintOf(sub) + if known && prev.fingerprint == fingerprint && !prev.unsure && !duplicates { + tenants[userID] = prev // The tenant's subring is as before. + continue } + t := w.compute(sub, fingerprint, duplicates) + t.shardSize = size tenants[userID] = t + } + o.tenants = tenants + o.publish(tenants) +} +// publish stores the shares for the limiter and reports them. +func (o *ownershipRefresher) publish(tenants map[string]tenantShare) { + shares := make(map[string]float64, len(tenants)) + for userID, t := range tenants { // Shares describe one copy per zone. When a zone is missing from the // ring, Get puts a second copy in another zone, so leave the tenant out // and let the limiter use the even split, which accounts for it. - if t.zones != o.ring.ReplicationFactor() { - continue + if t.zones == o.ring.ReplicationFactor() { + shares[userID] = t.share } - shares[userID] = t.share } - o.tenants = tenants o.ownership.shares.Store(&shares) o.shareGauge.Reset() @@ -228,6 +219,55 @@ func (o *ownershipRefresher) refresh(userIDs []string) { } } +func (o *ownershipRefresher) shardSize(userID string) int { + if !o.shuffleShardingEnabled { + return 0 + } + return o.limits.IngestionTenantShardSize(userID) +} + +// wholeRingMemo computes, at most once per refresh, the fingerprint and share +// of tenants using the whole ring. Other subrings pass straight through. +type wholeRingMemo struct { + o *ownershipRefresher + fingerprint *uint64 + share *tenantShare +} + +func (w *wholeRingMemo) isWholeRing(sub ring.ReadRing) bool { + return sub == ring.ReadRing(w.o.ring) +} + +func (w *wholeRingMemo) fingerprintOf(sub ring.ReadRing) uint64 { + if !w.isWholeRing(sub) { + return subringFingerprint(sub) + } + if w.fingerprint == nil { + f := subringFingerprint(sub) + w.fingerprint = &f + } + return *w.fingerprint +} + +// compute returns the share of sub. A subring is an immutable snapshot, but +// the whole ring is the live ring, which a heartbeat can change while it is +// read: if its fingerprint moved, the share is marked unsure. +func (w *wholeRingMemo) compute(sub ring.ReadRing, fingerprint uint64, duplicates bool) tenantShare { + if !w.isWholeRing(sub) { + t := w.o.computeShare(sub) + t.fingerprint = fingerprint + t.unsure = duplicates + return t + } + if w.share == nil { + t := w.o.computeShare(sub) + t.fingerprint = fingerprint + t.unsure = duplicates || subringFingerprint(sub) != fingerprint + w.share = &t + } + return *w.share +} + // subring returns the ring the distributor routes the tenant's writes with. func (o *ownershipRefresher) subring(userID string, shardSize int) ring.ReadRing { if shardSize <= 0 { diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index d406a483ba..66c2f93cb2 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -455,7 +455,7 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin change(desc) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher.refresh([]string{tenant}) - assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants)) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) return testutil.ToFloat64(refresher.computations) - before } @@ -466,7 +466,7 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin limits.limits[tenant] = &validation.Limits{IngestionTenantShardSize: shardSize + 3} refresher.refresh([]string{tenant}) assert.Equal(t, shardSize+3, refresher.tenants[tenant].shardSize) - assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants)) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) refresher.refresh(nil) assert.Empty(t, refresher.tenants, "a tenant gone from the ingester is dropped") @@ -553,7 +553,7 @@ func TestOwnershipRefresher_RecomputesWhenATenantSwitchesToTheWholeRing(t *testi fresh := freshOwnershipShares(t, next, me, overrides, []string{tenant}) require.NotEqual(t, before, fresh[tenant].share, "the layout must make the switch move the share") - assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) + assert.Equal(t, fresh, comparableShares(refresher.tenants)) } // Through any sequence of ring changes, the shares a refresher reuses must @@ -643,19 +643,18 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share } refresher.refresh(tenants) - require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), withoutGeneration(refresher.tenants), "step %d", step) + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } // Not a correctness condition: shows the test exercises reuse. t.Logf("the generation changed on %d of %d steps; ownership computed %v times", bumps, steps, testutil.ToFloat64(refresher.computations)) assert.Less(t, bumps, steps) } -// withoutGeneration drops what only decides when a share is recomputed, so +// comparableShares drops what only decides when a share is recomputed, so // shares can be compared with ones computed from scratch. -func withoutGeneration(tenants map[string]tenantShare) map[string]tenantShare { +func comparableShares(tenants map[string]tenantShare) map[string]tenantShare { out := make(map[string]tenantShare, len(tenants)) for id, t := range tenants { - t.generation = 0 t.unsure = false out[id] = t } @@ -707,7 +706,7 @@ func freshOwnershipShares(t *testing.T, desc *ring.Desc, me string, overrides *v r.UpdateDesc(desc) fresh := newOwnershipRefresher(r, me, true, overrides, nil, nil) fresh.refresh(tenants) - return withoutGeneration(fresh.tenants) + return comparableShares(fresh.tenants) } // collidingOwnershipTestDesc returns a ring where an instance of zone-1 holds @@ -794,7 +793,7 @@ func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { fresh := freshOwnershipShares(t, next, me, overrides, tenants) require.NotEqual(t, before, fresh[tenant].share, "the layout must make the change move the share") - assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) + assert.Equal(t, fresh, comparableShares(refresher.tenants)) }) } } @@ -855,7 +854,7 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { shrunk.RemoveIngester(ownershipTestInstanceID(1, 2)) limits.hook = func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shrunk)) } refresher.refresh([]string{tenant}) - require.Equal(t, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant}), withoutGeneration(refresher.tenants), "the share comes from the ring ShuffleShard used") + require.Equal(t, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant}), comparableShares(refresher.tenants), "the share comes from the ring ShuffleShard used") // An instance joins zone-2: 12 instances again. grown := cloneOwnershipTestDesc(shrunk) @@ -865,7 +864,7 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { fresh := freshOwnershipShares(t, grown, me, overrides, []string{tenant}) require.NotEqual(t, fresh[tenant].share, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant})[tenant].share, "the layout must make the two rings differ") - assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) + assert.Equal(t, fresh, comparableShares(refresher.tenants)) } // The ring leaves excluded zones out, so changes there bump the generation @@ -903,7 +902,7 @@ func TestOwnershipRefresher_ExcludedZones(t *testing.T) { fresh.UpdateDesc(cloneOwnershipTestDesc(desc)) want := newOwnershipRefresher(fresh, me, true, overrides, nil, nil) want.refresh([]string{tenant}) - assert.Equal(t, withoutGeneration(want.tenants), withoutGeneration(refresher.tenants)) + assert.Equal(t, comparableShares(want.tenants), comparableShares(refresher.tenants)) } // An instance outside a tenant's subring that takes a token of this ingester @@ -938,7 +937,7 @@ func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { fresh := freshOwnershipShares(t, desc, me, overrides, []string{tenant}) require.Equal(t, before.fingerprint, fresh[tenant].fingerprint, "the layout must keep the subring the same") require.NotEqual(t, before.share, fresh[tenant].share, "the layout must move the share") - assert.Equal(t, fresh, withoutGeneration(refresher.tenants)) + assert.Equal(t, fresh, comparableShares(refresher.tenants)) } // A share computed while a token was shared across zones depends on an @@ -985,7 +984,7 @@ func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { require.False(t, r.HasDuplicateTokens()) refresher.refresh(tenants) - assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), withoutGeneration(refresher.tenants)) + assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), comparableShares(refresher.tenants)) }) } } @@ -1036,7 +1035,7 @@ func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(back)) refresher.refresh(tenants) - assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), withoutGeneration(refresher.tenants)) + assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), comparableShares(refresher.tenants)) } // Randomized: each step a new ring bumps the generation, so the next refresh @@ -1101,6 +1100,6 @@ func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { heartbeat(desc) refresher.refresh(tenants) - require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), withoutGeneration(refresher.tenants), "step %d", step) + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } } From 573f1d6ee2c4acd778ed1efacd145b5f2cf806f6 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 21:06:55 +0000 Subject: [PATCH 05/18] ingester: hash ownership fingerprints with xxhash The delegate and the subring fingerprint hashed tokens with FNV-1a fed one 32-bit token at a time. Its low bits depend only on the tokens' low bits, so the lowest bit is just their parity, and collisions are easy to build. Hash each instance's zone (length-prefixed), READONLY flag and tokens with xxhash, which the module already uses, through one instanceHasher shared by the delegate and the fingerprint. The delegate now keeps one hash per instance. Members are still summed, so identical members do not cancel. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 90 ++++++++++++++-------------------- pkg/ingester/ownership_test.go | 51 ++++++++++++++++++- 2 files changed, 87 insertions(+), 54 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 83cc5e54fe..a3e01c7486 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -1,10 +1,12 @@ package ingester import ( + "encoding/binary" "maps" "sync" "time" + "github.com/cespare/xxhash/v2" "github.com/go-kit/log" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" @@ -31,16 +33,9 @@ type ringOwnershipDelegate struct { // zonal ownership anywhere in the ring. generation atomic.Uint64 - mtx sync.Mutex - instances map[string]instanceRecord -} - -// instanceRecord is what shuffle-shard picks and zonal ownership read of an -// instance. -type instanceRecord struct { - zone string - readOnly bool - tokens uint64 + mtx sync.Mutex + // instanceHash of every instance, as of the last bump. + instances map[string]uint64 } // OnRingInstanceHeartbeat runs inside the Lifecycler's CAS callback, with the @@ -57,16 +52,11 @@ func (d *ringOwnershipDelegate) OnRingInstanceHeartbeat(_ *ring.Lifecycler, ring // the new generation computes from the new ring. r.UpdateDesc(ringDesc) - // Shuffle-shard picks skip READONLY instances and zonal ownership leaves - // them out, so only instances, zones, tokens and READONLY matter. - // Heartbeats and other state changes do not. - instances := make(map[string]instanceRecord, len(ringDesc.Ingesters)) + // Heartbeats and state changes other than READONLY change no hash. + var h instanceHasher + instances := make(map[string]uint64, len(ringDesc.Ingesters)) for id, instance := range ringDesc.Ingesters { - instances[id] = instanceRecord{ - zone: instance.Zone, - readOnly: instance.State == ring.READONLY, - tokens: hashTokens(instance.Tokens), - } + instances[id] = h.hash(instance) } if d.instances == nil || !maps.Equal(d.instances, instances) { d.instances = instances @@ -74,14 +64,28 @@ func (d *ringOwnershipDelegate) OnRingInstanceHeartbeat(_ *ring.Lifecycler, ring } } -// hashTokens returns a 64-bit FNV-1a hash of tokens. -func hashTokens(tokens []uint32) uint64 { - h := uint64(14695981039346656037) - for _, token := range tokens { - h ^= uint64(token) - h *= 1099511628211 +// instanceHasher hashes what shuffle-shard picks and zonal ownership read of +// an instance: its zone, whether it is READONLY, and its tokens. Picks skip +// READONLY instances and zonal ownership leaves them out, so no other state +// matters. It reuses one buffer across calls. +type instanceHasher struct { + buf []byte +} + +func (h *instanceHasher) hash(instance ring.InstanceDesc) uint64 { + b := h.buf[:0] + b = binary.LittleEndian.AppendUint32(b, uint32(len(instance.Zone))) + b = append(b, instance.Zone...) + if instance.State == ring.READONLY { + b = append(b, 1) + } else { + b = append(b, 0) + } + for _, token := range instance.Tokens { + b = binary.LittleEndian.AppendUint32(b, token) } - return h + h.buf = b + return xxhash.Sum64(b) } // newOwnershipRing returns the ring the ownership shares are computed from. It @@ -294,35 +298,15 @@ func (o *ownershipRefresher) computeShare(sub ring.ReadRing) tenantShare { // instance outside the subring changes. func subringFingerprint(sub ring.ReadRing) uint64 { healthy, unhealthy, _ := sub.GetAllInstanceDescs(ring.Reporting) - var h uint64 + var ( + hasher instanceHasher + sum uint64 + ) for _, members := range [][]ring.InstanceDesc{healthy, unhealthy} { for _, member := range members { - m := hashTokens(member.Tokens) ^ hashString(member.Zone) - if member.State == ring.READONLY { - m = ^m - } - h += mix64(m) + // Summed rather than XORed, so identical members do not cancel. + sum += hasher.hash(member) } } - return h -} - -func hashString(s string) uint64 { - h := uint64(14695981039346656037) - for i := 0; i < len(s); i++ { - h ^= uint64(s[i]) - h *= 1099511628211 - } - return h -} - -// mix64 is the splitmix64 finalizer, so that summing member hashes does not -// let similar members cancel out. -func mix64(x uint64) uint64 { - x ^= x >> 30 - x *= 0xbf58476d1ce4e5b9 - x ^= x >> 27 - x *= 0x94d049bb133111eb - x ^= x >> 31 - return x + return sum } diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 66c2f93cb2..164c793367 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -695,7 +695,8 @@ func TestRingOwnershipDelegate_UpdatesTheRingUnderTheLock(t *testing.T) { <-done assert.True(t, neighbourIsReadOnly()) - assert.True(t, d.instances[neighbour].readOnly) + var h instanceHasher + assert.Equal(t, h.hash(readOnly.Ingesters[neighbour]), d.instances[neighbour]) } // freshOwnershipShares computes the shares from scratch on a new ring, so a bug @@ -1103,3 +1104,51 @@ func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } } + +func TestInstanceHasher(t *testing.T) { + instance := func(zone string, state ring.InstanceState, tokens ...uint32) ring.InstanceDesc { + return ring.InstanceDesc{Zone: zone, State: state, Tokens: tokens} + } + var h instanceHasher + base := h.hash(instance("zone-a", ring.ACTIVE, 1, 2, 3)) + + assert.Equal(t, base, h.hash(instance("zone-a", ring.ACTIVE, 1, 2, 3)), "the buffer is reused between calls") + for name, other := range map[string]ring.InstanceDesc{ + "zone": instance("zone-b", ring.ACTIVE, 1, 2, 3), + "READONLY": instance("zone-a", ring.READONLY, 1, 2, 3), + "tokens": instance("zone-a", ring.ACTIVE, 1, 2, 4), + "no token": instance("zone-a", ring.ACTIVE, 1, 2), + } { + assert.NotEqual(t, base, h.hash(other), name) + } + assert.Equal(t, base, h.hash(instance("zone-a", ring.LEAVING, 1, 2, 3)), "states other than READONLY do not count") + // The zone's length is hashed, so a zone cannot run into the tokens: without + // it, both of these would hash "a", then five zero bytes. + assert.NotEqual(t, h.hash(instance("a", ring.ACTIVE, 0)), h.hash(instance("a\x00\x00\x00\x00", ring.ACTIVE))) +} + +// Two identical tokenless instances join a fourth zone, so the whole ring has +// four zones and the share must be left out. A fingerprint that lets identical +// members cancel, as XOR would, misses it. +func TestOwnershipRefresher_IdenticalMembersDoNotCancel(t *testing.T) { + const tenant = "whole" + me := ownershipTestInstanceID(0, 0) + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16}) + overrides := validation.NewOverrides(validation.Limits{}, nil) + d, r := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh([]string{tenant}) + _, ok := refresher.ownership.share(tenant) + require.True(t, ok) + + next := cloneOwnershipTestDesc(desc) + for _, id := range []string{"zone-3-a", "zone-3-b"} { + next.AddIngester(id, id+"-addr", "zone-3", nil, ring.PENDING, time.Time{}) + } + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) + refresher.refresh([]string{tenant}) + + _, ok = refresher.ownership.share(tenant) + assert.False(t, ok, "four zones: the share must not be used") +} From 90bef5573623d7ed69669b552a7ae604b4a01e4e Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Mon, 23 Nov 2026 21:15:41 +0000 Subject: [PATCH 06/18] ingester: refresh ownership shares in their own service The refresh ran on updateLoop, the loop that also ticks the ingestion rate every second. After a ring change at large shard sizes a refresh takes seconds, and EwmaRate.Tick divides what it counted by one interval, so the next tick inflated the rate and could trip -ingester.instance-limits.max-ingestion-rate. Run it in a timer service of its own, started with the ingester's other subservices. On shutdown a refresh stops between tenants and leaves the shares as they were. Signed-off-by: Alan Protasio --- pkg/ingester/ingester.go | 18 +++++++-------- pkg/ingester/ownership.go | 13 ++++++++++- pkg/ingester/ownership_test.go | 40 ++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index 199a81f141..029927e05a 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -1040,6 +1040,15 @@ func (i *Ingester) starting(ctx context.Context) error { compactionService := services.NewBasicService(nil, i.compactionLoop, nil) servs = append(servs, compactionService) + if i.ownershipRefresher != nil { + // Its own service: after a ring change a refresh can take seconds, which + // must not delay updateLoop and the ingestion rate it ticks. + servs = append(servs, services.NewTimerService(ownershipRefreshPeriod, nil, func(ctx context.Context) error { + i.ownershipRefresher.refreshContext(ctx, i.getTSDBUsers()) + return nil + }, nil)) + } + if i.cfg.BlocksStorageConfig.TSDB.IsBlocksShippingEnabled() { shippingService := services.NewBasicService(nil, i.shipBlocksLoop, nil) servs = append(servs, shippingService) @@ -1142,13 +1151,6 @@ func (i *Ingester) updateLoop(ctx context.Context) error { labelSetMetricsTicker := time.NewTicker(labelSetMetricsTickInterval) defer labelSetMetricsTicker.Stop() - var ownershipTickerChan <-chan time.Time - if i.ownershipRefresher != nil { - t := time.NewTicker(ownershipRefreshPeriod) - ownershipTickerChan = t.C - defer t.Stop() - } - for { select { case <-metadataPurgeTicker.C: @@ -1176,8 +1178,6 @@ func (i *Ingester) updateLoop(ctx context.Context) error { i.updateUserTSDBConfigs() case <-labelSetMetricsTicker.C: i.updateLabelSetMetrics() - case <-ownershipTickerChan: - i.ownershipRefresher.refresh(i.getTSDBUsers()) case <-ctx.Done(): return nil case err := <-i.subservicesWatcher.Chan(): diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index a3e01c7486..da1d786a7c 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -1,6 +1,7 @@ package ingester import ( + "context" "encoding/binary" "maps" "sync" @@ -20,7 +21,7 @@ import ( var errRingOwnershipRequiresZoneAwareness = errors.New("-ingester.use-ring-ownership-for-limits requires zone-aware replication to be enabled") -// ownershipRefreshPeriod is how often tenant shares are recomputed. The +// ownershipRefreshPeriod is how often tenant shares are refreshed. The // desc-fed ring itself only changes on this ingester's heartbeats. const ownershipRefreshPeriod = 10 * time.Second @@ -169,6 +170,12 @@ func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabl } func (o *ownershipRefresher) refresh(userIDs []string) { + o.refreshContext(context.Background(), userIDs) +} + +// refreshContext refreshes the shares of userIDs. If ctx is done before every +// tenant is refreshed, it returns without changing anything. +func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []string) { if o.ring.InstancesCount() == 0 { return // No heartbeat has fed the ring yet. } @@ -183,6 +190,10 @@ func (o *ownershipRefresher) refresh(userIDs []string) { w := wholeRingMemo{o: o} tenants := make(map[string]tenantShare, len(userIDs)) for _, userID := range userIDs { + if ctx.Err() != nil { + o.lastGeneration = 0 // Check every tenant next time. + return + } size := o.shardSize(userID) prev, ok := o.tenants[userID] known := ok && prev.shardSize == size diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 164c793367..cd6979612b 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -1,6 +1,7 @@ package ingester import ( + "context" "fmt" "maps" "math" @@ -1152,3 +1153,42 @@ func TestOwnershipRefresher_IdenticalMembersDoNotCancel(t *testing.T) { _, ok = refresher.ownership.share(tenant) assert.False(t, ok, "four zones: the share must not be used") } + +// A refresh stopped part-way, as on shutdown, leaves the shares as they were, +// and the next refresh checks every tenant. +func TestOwnershipRefresher_StoppedRefreshChangesNothing(t *testing.T) { + const tenant = "whole" + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + tenants := []string{tenant} + overrides := validation.NewOverrides(validation.Limits{}, nil) + + // A neighbour whose READONLY flip moves the whole-ring share. + baseline := freshOwnershipShares(t, desc, me, overrides, tenants)[tenant].share + changed := cloneOwnershipTestDesc(desc) + for i := 1; i < layout.perZone; i++ { + candidate := cloneOwnershipTestDesc(desc) + setOwnershipTestState(ownershipTestInstanceID(0, i), ring.READONLY)(candidate) + if freshOwnershipShares(t, candidate, me, overrides, tenants)[tenant].share != baseline { + changed = candidate + break + } + } + require.NotEqual(t, baseline, freshOwnershipShares(t, changed, me, overrides, tenants)[tenant].share) + + d, r := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher.refresh(tenants) + before := maps.Clone(refresher.tenants) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(changed)) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + refresher.refreshContext(ctx, tenants) + assert.Equal(t, before, refresher.tenants) + + refresher.refresh(tenants) + assert.Equal(t, freshOwnershipShares(t, changed, me, overrides, tenants), comparableShares(refresher.tenants)) +} From b7aa09b4997bb714a7cb4a409d26ff34570813c0 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 00:43:21 +0000 Subject: [PATCH 07/18] ring: count a token shared across zones where Get routes it A token maps to one instance ring-wide. When instances in two zones share it, Get routes the token to the instance the token map holds, and the other zone's keys before it go to that zone's next token. ZonalOwnership credited that other zone's range to the instance in the wrong zone, so that zone's shares summed to less than 1 and its next instance was given too small a share. Count a zone's token only if the token map holds it for an instance in that zone. On a shuffle shard nothing changes: a token held by an instance outside the shard was already skipped. Signed-off-by: Alan Protasio --- CHANGELOG.md | 2 +- pkg/ingester/ownership_test.go | 4 ++-- pkg/ring/ring_zonal_ownership.go | 8 ++++++-- pkg/ring/ring_zonal_ownership_test.go | 20 ++++++++++++++++++++ 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ed5e82676..4fad64dac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`. With zone-aware replication, global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share. Requires zone-aware replication; while the number of zones in the ring differs from the replication factor, the equal-share conversion is used. On an unevenly balanced ring the equal-share assumption throttles tenants on the ingesters with the largest share well before they reach their global limit. The ring is read from the ingester's own heartbeats, so no KV store traffic is added. The share in use is exposed as `cortex_ingester_ring_ownership_share{user}`. #7954 -* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cost anything. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while tokens are shared across zones, every tenant is. Shares now count every instance's tokens except READONLY instances'; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. #7961 +* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cost anything. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while tokens are shared across zones, every tenant is. Shares now count every instance's tokens except READONLY instances', and a token shared across zones only in the zone `Get` sends its keys to; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index cd6979612b..270abf6d9d 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -756,9 +756,9 @@ func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { prepare func(*ring.Desc) change func(*ring.Desc) }{ - "the instance holding it in another zone becomes READONLY": { + "the instance holding it in another zone leaves": { sharedFromStart: true, - change: setOwnershipTestState(collider, ring.READONLY), + change: func(d *ring.Desc) { d.RemoveIngester(collider) }, }, "an instance joins another zone with it": { change: func(d *ring.Desc) { diff --git a/pkg/ring/ring_zonal_ownership.go b/pkg/ring/ring_zonal_ownership.go index 36c4f64300..d8b0d68b16 100644 --- a/pkg/ring/ring_zonal_ownership.go +++ b/pkg/ring/ring_zonal_ownership.go @@ -40,6 +40,8 @@ func (r *Ring) HasDuplicateTokens() bool { // Every instance owns the ranges of its tokens, except READONLY instances: // writes skip them, and their ranges fall to the next instance in the same // zone, which is the instance Get extends to. READONLY instances report 0. +// A token shared across zones counts only in the zone of the instance the +// ring's token map holds for it, which is where Get sends its keys. // This is where writes go with -distributor.extend-writes=false. With it on, // writes also skip JOINING, LEAVING and PENDING instances, which this does not // model. @@ -80,11 +82,13 @@ func (r *Ring) computeZonalOwnership() map[string]float64 { ownership[id] = 0 } - for _, zoneTokens := range r.ringTokensByZone { + for zone, zoneTokens := range r.ringTokensByZone { // Tokens are sorted, so the remaining tokens stay sorted. remaining := make([]uint32, 0, len(zoneTokens)) for _, token := range zoneTokens { - if r.ownsToken(token) { + // Get routes a token shared across zones to the instance the token + // map holds; another zone's copy leaves its range to the next token. + if r.ownsToken(token) && r.ringInstanceByToken[token].Zone == zone { remaining = append(remaining, token) } } diff --git a/pkg/ring/ring_zonal_ownership_test.go b/pkg/ring/ring_zonal_ownership_test.go index 5b6da351ab..746dddabca 100644 --- a/pkg/ring/ring_zonal_ownership_test.go +++ b/pkg/ring/ring_zonal_ownership_test.go @@ -146,6 +146,26 @@ func TestRing_ZonalOwnership_DuplicateTokenOwnsNoExtraRange(t *testing.T) { assert.InDelta(t, 0.5, got["a2"], ownershipTolerance) } +// A token shared across zones maps to one instance ring-wide. Get skips it in +// the other zone, whose range then falls to that zone's next token. +func TestRing_ZonalOwnership_TokenSharedAcrossZones(t *testing.T) { + q := uint32(quarterOfRing) + // b1 sorts after a2, so the ring-wide token map gives 2q to b1. + desc := newOwnershipTestDesc([]ownershipTestInstance{ + {id: "a1", zone: "a", tokens: []uint32{q}, state: ACTIVE}, + {id: "a2", zone: "a", tokens: []uint32{2 * q}, state: ACTIVE}, + {id: "a3", zone: "a", tokens: []uint32{3 * q}, state: ACTIVE}, + {id: "b1", zone: "b", tokens: []uint32{2 * q}, state: ACTIVE}, + {id: "b2", zone: "b", tokens: []uint32{0}, state: ACTIVE}, + }) + got := newOwnershipTestRing(t, 2, desc).ZonalOwnership() + + expected := map[string]float64{"a1": 0.5, "a2": 0, "a3": 0.5, "b1": 0.5, "b2": 0.5} + for id, share := range expected { + assert.InDelta(t, share, got[id], ownershipTolerance, id) + } +} + // randomOwnershipInstances builds a ring with random unique tokens. stateOf // gives the state of instance i in zone z; nil means every instance is ACTIVE. func randomOwnershipInstances(rnd *rand.Rand, zones, perZone, tokensPerInstance int, stateOf func(z, i int) InstanceState) []ownershipTestInstance { From 86a4e5a1341a4bf358e341623c8db41d327fd165 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 01:41:30 +0000 Subject: [PATCH 08/18] ingester: compute ownership shares from a ring no heartbeat changes The refresher read the ring the delegate updated on every heartbeat, so a heartbeat could change it in the middle of a refresh. HasDuplicateTokens was read once, at the start of a refresh: a heartbeat could share a token after that read and before a tenant's subring was built, and another could unshare it before the next refresh. The share, computed from the ring with the token shared, was reused by the next refresh, because the instance sharing the token was outside the subring and the fingerprint had not changed. It stayed wrong until the tenant's subring changed. Have the delegate keep a copy of the desc at each change that can move a share, with a count of the changes, and have the refresher build a ring from that copy whenever the count moved. A refresh reads one ring that nothing else updates, so the whole-ring fingerprint no longer needs to be read again after its share is computed. A heartbeat without such a change now only hashes the instances: at 3,000 instances with 128 tokens each, 0.9 ms instead of 3 ms, and 1.6 ms instead of 213 ms when an instance joins or leaves, since the delegate no longer rebuilds a ring inside the Lifecycler's heartbeat callback. The refresher builds the ring instead, in about 0.2 s, once per refresh after a change. Signed-off-by: Alan Protasio --- pkg/ingester/ingester.go | 11 +- pkg/ingester/ownership.go | 133 +++++++------ pkg/ingester/ownership_test.go | 331 ++++++++++++++++++++------------- 3 files changed, 285 insertions(+), 190 deletions(-) diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index 029927e05a..5159f6b08e 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -897,7 +897,7 @@ func New(cfg Config, limits *validation.Overrides, registerer prometheus.Registe }, i.getOldestUnshippedBlockMetric) } - ownershipDelegate := &ringOwnershipDelegate{} + ownershipDelegate := &ringOwnershipDelegate{enabled: cfg.UseRingOwnershipForLimits} i.lifecycler, err = ring.NewLifecyclerWithDelegate(cfg.LifecyclerConfig, i, "ingester", RingKey, false, cfg.BlocksStorageConfig.TSDB.FlushBlocksOnShutdown, logger, prometheus.WrapRegistererWithPrefix("cortex_", registerer), ownershipDelegate) if err != nil { return nil, err @@ -917,12 +917,13 @@ func New(cfg Config, limits *validation.Overrides, registerer prometheus.Registe ) if cfg.UseRingOwnershipForLimits { - ownershipRing, err := newOwnershipRing(cfg.LifecyclerConfig.RingConfig, i.lifecycler.KVStore, logger) - if err != nil { + newRing := func() (*ring.Ring, error) { + return newOwnershipRing(cfg.LifecyclerConfig.RingConfig, i.lifecycler.KVStore, logger) + } + if _, err := newRing(); err != nil { return nil, errors.Wrap(err, "failed to create the ring for ownership-based limits") } - ownershipDelegate.ring.Store(ownershipRing) - i.ownershipRefresher = newOwnershipRefresher(ownershipRing, i.lifecycler.ID, i.limiter.shuffleShardingEnabled, limits, registerer, ownershipDelegate.generation.Load) + i.ownershipRefresher = newOwnershipRefresher(ownershipDelegate.latest, newRing, i.lifecycler.ID, i.limiter.shuffleShardingEnabled, limits, registerer) i.limiter.ownership = i.ownershipRefresher.ownership } diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index da1d786a7c..d7171ebecc 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -4,6 +4,7 @@ import ( "context" "encoding/binary" "maps" + "slices" "sync" "time" @@ -21,48 +22,63 @@ import ( var errRingOwnershipRequiresZoneAwareness = errors.New("-ingester.use-ring-ownership-for-limits requires zone-aware replication to be enabled") -// ownershipRefreshPeriod is how often tenant shares are refreshed. The -// desc-fed ring itself only changes on this ingester's heartbeats. +// ownershipRefreshPeriod is how often tenant shares are refreshed. The ring +// they are computed from only changes on this ingester's heartbeats. const ownershipRefreshPeriod = 10 * time.Second -// ringOwnershipDelegate feeds a desc-fed ring with the ring the Lifecycler -// reads on every heartbeat, so tracking ownership adds no KV store traffic. +// ringOwnershipDelegate keeps the ring the Lifecycler reads on every +// heartbeat, as of the last change that can move a share, so tracking +// ownership adds no KV store traffic. type ringOwnershipDelegate struct { - ring atomic.Pointer[ring.Ring] - - // Bumped after each ring update that can change a shuffle-shard pick or - // zonal ownership anywhere in the ring. - generation atomic.Uint64 + enabled bool mtx sync.Mutex - // instanceHash of every instance, as of the last bump. - instances map[string]uint64 + // As of the last change: instanceHash of every instance, a copy of the + // desc that nothing modifies, and the number of changes. + instances map[string]uint64 + desc *ring.Desc + generation uint64 } // OnRingInstanceHeartbeat runs inside the Lifecycler's CAS callback, with the -// ring about to be written to the KV store. UpdateDesc copies it. +// ring about to be written to the KV store. func (d *ringOwnershipDelegate) OnRingInstanceHeartbeat(_ *ring.Lifecycler, ringDesc *ring.Desc) { - r := d.ring.Load() - if r == nil { + if !d.enabled { return } - // Callbacks can overlap, so the ring and the record are updated together. - d.mtx.Lock() - defer d.mtx.Unlock() - // Update the ring before bumping the generation, so a refresh that reads - // the new generation computes from the new ring. - r.UpdateDesc(ringDesc) - // Heartbeats and state changes other than READONLY change no hash. var h instanceHasher instances := make(map[string]uint64, len(ringDesc.Ingesters)) for id, instance := range ringDesc.Ingesters { instances[id] = h.hash(instance) } - if d.instances == nil || !maps.Equal(d.instances, instances) { - d.instances = instances - d.generation.Inc() + // Callbacks can overlap. + d.mtx.Lock() + defer d.mtx.Unlock() + if d.desc != nil && maps.Equal(d.instances, instances) { + return + } + d.instances = instances + d.desc = copyDesc(ringDesc) + d.generation++ +} + +// latest returns the desc as of the last change, and the number of changes. +func (d *ringOwnershipDelegate) latest() (*ring.Desc, uint64) { + d.mtx.Lock() + defer d.mtx.Unlock() + return d.desc, d.generation +} + +// copyDesc copies desc so that what the KV store does with it after the +// callback, such as merging it into its own state, cannot reach the copy. +func copyDesc(desc *ring.Desc) *ring.Desc { + out := &ring.Desc{Ingesters: maps.Clone(desc.Ingesters)} + for id, instance := range out.Ingesters { + instance.Tokens = slices.Clone(instance.Tokens) + out.Ingesters[id] = instance } + return out } // instanceHasher hashes what shuffle-shard picks and zonal ownership read of @@ -89,9 +105,8 @@ func (h *instanceHasher) hash(instance ring.InstanceDesc) uint64 { return xxhash.Sum64(b) } -// newOwnershipRing returns the ring the ownership shares are computed from. It -// is fed by ringOwnershipDelegate and only a share per tenant is kept, so -// subrings are not cached. +// newOwnershipRing returns a ring to compute ownership shares from. Only a +// share per tenant is kept, so subrings are not cached. func newOwnershipRing(cfg ring.Config, kvClient kv.Client, logger log.Logger) (*ring.Ring, error) { cfg.SubringCacheDisabled = true return ring.NewDescFedRing(cfg, "ingester-ownership", RingKey, kvClient, logger) @@ -115,9 +130,11 @@ func (t *tenantOwnership) share(userID string) (float64, bool) { return s, ok && s > 0 } -// ownershipRefresher computes tenantOwnership from the desc-fed ring. +// ownershipRefresher computes tenantOwnership from the ring as of the +// delegate's last change. type ownershipRefresher struct { - ring *ring.Ring + latest func() (*ring.Desc, uint64) + newRing func() (*ring.Ring, error) instanceID string shuffleShardingEnabled bool limits *validation.Overrides @@ -125,11 +142,9 @@ type ownershipRefresher struct { shareGauge *prometheus.GaugeVec computations prometheus.Counter - // generation returns a value that changes whenever the ring changes in a - // way that can move a shuffle-shard pick or a share. - generation func() uint64 - - // Only touched by refresh. + // Only touched by refresh. ring is the last one built, and is never + // updated, so nothing changes while a refresh reads it. + ring *ring.Ring lastGeneration uint64 tenants map[string]tenantShare } @@ -139,20 +154,16 @@ type tenantShare struct { fingerprint uint64 share float64 zones int - // Computed while tokens were shared across zones, or from a whole ring - // that changed during the computation: recompute after the next change. + // Computed while a token was shared: recompute after the next change. unsure bool } -// newOwnershipRefresher returns a refresher reading generation to tell whether -// the ring changed. A nil generation makes every refresh check every tenant. -func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer, generation func() uint64) *ownershipRefresher { - if generation == nil { - var n uint64 - generation = func() uint64 { n++; return n } - } +// newOwnershipRefresher returns a refresher that reads the ring from latest, +// and builds a ring from it with newRing whenever it changed. +func newOwnershipRefresher(latest func() (*ring.Desc, uint64), newRing func() (*ring.Ring, error), instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer) *ownershipRefresher { return &ownershipRefresher{ - ring: r, + latest: latest, + newRing: newRing, instanceID: instanceID, shuffleShardingEnabled: shuffleShardingEnabled, limits: limits, @@ -165,7 +176,6 @@ func newOwnershipRefresher(r *ring.Ring, instanceID string, shuffleShardingEnabl Name: "cortex_ingester_ring_ownership_computations_total", Help: "Number of times a ring ownership share was computed.", }), - generation: generation, } } @@ -174,24 +184,29 @@ func (o *ownershipRefresher) refresh(userIDs []string) { } // refreshContext refreshes the shares of userIDs. If ctx is done before every -// tenant is refreshed, it returns without changing anything. +// tenant is refreshed, it returns without changing the shares. func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []string) { - if o.ring.InstancesCount() == 0 { + desc, generation := o.latest() + if len(desc.GetIngesters()) == 0 { return // No heartbeat has fed the ring yet. } - // Read first, so a change during this refresh is seen by the next one. - generation := o.generation() ringChanged := generation != o.lastGeneration - o.lastGeneration = generation - // A token shared by two zones lets an instance outside a tenant's subring - // decide this zone's ownership, which the fingerprint does not cover. + if ringChanged { + r, err := o.newRing() + if err != nil { + return // Not reached: New fails on an invalid config. + } + r.UpdateDesc(desc) + o.ring = r + } + // A token shared by two instances lets one outside a tenant's subring + // decide its ownership, which the fingerprint does not cover. duplicates := o.ring.HasDuplicateTokens() w := wholeRingMemo{o: o} tenants := make(map[string]tenantShare, len(userIDs)) for _, userID := range userIDs { if ctx.Err() != nil { - o.lastGeneration = 0 // Check every tenant next time. return } size := o.shardSize(userID) @@ -207,10 +222,12 @@ func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []strin tenants[userID] = prev // The tenant's subring is as before. continue } - t := w.compute(sub, fingerprint, duplicates) + t := w.compute(sub, fingerprint) + t.unsure = duplicates t.shardSize = size tenants[userID] = t } + o.lastGeneration = generation o.tenants = tenants o.publish(tenants) } @@ -264,20 +281,16 @@ func (w *wholeRingMemo) fingerprintOf(sub ring.ReadRing) uint64 { return *w.fingerprint } -// compute returns the share of sub. A subring is an immutable snapshot, but -// the whole ring is the live ring, which a heartbeat can change while it is -// read: if its fingerprint moved, the share is marked unsure. -func (w *wholeRingMemo) compute(sub ring.ReadRing, fingerprint uint64, duplicates bool) tenantShare { +// compute returns the share of sub. +func (w *wholeRingMemo) compute(sub ring.ReadRing, fingerprint uint64) tenantShare { if !w.isWholeRing(sub) { t := w.o.computeShare(sub) t.fingerprint = fingerprint - t.unsure = duplicates return t } if w.share == nil { t := w.o.computeShare(sub) t.fingerprint = fingerprint - t.unsure = duplicates || subringFingerprint(sub) != fingerprint w.share = &t } return *w.share diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 270abf6d9d..2778530ef6 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -78,22 +79,29 @@ func newOwnershipTestRing(t *testing.T, replicationFactor int, excludedZones []s return r } -func TestRingOwnershipDelegate_FeedsACopyOfTheDesc(t *testing.T) { +func TestRingOwnershipDelegate_KeepsACopyOfTheDesc(t *testing.T) { desc := ring.NewDesc() desc.AddIngester("a-1", "a-1-addr", "a", []uint32{300, 100}, ring.ACTIVE, time.Time{}) desc.AddIngester("a-2", "a-2-addr", "a", []uint32{200}, ring.ACTIVE, time.Time{}) desc.AddIngester("b-1", "b-1-addr", "b", []uint32{400}, ring.ACTIVE, time.Time{}) - r := newOwnershipTestRing(t, 1, []string{"b"}) - delegate := &ringOwnershipDelegate{} - delegate.ring.Store(r) + d, newRing := newOwnershipTestDelegate(t, "a-1", 1, "b") + d.OnRingInstanceHeartbeat(nil, desc) + // The KV store can change the desc it writes after the callback. + desc.RemoveIngester("a-2") + slices.Sort(desc.Ingesters["a-1"].Tokens) - delegate.OnRingInstanceHeartbeat(nil, desc) + kept, _ := d.latest() + assert.Contains(t, kept.Ingesters, "a-2") + assert.Equal(t, []uint32{300, 100}, kept.Ingesters["a-1"].Tokens) - // The ring deletes excluded zones and sorts tokens in place; the desc being - // written to the KV store must be left as it was. - assert.Contains(t, desc.Ingesters, "b-1") - assert.Equal(t, []uint32{300, 100}, desc.Ingesters["a-1"].Tokens) + // The ring deletes excluded zones and sorts tokens in place, but not in the + // desc it is built from. + r, err := newRing() + require.NoError(t, err) + r.UpdateDesc(kept) + assert.Contains(t, kept.Ingesters, "b-1") + assert.Equal(t, []uint32{300, 100}, kept.Ingesters["a-1"].Tokens) ownership := r.ZonalOwnership() assert.NotContains(t, ownership, "b-1") @@ -101,9 +109,11 @@ func TestRingOwnershipDelegate_FeedsACopyOfTheDesc(t *testing.T) { assert.Positive(t, ownership["a-2"]) } -func TestRingOwnershipDelegate_NoRing(t *testing.T) { - delegate := &ringOwnershipDelegate{} - assert.NotPanics(t, func() { delegate.OnRingInstanceHeartbeat(nil, ring.NewDesc()) }) +func TestRingOwnershipDelegate_Disabled(t *testing.T) { + d := &ringOwnershipDelegate{} + d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), ownershipTestRingLayout{zones: 3, perZone: 1, tokensPerInstance: 1})) + desc, _ := d.latest() + assert.Nil(t, desc) } func TestOwnershipRefresher(t *testing.T) { @@ -115,7 +125,6 @@ func TestOwnershipRefresher(t *testing.T) { layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) - r := newOwnershipTestRing(t, layout.zones, nil) limits := validation.Limits{} tenantLimits := &staticTenantLimits{limits: map[string]*validation.Limits{ shuffledTenant: {IngestionTenantShardSize: shardSize}, @@ -123,16 +132,20 @@ func TestOwnershipRefresher(t *testing.T) { overrides := validation.NewOverrides(limits, tenantLimits) ingesterID := ownershipTestInstanceID(0, 0) - refresher := newOwnershipRefresher(r, ingesterID, true, overrides, nil, nil) + d, newRing := newOwnershipTestDelegate(t, ingesterID, layout.zones) + refresher := newOwnershipRefresher(d.latest, newRing, ingesterID, true, overrides, nil) // Nothing is known before the ring has been fed. refresher.refresh([]string{shuffledTenant, unshuffledTenant}) _, ok := refresher.ownership.share(unshuffledTenant) assert.False(t, ok) - r.UpdateDesc(desc) + d.OnRingInstanceHeartbeat(nil, desc) refresher.refresh([]string{shuffledTenant, unshuffledTenant}) + r := newOwnershipTestRing(t, layout.zones, nil) + r.UpdateDesc(desc) + share, ok := refresher.ownership.share(unshuffledTenant) require.True(t, ok) assert.InDelta(t, r.ZonalOwnership()[ingesterID], share, ownershipTestTolerance) @@ -155,10 +168,10 @@ func TestOwnershipRefresher_ZoneMissingFromRing(t *testing.T) { // RF 3 over a ring with only 2 zones: Get puts a second copy in one zone, // which zonal shares don't describe. layout := ownershipTestRingLayout{zones: 2, perZone: 4, tokensPerInstance: 16} - r := newOwnershipTestRing(t, 3, nil) - r.UpdateDesc(newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) + d, newRing := newOwnershipTestDelegate(t, ownershipTestInstanceID(0, 0), 3) + d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) - refresher := newOwnershipRefresher(r, ownershipTestInstanceID(0, 0), false, validation.NewOverrides(validation.Limits{}, nil), nil, nil) + refresher := newOwnershipRefresher(d.latest, newRing, ownershipTestInstanceID(0, 0), false, validation.NewOverrides(validation.Limits{}, nil), nil) refresher.refresh([]string{tenant}) _, ok := refresher.ownership.share(tenant) @@ -246,8 +259,11 @@ func TestLimiter_OwnershipAvoidsThrottlingOnUnevenRing(t *testing.T) { ) layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} rnd := rand.New(rand.NewSource(ownershipTestSeed)) + desc := newOwnershipTestDesc(rnd, layout) r := newOwnershipTestRing(t, layout.zones, nil) - r.UpdateDesc(newOwnershipTestDesc(rnd, layout)) + r.UpdateDesc(desc) + d, newRing := newOwnershipTestDelegate(t, "", layout.zones) + d.OnRingInstanceHeartbeat(nil, desc) // Route the tenant's series the way the distributor does. received := map[string]int{} @@ -276,7 +292,7 @@ func TestLimiter_OwnershipAvoidsThrottlingOnUnevenRing(t *testing.T) { throttledByEvenSplit++ } - refresher := newOwnershipRefresher(r, id, false, overrides, nil, nil) + refresher := newOwnershipRefresher(d.latest, newRing, id, false, overrides, nil) refresher.refresh([]string{tenant}) byOwnership := NewLimiter(overrides, ringCount, util.ShardingStrategyDefault, true, layout.zones, true, "") byOwnership.ownership = refresher.ownership @@ -299,16 +315,21 @@ func (s *staticTenantLimits) AllByUserID() map[string]*validation.Limits { return s.limits } -func newOwnershipTestDelegate(t *testing.T, _ string, replicationFactor int) (*ringOwnershipDelegate, *ring.Ring) { +// newOwnershipTestDelegate returns an enabled delegate, and a function that +// builds rings with the replication factor given, as the ingester does. +func newOwnershipTestDelegate(t *testing.T, _ string, replicationFactor int, excludedZones ...string) (*ringOwnershipDelegate, func() (*ring.Ring, error)) { t.Helper() kvClient, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) t.Cleanup(func() { _ = closer.Close() }) - r, err := newOwnershipRing(ring.Config{HeartbeatTimeout: time.Minute, ReplicationFactor: replicationFactor, ZoneAwarenessEnabled: true}, kvClient, log.NewNopLogger()) - require.NoError(t, err) + cfg := ring.Config{HeartbeatTimeout: time.Minute, ReplicationFactor: replicationFactor, ZoneAwarenessEnabled: true, ExcludedZones: excludedZones} + return &ringOwnershipDelegate{enabled: true}, func() (*ring.Ring, error) { + return newOwnershipRing(cfg, kvClient, log.NewNopLogger()) + } +} - d := &ringOwnershipDelegate{} - d.ring.Store(r) - return d, r +func generationOf(d *ringOwnershipDelegate) uint64 { + _, generation := d.latest() + return generation } // cloneOwnershipTestDesc returns a copy of desc that a test can modify. @@ -331,8 +352,10 @@ func setOwnershipTestState(id string, state ring.InstanceState) func(*ring.Desc) func TestNewOwnershipRing_DoesNotCacheSubrings(t *testing.T) { layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} - d, r := newOwnershipTestDelegate(t, ownershipTestInstanceID(0, 0), layout.zones) - d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) + _, newRing := newOwnershipTestDelegate(t, ownershipTestInstanceID(0, 0), layout.zones) + r, err := newRing() + require.NoError(t, err) + r.UpdateDesc(newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) assert.NotSame(t, r.ShuffleShard("tenant", 6), r.ShuffleShard("tenant", 6)) } @@ -401,13 +424,13 @@ func TestRingOwnershipDelegate_Generation(t *testing.T) { tc.prepare(desc) } d.OnRingInstanceHeartbeat(nil, desc) - require.Equal(t, uint64(1), d.generation.Load(), "the first ring is a change") + require.Equal(t, uint64(1), generationOf(d), "the first ring is a change") next := cloneOwnershipTestDesc(desc) tc.change(next) d.OnRingInstanceHeartbeat(nil, next) - assert.Equal(t, tc.bumped, d.generation.Load() != 1) + assert.Equal(t, tc.bumped, generationOf(d) != 1) }) } } @@ -420,18 +443,18 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin me := ownershipTestInstanceID(0, 0) layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) limits := &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}} overrides := validation.NewOverrides(validation.Limits{}, limits) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) require.Equal(t, 1.0, testutil.ToFloat64(refresher.computations)) // An instance outside the tenant's subring and one in it. members := map[string]bool{} - healthy, unhealthy, err := r.ShuffleShard(tenant, shardSize).GetAllInstanceDescs(ring.Reporting) + healthy, unhealthy, err := refresher.ring.ShuffleShard(tenant, shardSize).GetAllInstanceDescs(ring.Reporting) require.NoError(t, err) for _, member := range append(healthy, unhealthy...) { members[member.Addr] = true @@ -460,7 +483,9 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin return testutil.ToFloat64(refresher.computations) - before } + built := refresher.ring assert.Zero(t, update(setOwnershipTestState(inside, ring.LEAVING)), "not READONLY: the ring has not changed") + assert.Same(t, built, refresher.ring, "so it is not built again") assert.Zero(t, update(setOwnershipTestState(outside, ring.READONLY)), "the ring changed, the tenant's subring did not") assert.Equal(t, 1.0, update(setOwnershipTestState(inside, ring.READONLY)), "a member of the tenant's subring changed") @@ -487,9 +512,9 @@ func TestOwnershipRefresher_ReadOnlyNeighbourChangesTheShardPick(t *testing.T) { overrides := validation.NewOverrides(validation.Limits{}, limits) setOwnershipTestState(neighbour, ring.LEAVING)(desc) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, desc) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) before := refresher.tenants[tenant].share @@ -498,7 +523,7 @@ func TestOwnershipRefresher_ReadOnlyNeighbourChangesTheShardPick(t *testing.T) { d.OnRingInstanceHeartbeat(nil, next) refresher.refresh([]string{tenant}) - fresh := newOwnershipRefresher(r, me, true, overrides, nil, nil) + fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) fresh.refresh([]string{tenant}) require.NotEqual(t, before, fresh.tenants[tenant].share, "the layout must make the pick change") assert.Equal(t, fresh.tenants[tenant].share, refresher.tenants[tenant].share) @@ -541,9 +566,9 @@ func TestOwnershipRefresher_RecomputesWhenATenantSwitchesToTheWholeRing(t *testi require.NotEmpty(t, tenant) overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}}) - d, r := newOwnershipTestDelegate(t, me, 3) + d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) before := refresher.tenants[tenant].share @@ -585,8 +610,8 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share } overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: tenantLimits}) - d, r := newOwnershipTestDelegate(t, me, layout.zones) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) added, bumps := 0, 0 newToken := func(d *ring.Desc) uint32 { if sharedTokens && rnd.Intn(3) == 0 { @@ -637,9 +662,9 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share next.Ingesters[id] = instance } desc = next - before := d.generation.Load() + before := generationOf(d) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - if d.generation.Load() != before { + if generationOf(d) != before { bumps++ } refresher.refresh(tenants) @@ -663,26 +688,20 @@ func comparableShares(tenants map[string]tenantShare) map[string]tenantShare { } // Heartbeat callbacks can overlap: the Lifecycler's first heartbeat runs on its -// own goroutine. If the ring were updated outside the delegate's lock, one -// callback could update the ring after another, then compare first and find no -// change, leaving the ring and the recorded desc different for good. So a -// callback must not touch the ring while another holds the lock. -func TestRingOwnershipDelegate_UpdatesTheRingUnderTheLock(t *testing.T) { +// own goroutine. If the desc were kept outside the delegate's lock, one +// callback could keep its desc after another, then compare first and find no +// change, leaving the kept desc and the recorded hashes different for good. +func TestRingOwnershipDelegate_KeepsTheDescUnderTheLock(t *testing.T) { const wait = 50 * time.Millisecond me := ownershipTestInstanceID(0, 0) neighbour := ownershipTestInstanceID(0, 1) layout := ownershipTestRingLayout{zones: 3, perZone: 3, tokensPerInstance: 4} desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, _ := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) readOnly := cloneOwnershipTestDesc(desc) setOwnershipTestState(neighbour, ring.READONLY)(readOnly) - neighbourIsReadOnly := func() bool { - state, err := r.GetInstanceState(neighbour) - require.NoError(t, err) - return state == ring.READONLY - } d.mtx.Lock() done := make(chan struct{}) @@ -691,11 +710,12 @@ func TestRingOwnershipDelegate_UpdatesTheRingUnderTheLock(t *testing.T) { d.OnRingInstanceHeartbeat(nil, readOnly) }() time.Sleep(wait) - assert.False(t, neighbourIsReadOnly(), "the ring was updated while another callback held the lock") + assert.Equal(t, ring.ACTIVE, d.desc.Ingesters[neighbour].State, "the desc was kept while another callback held the lock") d.mtx.Unlock() <-done - assert.True(t, neighbourIsReadOnly()) + kept, _ := d.latest() + assert.Equal(t, ring.READONLY, kept.Ingesters[neighbour].State) var h instanceHasher assert.Equal(t, h.hash(readOnly.Ingesters[neighbour]), d.instances[neighbour]) } @@ -704,9 +724,9 @@ func TestRingOwnershipDelegate_UpdatesTheRingUnderTheLock(t *testing.T) { // in the reuse or in the ring's caches cannot show on both sides. func freshOwnershipShares(t *testing.T, desc *ring.Desc, me string, overrides *validation.Overrides, tenants []string) map[string]tenantShare { t.Helper() - _, r := newOwnershipTestDelegate(t, me, 3) - r.UpdateDesc(desc) - fresh := newOwnershipRefresher(r, me, true, overrides, nil, nil) + d, newRing := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, desc) + fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) fresh.refresh(tenants) return comparableShares(fresh.tenants) } @@ -782,9 +802,9 @@ func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { if tc.prepare != nil { tc.prepare(desc) } - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh(tenants) before := refresher.tenants[tenant].share @@ -801,7 +821,7 @@ func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { } // hookedTenantLimits runs hook once, the first time ByUserID is called for -// user, standing in for a heartbeat that updates the ring during a refresh. +// user, standing in for a heartbeat that lands during a refresh. type hookedTenantLimits struct { staticTenantLimits user string @@ -821,10 +841,9 @@ func (h *hookedTenantLimits) arm(user string, hook func()) { h.user, h.hook, h.once = user, hook, sync.Once{} } -// A heartbeat during a refresh can change the ring between the generation the -// refresh read and the subring it builds. The stored share must describe the -// ring it was computed from, so that the next refresh compares against the -// right one. +// A heartbeat during a refresh changes the ring after the refresh started. The +// stored share must describe the ring the refresh read, so that the next +// refresh compares against the right one. func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { const shardSize = 11 me := ownershipTestInstanceID(0, 0) @@ -845,18 +864,19 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { limits.limits = map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}} overrides := validation.NewOverrides(validation.Limits{}, limits) - d, r := newOwnershipTestDelegate(t, me, 3) + d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh(nil) // During the refresh that first sees the tenant, an instance leaves zone-1, - // so ShuffleShard sees 11 instances and returns the whole ring. + // so that ShuffleShard on the new ring sees 11 instances and returns the + // whole ring. The refresh keeps reading the ring it started with. shrunk := cloneOwnershipTestDesc(desc) shrunk.RemoveIngester(ownershipTestInstanceID(1, 2)) limits.hook = func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shrunk)) } refresher.refresh([]string{tenant}) - require.Equal(t, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant}), comparableShares(refresher.tenants), "the share comes from the ring ShuffleShard used") + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants), "the share comes from the ring the refresh started with") // An instance joins zone-2: 12 instances again. grown := cloneOwnershipTestDesc(shrunk) @@ -876,20 +896,11 @@ func TestOwnershipRefresher_ExcludedZones(t *testing.T) { me := ownershipTestInstanceID(0, 0) layout := ownershipTestRingLayout{zones: 4, perZone: 3, tokensPerInstance: 16} desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) - newRing := func() (*ringOwnershipDelegate, *ring.Ring) { - kvClient, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) - t.Cleanup(func() { _ = closer.Close() }) - r, err := newOwnershipRing(ring.Config{HeartbeatTimeout: time.Minute, ReplicationFactor: 3, ZoneAwarenessEnabled: true, ExcludedZones: []string{"zone-3"}}, kvClient, log.NewNopLogger()) - require.NoError(t, err) - d := &ringOwnershipDelegate{} - d.ring.Store(r) - return d, r - } overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) - d, r := newRing() + d, newRing := newOwnershipTestDelegate(t, me, 3, "zone-3") d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) require.Equal(t, 3, refresher.tenants[tenant].zones) computed := testutil.ToFloat64(refresher.computations) @@ -900,9 +911,9 @@ func TestOwnershipRefresher_ExcludedZones(t *testing.T) { refresher.refresh([]string{tenant}) assert.Equal(t, computed, testutil.ToFloat64(refresher.computations)) - _, fresh := newRing() - fresh.UpdateDesc(cloneOwnershipTestDesc(desc)) - want := newOwnershipRefresher(fresh, me, true, overrides, nil, nil) + fresh, freshRing := newOwnershipTestDelegate(t, me, 3, "zone-3") + fresh.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + want := newOwnershipRefresher(fresh.latest, freshRing, me, true, overrides, nil) want.refresh([]string{tenant}) assert.Equal(t, comparableShares(want.tenants), comparableShares(refresher.tenants)) } @@ -923,9 +934,9 @@ func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { require.Contains(t, desc.Ingesters[me].Tokens, token) overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) before := refresher.tenants[tenant] @@ -964,9 +975,9 @@ func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { t.Run(name, func(t *testing.T) { desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) require.Contains(t, desc.Ingesters[me].Tokens, token) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh(tenants) before := refresher.tenants[tenant].share @@ -977,24 +988,24 @@ func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { shared.Ingesters[collider] = instance d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) refresher.refresh(tenants) - require.True(t, r.HasDuplicateTokens()) + require.True(t, refresher.ring.HasDuplicateTokens()) require.NotEqual(t, before, refresher.tenants[tenant].share, "the layout must make sharing move the share") after := cloneOwnershipTestDesc(desc) end(after) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(after)) - require.False(t, r.HasDuplicateTokens()) refresher.refresh(tenants) + require.False(t, refresher.ring.HasDuplicateTokens()) assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), comparableShares(refresher.tenants)) }) } } -// Whole-ring tenants read the live ring, which a heartbeat can change during a -// refresh. If the ring changes after the whole-ring fingerprint is taken and is -// back as it was by the next refresh, the fingerprint matches again, so the -// share stored with it must not come from the changed ring. +// A heartbeat can change the ring during a refresh. If it changes after the +// whole-ring fingerprint is taken and is back as it was by the next refresh, the +// fingerprint matches again, so the share stored with it must not come from the +// changed ring. func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) { const ( first = "whole-1" @@ -1008,22 +1019,11 @@ func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) overrides := validation.NewOverrides(validation.Limits{}, limits) tenants := []string{first, second} - // A neighbour whose READONLY flip moves the whole-ring share. - baseline := freshOwnershipShares(t, desc, me, overrides, tenants)[first].share - readOnly := cloneOwnershipTestDesc(desc) - for i := 1; i < layout.perZone; i++ { - candidate := cloneOwnershipTestDesc(desc) - setOwnershipTestState(ownershipTestInstanceID(0, i), ring.READONLY)(candidate) - if freshOwnershipShares(t, candidate, me, overrides, tenants)[first].share != baseline { - readOnly = candidate - break - } - } - require.NotEqual(t, baseline, freshOwnershipShares(t, readOnly, me, overrides, tenants)[first].share) + readOnly := readOnlyNeighbour(t, desc, me, layout.perZone, overrides, first) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) // The neighbour becomes READONLY after the first whole-ring tenant, and // is back to ACTIVE before the next refresh. @@ -1060,8 +1060,8 @@ func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { overrides := validation.NewOverrides(validation.Limits{}, limits) states := []ring.InstanceState{ring.ACTIVE, ring.JOINING, ring.LEAVING, ring.PENDING, ring.READONLY} - d, r := newOwnershipTestDelegate(t, me, layout.zones) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) timestamp := int64(0) heartbeat := func(desc *ring.Desc) { timestamp++ @@ -1136,9 +1136,9 @@ func TestOwnershipRefresher_IdenticalMembersDoNotCancel(t *testing.T) { me := ownershipTestInstanceID(0, 0) desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16}) overrides := validation.NewOverrides(validation.Limits{}, nil) - d, r := newOwnershipTestDelegate(t, me, 3) + d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh([]string{tenant}) _, ok := refresher.ownership.share(tenant) require.True(t, ok) @@ -1164,22 +1164,11 @@ func TestOwnershipRefresher_StoppedRefreshChangesNothing(t *testing.T) { tenants := []string{tenant} overrides := validation.NewOverrides(validation.Limits{}, nil) - // A neighbour whose READONLY flip moves the whole-ring share. - baseline := freshOwnershipShares(t, desc, me, overrides, tenants)[tenant].share - changed := cloneOwnershipTestDesc(desc) - for i := 1; i < layout.perZone; i++ { - candidate := cloneOwnershipTestDesc(desc) - setOwnershipTestState(ownershipTestInstanceID(0, i), ring.READONLY)(candidate) - if freshOwnershipShares(t, candidate, me, overrides, tenants)[tenant].share != baseline { - changed = candidate - break - } - } - require.NotEqual(t, baseline, freshOwnershipShares(t, changed, me, overrides, tenants)[tenant].share) + changed := readOnlyNeighbour(t, desc, me, layout.perZone, overrides, tenant) - d, r := newOwnershipTestDelegate(t, me, layout.zones) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher := newOwnershipRefresher(r, me, true, overrides, nil, d.generation.Load) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) refresher.refresh(tenants) before := maps.Clone(refresher.tenants) @@ -1192,3 +1181,95 @@ func TestOwnershipRefresher_StoppedRefreshChangesNothing(t *testing.T) { refresher.refresh(tenants) assert.Equal(t, freshOwnershipShares(t, changed, me, overrides, tenants), comparableShares(refresher.tenants)) } + +// A token becomes shared during a refresh and stops being shared before the +// next one. No share may stay computed from the ring with it shared. +func TestOwnershipRefresher_TokenSharedDuringARefresh(t *testing.T) { + const ( + tenant = "tenant-1" + token = uint32(1036751706) + ) + me := ownershipTestInstanceID(0, 0) + collider := ownershipTestInstanceID(1, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 6, tokensPerInstance: 8} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + require.Contains(t, desc.Ingesters[me].Tokens, token) + // The collider, outside the tenant's shard, takes one of my tokens. + shared := cloneOwnershipTestDesc(desc) + in := shared.Ingesters[collider] + in.Tokens = append(slices.Clone(in.Tokens), token) + slices.Sort(in.Tokens) + shared.Ingesters[collider] = in + + limits := &hookedTenantLimits{} + limits.limits = map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}} + overrides := validation.NewOverrides(validation.Limits{}, limits) + require.NotEqual(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), freshOwnershipShares(t, shared, me, overrides, []string{tenant})) + + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.refresh(nil) + limits.arm(tenant, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) }) + refresher.refresh([]string{tenant}) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh([]string{tenant}) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) +} + +// readOnlyNeighbour returns desc with a zone-0 neighbour of me made READONLY, +// one whose change moves me's share of tenant. +func readOnlyNeighbour(t *testing.T, desc *ring.Desc, me string, perZone int, overrides *validation.Overrides, tenant string) *ring.Desc { + t.Helper() + baseline := freshOwnershipShares(t, desc, me, overrides, []string{tenant})[tenant].share + for i := 1; i < perZone; i++ { + changed := cloneOwnershipTestDesc(desc) + setOwnershipTestState(ownershipTestInstanceID(0, i), ring.READONLY)(changed) + if freshOwnershipShares(t, changed, me, overrides, []string{tenant})[tenant].share != baseline { + return changed + } + } + t.Fatal("no neighbour moves the share") + return nil +} + +// hookedCounter runs hook once before counting, standing in for a heartbeat +// that lands while a share is computed. +type hookedCounter struct { + prometheus.Counter + hook func() +} + +func (c *hookedCounter) Inc() { + if hook := c.hook; hook != nil { + c.hook = nil + hook() + } + c.Counter.Inc() +} + +// A heartbeat lands while the whole ring's share is computed, after its +// fingerprint was read, and is undone before the next refresh. The share and +// the fingerprint stored with it must come from the same ring. +func TestOwnershipRefresher_WholeRingChangesDuringItsComputation(t *testing.T) { + const tenant = "whole" + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + overrides := validation.NewOverrides(validation.Limits{}, nil) + changed := readOnlyNeighbour(t, desc, me, layout.perZone, overrides, tenant) + + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.computations = &hookedCounter{ + Counter: refresher.computations, + hook: func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(changed)) }, + } + refresher.refresh([]string{tenant}) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh([]string{tenant}) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) +} From 48661dd3351b1f17bd44e6f8f98b2013450dc53d Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 03:05:22 +0000 Subject: [PATCH 09/18] ingester: compare the ring with the kept copy instead of hashing it To tell whether a heartbeat changed anything a share depends on, the ownership delegate hashed every instance on each heartbeat, and kept the hashes and a count of the changes. It already keeps a copy of the desc at each change, so compare the new desc with that copy instead: the instances, and each one's zone, tokens and READONLY flag. Addresses, timestamps and other states are ignored, as before. Each change replaces the copy with a new one, so the refresher tells a change from the copy itself, and the count goes too. At 3,000 instances with 128 tokens each, a heartbeat without such a change takes 0.6 ms instead of 0.8 ms and allocates nothing instead of 111 KB; one with a change takes 0.9 to 1.2 ms instead of 1.6 ms. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 73 ++++++++++++++++++---------------- pkg/ingester/ownership_test.go | 62 ++++++++++++++--------------- 2 files changed, 68 insertions(+), 67 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index d7171ebecc..39666a9554 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -26,18 +26,15 @@ var errRingOwnershipRequiresZoneAwareness = errors.New("-ingester.use-ring-owner // they are computed from only changes on this ingester's heartbeats. const ownershipRefreshPeriod = 10 * time.Second -// ringOwnershipDelegate keeps the ring the Lifecycler reads on every +// ringOwnershipDelegate keeps a copy of the ring the Lifecycler writes on each // heartbeat, as of the last change that can move a share, so tracking // ownership adds no KV store traffic. type ringOwnershipDelegate struct { enabled bool mtx sync.Mutex - // As of the last change: instanceHash of every instance, a copy of the - // desc that nothing modifies, and the number of changes. - instances map[string]uint64 - desc *ring.Desc - generation uint64 + // Nothing modifies the copy: each change replaces it with a new one. + desc *ring.Desc } // OnRingInstanceHeartbeat runs inside the Lifecycler's CAS callback, with the @@ -46,28 +43,37 @@ func (d *ringOwnershipDelegate) OnRingInstanceHeartbeat(_ *ring.Lifecycler, ring if !d.enabled { return } - // Heartbeats and state changes other than READONLY change no hash. - var h instanceHasher - instances := make(map[string]uint64, len(ringDesc.Ingesters)) - for id, instance := range ringDesc.Ingesters { - instances[id] = h.hash(instance) - } // Callbacks can overlap. d.mtx.Lock() defer d.mtx.Unlock() - if d.desc != nil && maps.Equal(d.instances, instances) { - return + if d.desc == nil || sharesMayDiffer(d.desc, ringDesc) { + d.desc = copyDesc(ringDesc) } - d.instances = instances - d.desc = copyDesc(ringDesc) - d.generation++ } -// latest returns the desc as of the last change, and the number of changes. -func (d *ringOwnershipDelegate) latest() (*ring.Desc, uint64) { +// latest returns the copy as of the last change. Each change replaces it, so a +// different pointer means a different ring. +func (d *ringOwnershipDelegate) latest() *ring.Desc { d.mtx.Lock() defer d.mtx.Unlock() - return d.desc, d.generation + return d.desc +} + +// sharesMayDiffer reports whether a and b differ in what shuffle-shard picks +// and zonal ownership read: the instances, and each one's zone, tokens and +// whether it is READONLY. Picks skip READONLY instances and zonal ownership +// leaves them out, so no other state matters. +func sharesMayDiffer(a, b *ring.Desc) bool { + if len(a.Ingesters) != len(b.Ingesters) { + return true + } + for id, x := range a.Ingesters { + y, ok := b.Ingesters[id] + if !ok || x.Zone != y.Zone || (x.State == ring.READONLY) != (y.State == ring.READONLY) || !slices.Equal(x.Tokens, y.Tokens) { + return true + } + } + return false } // copyDesc copies desc so that what the KV store does with it after the @@ -81,10 +87,8 @@ func copyDesc(desc *ring.Desc) *ring.Desc { return out } -// instanceHasher hashes what shuffle-shard picks and zonal ownership read of -// an instance: its zone, whether it is READONLY, and its tokens. Picks skip -// READONLY instances and zonal ownership leaves them out, so no other state -// matters. It reuses one buffer across calls. +// instanceHasher hashes the fields of an instance that sharesMayDiffer +// compares. It reuses one buffer across calls. type instanceHasher struct { buf []byte } @@ -133,7 +137,7 @@ func (t *tenantOwnership) share(userID string) (float64, bool) { // ownershipRefresher computes tenantOwnership from the ring as of the // delegate's last change. type ownershipRefresher struct { - latest func() (*ring.Desc, uint64) + latest func() *ring.Desc newRing func() (*ring.Ring, error) instanceID string shuffleShardingEnabled bool @@ -143,10 +147,11 @@ type ownershipRefresher struct { computations prometheus.Counter // Only touched by refresh. ring is the last one built, and is never - // updated, so nothing changes while a refresh reads it. - ring *ring.Ring - lastGeneration uint64 - tenants map[string]tenantShare + // updated, so nothing changes while a refresh reads it. lastDesc is the + // desc the last complete refresh read. + ring *ring.Ring + lastDesc *ring.Desc + tenants map[string]tenantShare } type tenantShare struct { @@ -158,9 +163,9 @@ type tenantShare struct { unsure bool } -// newOwnershipRefresher returns a refresher that reads the ring from latest, +// newOwnershipRefresher returns a refresher that reads the desc from latest, // and builds a ring from it with newRing whenever it changed. -func newOwnershipRefresher(latest func() (*ring.Desc, uint64), newRing func() (*ring.Ring, error), instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer) *ownershipRefresher { +func newOwnershipRefresher(latest func() *ring.Desc, newRing func() (*ring.Ring, error), instanceID string, shuffleShardingEnabled bool, limits *validation.Overrides, registerer prometheus.Registerer) *ownershipRefresher { return &ownershipRefresher{ latest: latest, newRing: newRing, @@ -186,11 +191,11 @@ func (o *ownershipRefresher) refresh(userIDs []string) { // refreshContext refreshes the shares of userIDs. If ctx is done before every // tenant is refreshed, it returns without changing the shares. func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []string) { - desc, generation := o.latest() + desc := o.latest() if len(desc.GetIngesters()) == 0 { return // No heartbeat has fed the ring yet. } - ringChanged := generation != o.lastGeneration + ringChanged := desc != o.lastDesc if ringChanged { r, err := o.newRing() if err != nil { @@ -227,7 +232,7 @@ func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []strin t.shardSize = size tenants[userID] = t } - o.lastGeneration = generation + o.lastDesc = desc o.tenants = tenants o.publish(tenants) } diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 2778530ef6..4cf02b463e 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -91,7 +91,7 @@ func TestRingOwnershipDelegate_KeepsACopyOfTheDesc(t *testing.T) { desc.RemoveIngester("a-2") slices.Sort(desc.Ingesters["a-1"].Tokens) - kept, _ := d.latest() + kept := d.latest() assert.Contains(t, kept.Ingesters, "a-2") assert.Equal(t, []uint32{300, 100}, kept.Ingesters["a-1"].Tokens) @@ -112,8 +112,7 @@ func TestRingOwnershipDelegate_KeepsACopyOfTheDesc(t *testing.T) { func TestRingOwnershipDelegate_Disabled(t *testing.T) { d := &ringOwnershipDelegate{} d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), ownershipTestRingLayout{zones: 3, perZone: 1, tokensPerInstance: 1})) - desc, _ := d.latest() - assert.Nil(t, desc) + assert.Nil(t, d.latest()) } func TestOwnershipRefresher(t *testing.T) { @@ -327,11 +326,6 @@ func newOwnershipTestDelegate(t *testing.T, _ string, replicationFactor int, exc } } -func generationOf(d *ringOwnershipDelegate) uint64 { - _, generation := d.latest() - return generation -} - // cloneOwnershipTestDesc returns a copy of desc that a test can modify. func cloneOwnershipTestDesc(desc *ring.Desc) *ring.Desc { out := ring.NewDesc() @@ -360,7 +354,7 @@ func TestNewOwnershipRing_DoesNotCacheSubrings(t *testing.T) { assert.NotSame(t, r.ShuffleShard("tenant", 6), r.ShuffleShard("tenant", 6)) } -func TestRingOwnershipDelegate_Generation(t *testing.T) { +func TestRingOwnershipDelegate_KeepsADescOnEachChange(t *testing.T) { me := ownershipTestInstanceID(0, 0) neighbour := ownershipTestInstanceID(0, 1) other := ownershipTestInstanceID(1, 0) @@ -376,7 +370,7 @@ func TestRingOwnershipDelegate_Generation(t *testing.T) { tests := map[string]struct { prepare func(*ring.Desc) change func(*ring.Desc) - bumped bool + changed bool }{ "heartbeat only": {change: func(d *ring.Desc) { for id, instance := range d.Ingesters { @@ -387,16 +381,16 @@ func TestRingOwnershipDelegate_Generation(t *testing.T) { "a state change other than READONLY in my zone": {change: setOwnershipTestState(neighbour, ring.LEAVING)}, "a state change other than READONLY in other zone": {change: setOwnershipTestState(other, ring.JOINING)}, "my own state change": {change: setOwnershipTestState(me, ring.LEAVING)}, - "an instance becomes READONLY in my zone": {change: setOwnershipTestState(neighbour, ring.READONLY), bumped: true}, - "an instance becomes READONLY in another zone": {change: setOwnershipTestState(other, ring.READONLY), bumped: true}, + "an instance becomes READONLY in my zone": {change: setOwnershipTestState(neighbour, ring.READONLY), changed: true}, + "an instance becomes READONLY in another zone": {change: setOwnershipTestState(other, ring.READONLY), changed: true}, "an instance stops being READONLY": { - prepare: setOwnershipTestState(other, ring.READONLY), change: setOwnershipTestState(other, ring.ACTIVE), bumped: true, + prepare: setOwnershipTestState(other, ring.READONLY), change: setOwnershipTestState(other, ring.ACTIVE), changed: true, }, "an instance joins": { - change: func(d *ring.Desc) { d.AddIngester("new", "new", "zone-1", []uint32{42}, ring.JOINING, time.Time{}) }, bumped: true, + change: func(d *ring.Desc) { d.AddIngester("new", "new", "zone-1", []uint32{42}, ring.JOINING, time.Time{}) }, changed: true, }, - "an instance leaves": {change: func(d *ring.Desc) { d.RemoveIngester(other) }, bumped: true}, - "tokens change": {change: changeTokens(other), bumped: true}, + "an instance leaves": {change: func(d *ring.Desc) { d.RemoveIngester(other) }, changed: true}, + "tokens change": {change: changeTokens(other), changed: true}, "a tokenless instance gets tokens": { prepare: func(d *ring.Desc) { d.AddIngester("new", "new", "zone-new", nil, ring.PENDING, time.Time{}) }, change: func(d *ring.Desc) { @@ -404,15 +398,20 @@ func TestRingOwnershipDelegate_Generation(t *testing.T) { instance.Tokens = []uint32{42} d.Ingesters["new"] = instance }, - bumped: true, + changed: true, }, + "an address change": {change: func(d *ring.Desc) { + instance := d.Ingesters[other] + instance.Addr = "moved" + d.Ingesters[other] = instance + }}, "an instance changes zone": { change: func(d *ring.Desc) { instance := d.Ingesters[other] instance.Zone = "zone-2" d.Ingesters[other] = instance }, - bumped: true, + changed: true, }, } @@ -424,13 +423,14 @@ func TestRingOwnershipDelegate_Generation(t *testing.T) { tc.prepare(desc) } d.OnRingInstanceHeartbeat(nil, desc) - require.Equal(t, uint64(1), generationOf(d), "the first ring is a change") + first := d.latest() + require.NotNil(t, first, "the first ring is a change") next := cloneOwnershipTestDesc(desc) tc.change(next) d.OnRingInstanceHeartbeat(nil, next) - assert.Equal(t, tc.bumped, generationOf(d) != 1) + assert.Equal(t, tc.changed, d.latest() != first) }) } } @@ -662,9 +662,9 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share next.Ingesters[id] = instance } desc = next - before := generationOf(d) + before := d.latest() d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - if generationOf(d) != before { + if d.latest() != before { bumps++ } refresher.refresh(tenants) @@ -672,7 +672,7 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } // Not a correctness condition: shows the test exercises reuse. - t.Logf("the generation changed on %d of %d steps; ownership computed %v times", bumps, steps, testutil.ToFloat64(refresher.computations)) + t.Logf("the ring changed on %d of %d steps; ownership computed %v times", bumps, steps, testutil.ToFloat64(refresher.computations)) assert.Less(t, bumps, steps) } @@ -688,9 +688,8 @@ func comparableShares(tenants map[string]tenantShare) map[string]tenantShare { } // Heartbeat callbacks can overlap: the Lifecycler's first heartbeat runs on its -// own goroutine. If the desc were kept outside the delegate's lock, one -// callback could keep its desc after another, then compare first and find no -// change, leaving the kept desc and the recorded hashes different for good. +// own goroutine. A callback must not compare or replace the kept desc while +// another holds the delegate's lock. func TestRingOwnershipDelegate_KeepsTheDescUnderTheLock(t *testing.T) { const wait = 50 * time.Millisecond me := ownershipTestInstanceID(0, 0) @@ -714,10 +713,7 @@ func TestRingOwnershipDelegate_KeepsTheDescUnderTheLock(t *testing.T) { d.mtx.Unlock() <-done - kept, _ := d.latest() - assert.Equal(t, ring.READONLY, kept.Ingesters[neighbour].State) - var h instanceHasher - assert.Equal(t, h.hash(readOnly.Ingesters[neighbour]), d.instances[neighbour]) + assert.Equal(t, ring.READONLY, d.latest().Ingesters[neighbour].State) } // freshOwnershipShares computes the shares from scratch on a new ring, so a bug @@ -889,8 +885,8 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { assert.Equal(t, fresh, comparableShares(refresher.tenants)) } -// The ring leaves excluded zones out, so changes there bump the generation -// but leave every tenant's subring, and so its share, as it was. +// The ring leaves excluded zones out, so changes there count as changes but +// leave every tenant's subring, and so its share, as it was. func TestOwnershipRefresher_ExcludedZones(t *testing.T) { const tenant = "tenant" me := ownershipTestInstanceID(0, 0) @@ -1040,7 +1036,7 @@ func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), comparableShares(refresher.tenants)) } -// Randomized: each step a new ring bumps the generation, so the next refresh +// Randomized: each step a new ring replaces the kept desc, so the next refresh // checks every tenant; during that refresh, at a random tenant, a second change // lands, and it is undone before the following refresh. Tenants are refreshed // in a random order. The shares must then equal those computed from scratch. From 0f13b5295aa32bfd800b26b18bbcf8c402a874db Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 03:29:23 +0000 Subject: [PATCH 10/18] ingester: drop the ownership refresh wrapper without a context Only tests called refresh(userIDs), which passed context.Background() to refreshContext. Rename refreshContext to refresh, so the refresher has one method, and have the tests pass the context. Signed-off-by: Alan Protasio --- pkg/ingester/ingester.go | 2 +- pkg/ingester/ownership.go | 10 ++-- pkg/ingester/ownership_test.go | 84 +++++++++++++++++----------------- 3 files changed, 46 insertions(+), 50 deletions(-) diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index 5159f6b08e..afdda22b49 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -1045,7 +1045,7 @@ func (i *Ingester) starting(ctx context.Context) error { // Its own service: after a ring change a refresh can take seconds, which // must not delay updateLoop and the ingestion rate it ticks. servs = append(servs, services.NewTimerService(ownershipRefreshPeriod, nil, func(ctx context.Context) error { - i.ownershipRefresher.refreshContext(ctx, i.getTSDBUsers()) + i.ownershipRefresher.refresh(ctx, i.getTSDBUsers()) return nil }, nil)) } diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 39666a9554..ce94a87fe1 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -184,13 +184,9 @@ func newOwnershipRefresher(latest func() *ring.Desc, newRing func() (*ring.Ring, } } -func (o *ownershipRefresher) refresh(userIDs []string) { - o.refreshContext(context.Background(), userIDs) -} - -// refreshContext refreshes the shares of userIDs. If ctx is done before every -// tenant is refreshed, it returns without changing the shares. -func (o *ownershipRefresher) refreshContext(ctx context.Context, userIDs []string) { +// refresh refreshes the shares of userIDs. If ctx is done before every tenant +// is refreshed, it returns without changing the shares. +func (o *ownershipRefresher) refresh(ctx context.Context, userIDs []string) { desc := o.latest() if len(desc.GetIngesters()) == 0 { return // No heartbeat has fed the ring yet. diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 4cf02b463e..856d613ffa 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -135,12 +135,12 @@ func TestOwnershipRefresher(t *testing.T) { refresher := newOwnershipRefresher(d.latest, newRing, ingesterID, true, overrides, nil) // Nothing is known before the ring has been fed. - refresher.refresh([]string{shuffledTenant, unshuffledTenant}) + refresher.refresh(context.Background(), []string{shuffledTenant, unshuffledTenant}) _, ok := refresher.ownership.share(unshuffledTenant) assert.False(t, ok) d.OnRingInstanceHeartbeat(nil, desc) - refresher.refresh([]string{shuffledTenant, unshuffledTenant}) + refresher.refresh(context.Background(), []string{shuffledTenant, unshuffledTenant}) r := newOwnershipTestRing(t, layout.zones, nil) r.UpdateDesc(desc) @@ -171,7 +171,7 @@ func TestOwnershipRefresher_ZoneMissingFromRing(t *testing.T) { d.OnRingInstanceHeartbeat(nil, newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout)) refresher := newOwnershipRefresher(d.latest, newRing, ownershipTestInstanceID(0, 0), false, validation.NewOverrides(validation.Limits{}, nil), nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) _, ok := refresher.ownership.share(tenant) assert.False(t, ok) @@ -292,7 +292,7 @@ func TestLimiter_OwnershipAvoidsThrottlingOnUnevenRing(t *testing.T) { } refresher := newOwnershipRefresher(d.latest, newRing, id, false, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) byOwnership := NewLimiter(overrides, ringCount, util.ShardingStrategyDefault, true, layout.zones, true, "") byOwnership.ownership = refresher.ownership assert.NoError(t, byOwnership.AssertMaxSeriesPerUser(tenant, series), "ingester %s with %d series", id, series) @@ -449,7 +449,7 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin limits := &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}} overrides := validation.NewOverrides(validation.Limits{}, limits) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) require.Equal(t, 1.0, testutil.ToFloat64(refresher.computations)) // An instance outside the tenant's subring and one in it. @@ -478,7 +478,7 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin before := testutil.ToFloat64(refresher.computations) change(desc) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) return testutil.ToFloat64(refresher.computations) - before } @@ -490,11 +490,11 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin assert.Equal(t, 1.0, update(setOwnershipTestState(inside, ring.READONLY)), "a member of the tenant's subring changed") limits.limits[tenant] = &validation.Limits{IngestionTenantShardSize: shardSize + 3} - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) assert.Equal(t, shardSize+3, refresher.tenants[tenant].shardSize) assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) - refresher.refresh(nil) + refresher.refresh(context.Background(), nil) assert.Empty(t, refresher.tenants, "a tenant gone from the ingester is dropped") } @@ -515,16 +515,16 @@ func TestOwnershipRefresher_ReadOnlyNeighbourChangesTheShardPick(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, desc) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) before := refresher.tenants[tenant].share next := cloneOwnershipTestDesc(desc) setOwnershipTestState(neighbour, ring.READONLY)(next) d.OnRingInstanceHeartbeat(nil, next) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - fresh.refresh([]string{tenant}) + fresh.refresh(context.Background(), []string{tenant}) require.NotEqual(t, before, fresh.tenants[tenant].share, "the layout must make the pick change") assert.Equal(t, fresh.tenants[tenant].share, refresher.tenants[tenant].share) } @@ -569,13 +569,13 @@ func TestOwnershipRefresher_RecomputesWhenATenantSwitchesToTheWholeRing(t *testi d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) before := refresher.tenants[tenant].share next := cloneOwnershipTestDesc(desc) next.RemoveIngester(ownershipTestInstanceID(1, 0)) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) fresh := freshOwnershipShares(t, next, me, overrides, []string{tenant}) require.NotEqual(t, before, fresh[tenant].share, "the layout must make the switch move the share") @@ -667,7 +667,7 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share if d.latest() != before { bumps++ } - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } @@ -723,7 +723,7 @@ func freshOwnershipShares(t *testing.T, desc *ring.Desc, me string, overrides *v d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, desc) fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - fresh.refresh(tenants) + fresh.refresh(context.Background(), tenants) return comparableShares(fresh.tenants) } @@ -801,13 +801,13 @@ func TestOwnershipRefresher_TokenSharedAcrossZones(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) before := refresher.tenants[tenant].share next := cloneOwnershipTestDesc(desc) tc.change(next) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) fresh := freshOwnershipShares(t, next, me, overrides, tenants) require.NotEqual(t, before, fresh[tenant].share, "the layout must make the change move the share") @@ -863,7 +863,7 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh(nil) + refresher.refresh(context.Background(), nil) // During the refresh that first sees the tenant, an instance leaves zone-1, // so that ShuffleShard on the new ring sees 11 instances and returns the @@ -871,14 +871,14 @@ func TestOwnershipRefresher_WholeRingFlagDescribesTheRingUsed(t *testing.T) { shrunk := cloneOwnershipTestDesc(desc) shrunk.RemoveIngester(ownershipTestInstanceID(1, 2)) limits.hook = func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shrunk)) } - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) require.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants), "the share comes from the ring the refresh started with") // An instance joins zone-2: 12 instances again. grown := cloneOwnershipTestDesc(shrunk) grown.AddIngester(ownershipTestInstanceID(2, 9), "zone-2-ingester-9-addr", "zone-2", []uint32{rnd.Uint32(), rnd.Uint32()}, ring.ACTIVE, time.Time{}) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(grown)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) fresh := freshOwnershipShares(t, grown, me, overrides, []string{tenant}) require.NotEqual(t, fresh[tenant].share, freshOwnershipShares(t, shrunk, me, overrides, []string{tenant})[tenant].share, "the layout must make the two rings differ") @@ -897,20 +897,20 @@ func TestOwnershipRefresher_ExcludedZones(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, 3, "zone-3") d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) require.Equal(t, 3, refresher.tenants[tenant].zones) computed := testutil.ToFloat64(refresher.computations) setOwnershipTestState(ownershipTestInstanceID(3, 0), ring.READONLY)(desc) desc.RemoveIngester(ownershipTestInstanceID(3, 1)) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) assert.Equal(t, computed, testutil.ToFloat64(refresher.computations)) fresh, freshRing := newOwnershipTestDelegate(t, me, 3, "zone-3") fresh.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) want := newOwnershipRefresher(fresh.latest, freshRing, me, true, overrides, nil) - want.refresh([]string{tenant}) + want.refresh(context.Background(), []string{tenant}) assert.Equal(t, comparableShares(want.tenants), comparableShares(refresher.tenants)) } @@ -933,7 +933,7 @@ func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) before := refresher.tenants[tenant] instance := desc.Ingesters[collider] @@ -941,7 +941,7 @@ func TestOwnershipRefresher_TokenSharedFromOutsideTheSubring(t *testing.T) { slices.Sort(instance.Tokens) desc.Ingesters[collider] = instance d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) fresh := freshOwnershipShares(t, desc, me, overrides, []string{tenant}) require.Equal(t, before.fingerprint, fresh[tenant].fingerprint, "the layout must keep the subring the same") @@ -974,7 +974,7 @@ func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) before := refresher.tenants[tenant].share shared := cloneOwnershipTestDesc(desc) @@ -983,14 +983,14 @@ func TestOwnershipRefresher_RecomputesWhenTokensStopBeingShared(t *testing.T) { slices.Sort(instance.Tokens) shared.Ingesters[collider] = instance d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) require.True(t, refresher.ring.HasDuplicateTokens()) require.NotEqual(t, before, refresher.tenants[tenant].share, "the layout must make sharing move the share") after := cloneOwnershipTestDesc(desc) end(after) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(after)) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) require.False(t, refresher.ring.HasDuplicateTokens()) assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), comparableShares(refresher.tenants)) @@ -1024,14 +1024,14 @@ func TestOwnershipRefresher_WholeRingChangedDuringARefreshAndBack(t *testing.T) // The neighbour becomes READONLY after the first whole-ring tenant, and // is back to ACTIVE before the next refresh. limits.arm(second, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(readOnly)) }) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) back := cloneOwnershipTestDesc(desc) for id, instance := range back.Ingesters { instance.Timestamp += 5 back.Ingesters[id] = instance } d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(back)) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), comparableShares(refresher.tenants)) } @@ -1094,9 +1094,9 @@ func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { heartbeat(desc) rnd.Shuffle(len(tenants), func(i, j int) { tenants[i], tenants[j] = tenants[j], tenants[i] }) limits.arm(tenants[rnd.Intn(len(tenants))], func() { heartbeat(changed) }) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) heartbeat(desc) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) } @@ -1135,7 +1135,7 @@ func TestOwnershipRefresher_IdenticalMembersDoNotCancel(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, 3) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) _, ok := refresher.ownership.share(tenant) require.True(t, ok) @@ -1144,7 +1144,7 @@ func TestOwnershipRefresher_IdenticalMembersDoNotCancel(t *testing.T) { next.AddIngester(id, id+"-addr", "zone-3", nil, ring.PENDING, time.Time{}) } d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) _, ok = refresher.ownership.share(tenant) assert.False(t, ok, "four zones: the share must not be used") @@ -1165,16 +1165,16 @@ func TestOwnershipRefresher_StoppedRefreshChangesNothing(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) before := maps.Clone(refresher.tenants) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(changed)) ctx, cancel := context.WithCancel(context.Background()) cancel() - refresher.refreshContext(ctx, tenants) + refresher.refresh(ctx, tenants) assert.Equal(t, before, refresher.tenants) - refresher.refresh(tenants) + refresher.refresh(context.Background(), tenants) assert.Equal(t, freshOwnershipShares(t, changed, me, overrides, tenants), comparableShares(refresher.tenants)) } @@ -1205,12 +1205,12 @@ func TestOwnershipRefresher_TokenSharedDuringARefresh(t *testing.T) { d, newRing := newOwnershipTestDelegate(t, me, layout.zones) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) - refresher.refresh(nil) + refresher.refresh(context.Background(), nil) limits.arm(tenant, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) }) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) } @@ -1263,9 +1263,9 @@ func TestOwnershipRefresher_WholeRingChangesDuringItsComputation(t *testing.T) { Counter: refresher.computations, hook: func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(changed)) }, } - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) - refresher.refresh([]string{tenant}) + refresher.refresh(context.Background(), []string{tenant}) assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) } From 209101daca2f7e9d1c1371353bb582900b079357 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 03:43:07 +0000 Subject: [PATCH 11/18] ingester: correct the ownership comments and CHANGELOG entry A shuffle shard does not skip a READONLY instance: it keeps it and picks one more instance in that zone. Say so in the comments that explain why only READONLY, among the states, can move a pick. In the CHANGELOG entry, a heartbeat still costs a comparison of the ring, so say it causes no recomputation rather than nothing; every tenant is recomputed while any token is held twice, within a zone too; and name the new cortex_ingester_ring_ownership_computations_total metric. Signed-off-by: Alan Protasio --- CHANGELOG.md | 2 +- pkg/ingester/ownership.go | 5 +++-- pkg/ingester/ownership_test.go | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fad64dac8..2372e5e46a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`. With zone-aware replication, global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share. Requires zone-aware replication; while the number of zones in the ring differs from the replication factor, the equal-share conversion is used. On an unevenly balanced ring the equal-share assumption throttles tenants on the ingesters with the largest share well before they reach their global limit. The ring is read from the ingester's own heartbeats, so no KV store traffic is added. The share in use is exposed as `cortex_ingester_ring_ownership_share{user}`. #7954 -* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cost anything. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while tokens are shared across zones, every tenant is. Shares now count every instance's tokens except READONLY instances', and a token shared across zones only in the zone `Get` sends its keys to; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. #7961 +* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cause any recomputation. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while a token is held twice, every tenant is. Shares now count every instance's tokens except READONLY instances', and a token shared across zones only in the zone `Get` sends its keys to; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. The number of shares computed is exposed as `cortex_ingester_ring_ownership_computations_total`. #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index ce94a87fe1..944b65a725 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -61,8 +61,9 @@ func (d *ringOwnershipDelegate) latest() *ring.Desc { // sharesMayDiffer reports whether a and b differ in what shuffle-shard picks // and zonal ownership read: the instances, and each one's zone, tokens and -// whether it is READONLY. Picks skip READONLY instances and zonal ownership -// leaves them out, so no other state matters. +// whether it is READONLY. A shard picks one more instance for each READONLY +// one it includes, and zonal ownership leaves READONLY instances out, so no +// other state matters. func sharesMayDiffer(a, b *ring.Desc) bool { if len(a.Ingesters) != len(b.Ingesters) { return true diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 856d613ffa..7fdc128329 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -499,8 +499,8 @@ func TestOwnershipRefresher_ComputesOwnershipOnlyWhenTheSubringChanges(t *testin } // A neighbour going from LEAVING to READONLY moves this ingester's share, -// because shard picks skip READONLY instances. On this layout the share goes -// from 0 to about 0.54. +// because a shard picks one more instance for each READONLY one it includes. +// On this layout the share goes from 0 to about 0.54. func TestOwnershipRefresher_ReadOnlyNeighbourChangesTheShardPick(t *testing.T) { // The tenant name and the seed below pick a layout where this happens. const tenant = "t" From 3f476fbcc44d01fb8d0e40d96ca801697f189116 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 03:45:42 +0000 Subject: [PATCH 12/18] CHANGELOG: shorten the ring ownership entry Signed-off-by: Alan Protasio --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2372e5e46a..4dbee812ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`. With zone-aware replication, global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share. Requires zone-aware replication; while the number of zones in the ring differs from the replication factor, the equal-share conversion is used. On an unevenly balanced ring the equal-share assumption throttles tenants on the ingesters with the largest share well before they reach their global limit. The ring is read from the ingester's own heartbeats, so no KV store traffic is added. The share in use is exposed as `cortex_ingester_ring_ownership_share{user}`. #7954 -* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of caching a shuffle-shard subring per tenant, and compute it again only when the tenant's subring changed. Heartbeats and state changes other than READONLY no longer cause any recomputation. After an instance joins, leaves, changes zone or tokens, or becomes or stops being READONLY, each tenant's subring is checked and only the tenants whose subring changed are recomputed; while a token is held twice, every tenant is. Shares now count every instance's tokens except READONLY instances', and a token shared across zones only in the zone `Get` sends its keys to; with `-distributor.extend-writes=true` (the default), the instances that take a JOINING, LEAVING or PENDING neighbour's writes keep a smaller share than they receive while the neighbour stays in that state. The number of shares computed is exposed as `cortex_ingester_ring_ownership_computations_total`. #7961 +* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of a cached subring per tenant, and recompute it only when the tenant's subring changes. Shares no longer follow `-distributor.extend-writes`: while an instance is JOINING, LEAVING or PENDING, the instance that takes its writes can throttle a tenant before it reaches its global limit. Adds the `cortex_ingester_ring_ownership_computations_total` metric. #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 From 1ffc17a2f3fe9339dfbab0e83b65771110ff7234 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:08:19 +0000 Subject: [PATCH 13/18] ingester: tell this ingester apart in the ownership fingerprint A subring's fingerprint sums its members' hashes, so it does not say which member is this ingester. If this ingester and a neighbour in its zone swapped their tokens, the fingerprint stayed the same and the old share was reused, although this ingester now owns the neighbour's ranges. Store this ingester's own hash with each share, or 0 when it is not in the tenant's subring, and recompute when it differs. A change of this ingester's instance then recomputes only the tenants whose subring it is in; its share elsewhere stays 0. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 19 +++++++++-- pkg/ingester/ownership_test.go | 62 ++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index 944b65a725..b7062de397 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -158,8 +158,11 @@ type ownershipRefresher struct { type tenantShare struct { shardSize int fingerprint uint64 - share float64 - zones int + // This ingester's hash if it is in the subring, else 0: the fingerprint + // does not tell which member is this ingester. + self uint64 + share float64 + zones int // Computed while a token was shared: recompute after the next change. unsure bool } @@ -204,6 +207,11 @@ func (o *ownershipRefresher) refresh(ctx context.Context, userIDs []string) { // A token shared by two instances lets one outside a tenant's subring // decide its ownership, which the fingerprint does not cover. duplicates := o.ring.HasDuplicateTokens() + var self uint64 + if instance, ok := desc.Ingesters[o.instanceID]; ok { + var h instanceHasher + self = h.hash(instance) + } w := wholeRingMemo{o: o} tenants := make(map[string]tenantShare, len(userIDs)) @@ -220,11 +228,16 @@ func (o *ownershipRefresher) refresh(ctx context.Context, userIDs []string) { } sub := o.subring(userID, size) fingerprint := w.fingerprintOf(sub) - if known && prev.fingerprint == fingerprint && !prev.unsure && !duplicates { + member := uint64(0) + if sub.HasInstance(o.instanceID) { + member = self + } + if known && prev.fingerprint == fingerprint && prev.self == member && !prev.unsure && !duplicates { tenants[userID] = prev // The tenant's subring is as before. continue } t := w.compute(sub, fingerprint) + t.self = member t.unsure = duplicates t.shardSize = size tenants[userID] = t diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 7fdc128329..7a572db719 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -1102,6 +1102,68 @@ func TestOwnershipRefresher_ChangesDuringARefreshUndone(t *testing.T) { } } +// The fingerprint sums the members' hashes, so it stays the same when this +// ingester and a neighbour in its zone swap their tokens, but this ingester's +// share does not. +func TestOwnershipRefresher_TokensSwappedWithANeighbour(t *testing.T) { + const tenant = "whole" + me := ownershipTestInstanceID(0, 0) + neighbour := ownershipTestInstanceID(0, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + overrides := validation.NewOverrides(validation.Limits{}, nil) + tenants := []string{tenant} + + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.refresh(context.Background(), tenants) + + swapped := cloneOwnershipTestDesc(desc) + a, b := swapped.Ingesters[me], swapped.Ingesters[neighbour] + a.Tokens, b.Tokens = b.Tokens, a.Tokens + swapped.Ingesters[me], swapped.Ingesters[neighbour] = a, b + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(swapped)) + refresher.refresh(context.Background(), tenants) + + fresh := freshOwnershipShares(t, swapped, me, overrides, tenants) + require.NotEqual(t, freshOwnershipShares(t, desc, me, overrides, tenants)[tenant].share, fresh[tenant].share, "the layout must make the swap move the share") + assert.Equal(t, fresh, comparableShares(refresher.tenants)) +} + +// A change of this ingester's own instance recomputes only the tenants whose +// subring it is in: elsewhere its share stays 0. +func TestOwnershipRefresher_OwnChangeOutsideTheSubring(t *testing.T) { + const shardSize = 3 + me := ownershipTestInstanceID(0, 0) + layout := ownershipTestRingLayout{zones: 3, perZone: 4, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + r, err := newRing() + require.NoError(t, err) + r.UpdateDesc(desc) + // A tenant whose shard leaves this ingester out. + tenant := "" + for i := 0; tenant == ""; i++ { + if candidate := fmt.Sprintf("tenant-%d", i); !r.ShuffleShard(candidate, shardSize).HasInstance(me) { + tenant = candidate + } + } + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: shardSize}}}) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.refresh(context.Background(), []string{tenant}) + computed := testutil.ToFloat64(refresher.computations) + + setOwnershipTestState(me, ring.READONLY)(desc) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh(context.Background(), []string{tenant}) + + assert.Equal(t, computed, testutil.ToFloat64(refresher.computations)) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) +} + func TestInstanceHasher(t *testing.T) { instance := func(zone string, state ring.InstanceState, tokens ...uint32) ring.InstanceDesc { return ring.InstanceDesc{Zone: zone, State: state, Tokens: tokens} From 94606e0ecd9348ebc188505ae08f37aeea1a7e8e Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:10:06 +0000 Subject: [PATCH 14/18] ingester: test the ownership refresh the ingester runs No test ran the refresh as the ingester wires it: a refresh that ignored the service's context, or published nothing to the limiter, would have passed. Move the service's iteration into Ingester.refreshOwnership and test it on an ingester whose lifecycler heartbeats the ring: it publishes its tenant's share to the limiter, and a refresh stopped by the context publishes nothing. The ingester's services are not started, so the test does not refresh at the same time as the service. Signed-off-by: Alan Protasio --- pkg/ingester/ingester.go | 5 +---- pkg/ingester/ownership.go | 7 ++++++ pkg/ingester/ownership_test.go | 41 ++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/pkg/ingester/ingester.go b/pkg/ingester/ingester.go index afdda22b49..c57f89aa59 100644 --- a/pkg/ingester/ingester.go +++ b/pkg/ingester/ingester.go @@ -1044,10 +1044,7 @@ func (i *Ingester) starting(ctx context.Context) error { if i.ownershipRefresher != nil { // Its own service: after a ring change a refresh can take seconds, which // must not delay updateLoop and the ingestion rate it ticks. - servs = append(servs, services.NewTimerService(ownershipRefreshPeriod, nil, func(ctx context.Context) error { - i.ownershipRefresher.refresh(ctx, i.getTSDBUsers()) - return nil - }, nil)) + servs = append(servs, services.NewTimerService(ownershipRefreshPeriod, nil, i.refreshOwnership, nil)) } if i.cfg.BlocksStorageConfig.TSDB.IsBlocksShippingEnabled() { diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index b7062de397..c75868d800 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -188,6 +188,13 @@ func newOwnershipRefresher(latest func() *ring.Desc, newRing func() (*ring.Ring, } } +// refreshOwnership refreshes the ownership shares of the ingester's tenants, +// as the iteration of a service of its own that stops it when ctx is done. +func (i *Ingester) refreshOwnership(ctx context.Context) error { + i.ownershipRefresher.refresh(ctx, i.getTSDBUsers()) + return nil +} + // refresh refreshes the shares of userIDs. If ctx is done before every tenant // is refreshed, it returns without changing the shares. func (o *ownershipRefresher) refresh(ctx context.Context, userIDs []string) { diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 7a572db719..c9b5c61cb4 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -20,6 +20,8 @@ import ( "github.com/cortexproject/cortex/pkg/ring" "github.com/cortexproject/cortex/pkg/ring/kv/consul" "github.com/cortexproject/cortex/pkg/util" + "github.com/cortexproject/cortex/pkg/util/services" + "github.com/cortexproject/cortex/pkg/util/test" "github.com/cortexproject/cortex/pkg/util/validation" ) @@ -1164,6 +1166,45 @@ func TestOwnershipRefresher_OwnChangeOutsideTheSubring(t *testing.T) { assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) } +// The ingester's refresh publishes the shares of its tenants to its limiter, +// from the ring its lifecycler heartbeats, and one stopped by the service's +// context publishes nothing. +func TestIngester_RefreshOwnership(t *testing.T) { + const userID = "user-1" + cfg := defaultIngesterTestConfig(t) + cfg.LifecyclerConfig.JoinAfter = 0 + cfg.LifecyclerConfig.HeartbeatPeriod = 100 * time.Millisecond + cfg.LifecyclerConfig.Zone = "zone-a" + cfg.LifecyclerConfig.RingConfig.ZoneAwarenessEnabled = true + cfg.LifecyclerConfig.RingConfig.ReplicationFactor = 1 + cfg.UseRingOwnershipForLimits = true + i, err := prepareIngesterWithBlocksStorage(t, cfg, prometheus.NewRegistry()) + require.NoError(t, err) + + // Only the lifecycler runs, so the ingester's own refresh service does not + // refresh at the same time as the test. + require.NoError(t, services.StartAndAwaitRunning(context.Background(), i.lifecycler)) + t.Cleanup(func() { assert.NoError(t, services.StopAndAwaitTerminated(context.Background(), i.lifecycler)) }) + i.lifecycler.Join() + test.Poll(t, 5*time.Second, true, func() any { + return len(i.ownershipRefresher.latest().GetIngesters()[cfg.LifecyclerConfig.ID].Tokens) > 0 + }) + _, err = i.getOrCreateTSDB(userID, true) + require.NoError(t, err) + t.Cleanup(i.closeAllTSDB) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.NoError(t, i.refreshOwnership(ctx)) + _, ok := i.limiter.ownership.share(userID) + assert.False(t, ok, "a stopped refresh publishes nothing") + + require.NoError(t, i.refreshOwnership(context.Background())) + share, ok := i.limiter.ownership.share(userID) + require.True(t, ok) + assert.Equal(t, 1.0, share, "the only ingester owns all of its zone") +} + func TestInstanceHasher(t *testing.T) { instance := func(zone string, state ring.InstanceState, tokens ...uint32) ring.InstanceDesc { return ring.InstanceDesc{Zone: zone, State: state, Tokens: tokens} From b96f2ce833184d26c3e25d11dd35300e3c0c38f9 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:10:18 +0000 Subject: [PATCH 15/18] CHANGELOG: fold the ring ownership entries into one -ingester.use-ring-ownership-for-limits is not released yet, so describe it once, as it now behaves, under both pull requests. Signed-off-by: Alan Protasio --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4dbee812ba..85d32072aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,7 @@ * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 -* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`. With zone-aware replication, global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share. Requires zone-aware replication; while the number of zones in the ring differs from the replication factor, the equal-share conversion is used. On an unevenly balanced ring the equal-share assumption throttles tenants on the ingesters with the largest share well before they reach their global limit. The ring is read from the ingester's own heartbeats, so no KV store traffic is added. The share in use is exposed as `cortex_ingester_ring_ownership_share{user}`. #7954 -* [ENHANCEMENT] Ingester: With `-ingester.use-ring-ownership-for-limits`, keep only each tenant's ownership share instead of a cached subring per tenant, and recompute it only when the tenant's subring changes. Shares no longer follow `-distributor.extend-writes`: while an instance is JOINING, LEAVING or PENDING, the instance that takes its writes can throttle a tenant before it reaches its global limit. Adds the `cortex_ingester_ring_ownership_computations_total` metric. #7961 +* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`, which requires zone-aware replication. Global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share, an assumption that on an unevenly balanced ring throttles tenants well before their global limit. While the number of zones differs from the replication factor, the equal-share conversion is used. Shares do not follow `-distributor.extend-writes`: while an instance is JOINING, LEAVING or PENDING, the instance that takes its writes can throttle a tenant early. Shares are computed from the ingester's own heartbeats, without KV store traffic, and recomputed only when a tenant's subring changes. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 From 3b0543fe112e323495e7831f3de33e114a9e4b3c Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:26:57 +0000 Subject: [PATCH 16/18] ingester: rename the ownership share's unsure flag to duplicates Since shares are computed from a ring no heartbeat changes, the flag is set only from HasDuplicateTokens: it records that a token was held twice when the share was computed. Name it after that, so the reuse check reads as no token held twice, then or now. Signed-off-by: Alan Protasio --- pkg/ingester/ownership.go | 9 +++++---- pkg/ingester/ownership_test.go | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pkg/ingester/ownership.go b/pkg/ingester/ownership.go index c75868d800..266b622931 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -163,8 +163,9 @@ type tenantShare struct { self uint64 share float64 zones int - // Computed while a token was shared: recompute after the next change. - unsure bool + // A token was held twice when this share was computed: recompute it after + // the next change. + duplicates bool } // newOwnershipRefresher returns a refresher that reads the desc from latest, @@ -239,13 +240,13 @@ func (o *ownershipRefresher) refresh(ctx context.Context, userIDs []string) { if sub.HasInstance(o.instanceID) { member = self } - if known && prev.fingerprint == fingerprint && prev.self == member && !prev.unsure && !duplicates { + if known && prev.fingerprint == fingerprint && prev.self == member && !prev.duplicates && !duplicates { tenants[userID] = prev // The tenant's subring is as before. continue } t := w.compute(sub, fingerprint) t.self = member - t.unsure = duplicates + t.duplicates = duplicates t.shardSize = size tenants[userID] = t } diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index c9b5c61cb4..600c926efc 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -683,7 +683,7 @@ func testOwnershipRefresherCachedSharesMatchFreshComputation(t *testing.T, share func comparableShares(tenants map[string]tenantShare) map[string]tenantShare { out := make(map[string]tenantShare, len(tenants)) for id, t := range tenants { - t.unsure = false + t.duplicates = false out[id] = t } return out From 6cbe13f4270740c0c2170acebaff7cbf14d03b32 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:28:37 +0000 Subject: [PATCH 17/18] CHANGELOG: shorten the ring ownership entry Signed-off-by: Alan Protasio --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85d32072aa..af2b359c46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 -* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits`, which requires zone-aware replication. Global series and metadata limits are converted to per-ingester limits using the share of each tenant's hash space (or shuffle shard) the ingester owns within its zone, instead of assuming every ingester owns an equal share, an assumption that on an unevenly balanced ring throttles tenants well before their global limit. While the number of zones differs from the replication factor, the equal-share conversion is used. Shares do not follow `-distributor.extend-writes`: while an instance is JOINING, LEAVING or PENDING, the instance that takes its writes can throttle a tenant early. Shares are computed from the ingester's own heartbeats, without KV store traffic, and recomputed only when a tenant's subring changes. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 +* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873 From 02693496c5f01f78a2a6a30134ff0cbbda9b4ce9 Mon Sep 17 00:00:00 2001 From: Alan Protasio Date: Tue, 24 Nov 2026 04:30:08 +0000 Subject: [PATCH 18/18] CHANGELOG: note that ring ownership shares ignore extend-writes Signed-off-by: Alan Protasio --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af2b359c46..82c5b6d138 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 -* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 +* [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Shares ignore `-distributor.extend-writes`, so a tenant can be throttled early while an instance is JOINING, LEAVING or PENDING. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 * [ENHANCEMENT] Ruler: Add rule information to query parameters sent to the Query Frontend when `-ruler.frontend-address` is configured, so the Query Frontend query stats logs (`-frontend.enabled-ruler-query-stats`) can identify the evaluated rule. In this mode, the Ruler query stats log (`-ruler.query-stats-enabled`) omits the fetched statistics fields, which are always zero. #6539 * [ENHANCEMENT] gRPC: When `-auth.enabled=true`, a gRPC request without the `X-Scope-OrgID` metadata is now rejected with the `UNAUTHENTICATED` status code instead of `UNKNOWN`. #7873