diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bea11a112..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`. 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: 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 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/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..c57f89aa59 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"` @@ -898,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 @@ -918,12 +917,13 @@ 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) - 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, cfg.DistributorExtendWrites, i.limiter.shuffleShardingEnabled, limits, registerer) + i.ownershipRefresher = newOwnershipRefresher(ownershipDelegate.latest, newRing, i.lifecycler.ID, i.limiter.shuffleShardingEnabled, limits, registerer) i.limiter.ownership = i.ownershipRefresher.ownership } @@ -1041,6 +1041,12 @@ 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, i.refreshOwnership, nil)) + } + if i.cfg.BlocksStorageConfig.TSDB.IsBlocksShippingEnabled() { shippingService := services.NewBasicService(nil, i.shipBlocksLoop, nil) servs = append(servs, shippingService) @@ -1143,13 +1149,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: @@ -1177,8 +1176,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 006789ebfd..266b622931 100644 --- a/pkg/ingester/ownership.go +++ b/pkg/ingester/ownership.go @@ -1,35 +1,120 @@ package ingester import ( + "context" + "encoding/binary" + "maps" + "slices" + "sync" "time" + "github.com/cespare/xxhash/v2" + "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" ) 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 -// 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 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 { - ring atomic.Pointer[ring.Ring] + enabled bool + + mtx sync.Mutex + // 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 -// 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) { - if r := d.ring.Load(); r != nil { - r.UpdateDesc(ringDesc) + if !d.enabled { + return + } + // Callbacks can overlap. + d.mtx.Lock() + defer d.mtx.Unlock() + if d.desc == nil || sharesMayDiffer(d.desc, ringDesc) { + d.desc = copyDesc(ringDesc) + } +} + +// 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 +} + +// 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. 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 + } + 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 +// 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 the fields of an instance that sharesMayDiffer +// compares. 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) } + h.buf = b + return xxhash.Sum64(b) +} + +// 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) } // tenantOwnership holds this ingester's share of each tenant's hash space @@ -50,28 +135,46 @@ 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 + newRing func() (*ring.Ring, error) instanceID string - writeOp ring.Operation shuffleShardingEnabled bool limits *validation.Overrides ownership *tenantOwnership shareGauge *prometheus.GaugeVec + 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. lastDesc is the + // desc the last complete refresh read. + ring *ring.Ring + lastDesc *ring.Desc + 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 { + shardSize int + fingerprint uint64 + // 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 + // 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, +// and builds a ring from it with newRing whenever it changed. +func newOwnershipRefresher(latest func() *ring.Desc, 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, - writeOp: writeOp, shuffleShardingEnabled: shuffleShardingEnabled, limits: limits, ownership: &tenantOwnership{}, @@ -79,29 +182,89 @@ 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 ring ownership share was computed.", + }), } } -func (o *ownershipRefresher) refresh(userIDs []string) { - if o.ring.InstancesCount() == 0 { - // No heartbeat has fed the ring yet. - return +// 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) { + desc := o.latest() + if len(desc.GetIngesters()) == 0 { + return // No heartbeat has fed the ring yet. + } + ringChanged := desc != o.lastDesc + if ringChanged { + r, err := o.newRing() + if err != nil { + return // Not reached: New fails on an invalid config. + } + r.UpdateDesc(desc) + o.ring = r } - shares := make(map[string]float64, len(userIDs)) + // 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)) 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) + if ctx.Err() != nil { + return + } + 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 } - zonal, ok := sub.(ring.ZonalOwnershipRing) + sub := o.subring(userID, size) + fingerprint := w.fingerprintOf(sub) + member := uint64(0) + if sub.HasInstance(o.instanceID) { + member = self + } + 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.duplicates = duplicates + t.shardSize = size + tenants[userID] = t + } + o.lastDesc = desc + 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 !ok || zonal.ZonesCount() != o.ring.ReplicationFactor() { - continue + if t.zones == o.ring.ReplicationFactor() { + shares[userID] = t.share } - shares[userID] = zonal.ZonalOwnership(o.writeOp)[o.instanceID] } o.ownership.shares.Store(&shares) @@ -110,3 +273,87 @@ func (o *ownershipRefresher) refresh(userIDs []string) { o.shareGauge.WithLabelValues(userID).Set(share) } } + +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. +func (w *wholeRingMemo) compute(sub ring.ReadRing, fingerprint uint64) tenantShare { + if !w.isWholeRing(sub) { + t := w.o.computeShare(sub) + t.fingerprint = fingerprint + return t + } + if w.share == nil { + t := w.o.computeShare(sub) + t.fingerprint = 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 { + 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 ( + hasher instanceHasher + sum uint64 + ) + for _, members := range [][]ring.InstanceDesc{healthy, unhealthy} { + for _, member := range members { + // Summed rather than XORed, so identical members do not cancel. + sum += hasher.hash(member) + } + } + return sum +} diff --git a/pkg/ingester/ownership_test.go b/pkg/ingester/ownership_test.go index 845a12fce2..600c926efc 100644 --- a/pkg/ingester/ownership_test.go +++ b/pkg/ingester/ownership_test.go @@ -1,20 +1,27 @@ package ingester import ( + "context" "fmt" + "maps" "math" "math/rand" "slices" + "sync" "testing" "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" "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" ) @@ -74,32 +81,40 @@ 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(ring.Write) + ownership := r.ZonalOwnership() assert.NotContains(t, ownership, "b-1") assert.Positive(t, ownership["a-1"]) 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})) + assert.Nil(t, d.latest()) } func TestOwnershipRefresher(t *testing.T) { @@ -111,7 +126,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}, @@ -119,21 +133,25 @@ func TestOwnershipRefresher(t *testing.T) { overrides := validation.NewOverrides(limits, tenantLimits) ingesterID := ownershipTestInstanceID(0, 0) - refresher := newOwnershipRefresher(r, ingesterID, true, true, overrides, 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}) + refresher.refresh(context.Background(), []string{shuffledTenant, unshuffledTenant}) _, ok := refresher.ownership.share(unshuffledTenant) assert.False(t, ok) + d.OnRingInstanceHeartbeat(nil, desc) + refresher.refresh(context.Background(), []string{shuffledTenant, unshuffledTenant}) + + r := newOwnershipTestRing(t, layout.zones, nil) r.UpdateDesc(desc) - refresher.refresh([]string{shuffledTenant, unshuffledTenant}) 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) @@ -151,11 +169,11 @@ 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), true, false, validation.NewOverrides(validation.Limits{}, nil), nil) - refresher.refresh([]string{tenant}) + refresher := newOwnershipRefresher(d.latest, newRing, ownershipTestInstanceID(0, 0), false, validation.NewOverrides(validation.Limits{}, nil), nil) + refresher.refresh(context.Background(), []string{tenant}) _, ok := refresher.ownership.share(tenant) assert.False(t, ok) @@ -242,8 +260,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{} @@ -272,8 +293,8 @@ func TestLimiter_OwnershipAvoidsThrottlingOnUnevenRing(t *testing.T) { throttledByEvenSplit++ } - refresher := newOwnershipRefresher(r, id, true, false, overrides, nil) - refresher.refresh([]string{tenant}) + refresher := newOwnershipRefresher(d.latest, newRing, id, false, overrides, nil) + 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) @@ -294,3 +315,1060 @@ func (s *staticTenantLimits) ByUserID(userID string) *validation.Limits { func (s *staticTenantLimits) AllByUserID() map[string]*validation.Limits { return s.limits } + +// 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() }) + 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()) + } +} + +// 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} + _, 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)) +} + +func TestRingOwnershipDelegate_KeepsADescOnEachChange(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) + changed 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), 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), changed: true, + }, + "an instance joins": { + 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) }, 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) { + instance := d.Ingesters["new"] + instance.Tokens = []uint32{42} + d.Ingesters["new"] = instance + }, + 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 + }, + changed: 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) + 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.changed, d.latest() != first) + }) + } +} + +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, 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(d.latest, newRing, me, true, overrides, nil) + 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. + members := map[string]bool{} + 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 + } + 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(context.Background(), []string{tenant}) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) + 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") + + limits.limits[tenant] = &validation.Limits{IngestionTenantShardSize: shardSize + 3} + 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(context.Background(), 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 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" + 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, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, desc) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + 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(context.Background(), []string{tenant}) + + fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + 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) +} + +// 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, newRing := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + 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(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") + assert.Equal(t, fresh, comparableShares(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, 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 { + // 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.latest() + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + if d.latest() != before { + bumps++ + } + refresher.refresh(context.Background(), tenants) + + 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 ring changed on %d of %d steps; ownership computed %v times", bumps, steps, testutil.ToFloat64(refresher.computations)) + assert.Less(t, bumps, steps) +} + +// comparableShares drops what only decides when a share is recomputed, so +// shares can be compared with ones computed from scratch. +func comparableShares(tenants map[string]tenantShare) map[string]tenantShare { + out := make(map[string]tenantShare, len(tenants)) + for id, t := range tenants { + t.duplicates = false + out[id] = t + } + return out +} + +// Heartbeat callbacks can overlap: the Lifecycler's first heartbeat runs on its +// 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) + neighbour := ownershipTestInstanceID(0, 1) + layout := ownershipTestRingLayout{zones: 3, perZone: 3, tokensPerInstance: 4} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + d, _ := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + + readOnly := cloneOwnershipTestDesc(desc) + setOwnershipTestState(neighbour, ring.READONLY)(readOnly) + + d.mtx.Lock() + done := make(chan struct{}) + go func() { + defer close(done) + d.OnRingInstanceHeartbeat(nil, readOnly) + }() + time.Sleep(wait) + 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.Equal(t, ring.READONLY, d.latest().Ingesters[neighbour].State) +} + +// 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() + d, newRing := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, desc) + fresh := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + fresh.refresh(context.Background(), tenants) + return comparableShares(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 leaves": { + sharedFromStart: true, + change: func(d *ring.Desc) { d.RemoveIngester(collider) }, + }, + "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, 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) + before := refresher.tenants[tenant].share + + next := cloneOwnershipTestDesc(desc) + tc.change(next) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(next)) + 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") + assert.Equal(t, fresh, comparableShares(refresher.tenants)) + }) + } +} + +// hookedTenantLimits runs hook once, the first time ByUserID is called for +// user, standing in for a heartbeat that lands 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) +} + +// 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 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) + 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, newRing := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, 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 + // 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(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(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") + assert.Equal(t, fresh, comparableShares(refresher.tenants)) +} + +// 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) + layout := ownershipTestRingLayout{zones: 4, perZone: 3, tokensPerInstance: 16} + desc := newOwnershipTestDesc(rand.New(rand.NewSource(ownershipTestSeed)), layout) + overrides := validation.NewOverrides(validation.Limits{}, &staticTenantLimits{limits: map[string]*validation.Limits{tenant: {IngestionTenantShardSize: 6}}}) + + d, newRing := newOwnershipTestDelegate(t, me, 3, "zone-3") + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + 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(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(context.Background(), []string{tenant}) + assert.Equal(t, comparableShares(want.tenants), comparableShares(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, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.refresh(context.Background(), []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(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") + require.NotEqual(t, before.share, fresh[tenant].share, "the layout must move the share") + assert.Equal(t, fresh, comparableShares(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, 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) + 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(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(context.Background(), tenants) + require.False(t, refresher.ring.HasDuplicateTokens()) + + assert.Equal(t, freshOwnershipShares(t, after, me, overrides, tenants), comparableShares(refresher.tenants)) + }) + } +} + +// 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" + 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} + + readOnly := readOnlyNeighbour(t, desc, me, layout.perZone, overrides, first) + + d, newRing := newOwnershipTestDelegate(t, me, layout.zones) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + 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. + limits.arm(second, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(readOnly)) }) + 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(context.Background(), tenants) + + assert.Equal(t, freshOwnershipShares(t, back, me, overrides, tenants), comparableShares(refresher.tenants)) +} + +// 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. +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, newRing := newOwnershipTestDelegate(t, me, layout.zones) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + 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(context.Background(), tenants) + heartbeat(desc) + refresher.refresh(context.Background(), tenants) + + require.Equal(t, freshOwnershipShares(t, desc, me, overrides, tenants), comparableShares(refresher.tenants), "step %d", step) + } +} + +// 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)) +} + +// 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} + } + 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, newRing := newOwnershipTestDelegate(t, me, 3) + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher := newOwnershipRefresher(d.latest, newRing, me, true, overrides, nil) + refresher.refresh(context.Background(), []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(context.Background(), []string{tenant}) + + _, 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) + + 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.refresh(context.Background(), tenants) + before := maps.Clone(refresher.tenants) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(changed)) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + refresher.refresh(ctx, tenants) + assert.Equal(t, before, refresher.tenants) + + refresher.refresh(context.Background(), 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(context.Background(), nil) + limits.arm(tenant, func() { d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(shared)) }) + refresher.refresh(context.Background(), []string{tenant}) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh(context.Background(), []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(context.Background(), []string{tenant}) + + d.OnRingInstanceHeartbeat(nil, cloneOwnershipTestDesc(desc)) + refresher.refresh(context.Background(), []string{tenant}) + assert.Equal(t, freshOwnershipShares(t, desc, me, overrides, []string{tenant}), comparableShares(refresher.tenants)) +} 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..d8b0d68b16 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,64 +24,71 @@ 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. +// 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. // // 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 } - 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.ownsTokenForWrites(token, op) { + // 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) } } @@ -96,18 +103,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..746dddabca 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,12 +140,32 @@ 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) } +// 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 { @@ -209,11 +221,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 +236,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 +339,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 +359,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)) + } + + // 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, + }, } - r.updateRingState(newOwnershipTestDesc(instances)) + 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()) + }) + } +} - cachedSubring := r.ShuffleShard(tenant, shardSize) - require.Same(t, subring, cachedSubring, "expected the cached subring") - assert.Zero(t, cachedSubring.(ZonalOwnershipRing).ZonalOwnership(Write)[target]) +// 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)) }