Skip to content

Commit fcc660d

Browse files
authored
ring: count each key once when it reaches quorum in DoBatch (#7975)
* ring: count a key once when DoBatch reaches its quorum batchTracker.record decremented rpcsPending on every success at or past a key's quorum. With RF 3 a fully replicated key counted twice, so in rare cases DoBatch returned success before every key reached quorum, and an error from a key that failed on all its replicas was not returned. Count a key only on the success that reaches its quorum, as dskit does (grafana/dskit#430). Successes past quorum still skip the remaining-instances check. Require at least one success per key, so a replication set with MaxErrors >= len(Instances) cannot leave the key uncounted. Signed-off-by: Alan Protasio <alanprot@gmail.com> * ring: test DoBatch quorum accounting Scripted tests fix the order in which DoBatch records each instance's outcome: fully replicated keys next to keys that miss quorum (4xx and 5xx, several orders), keys at exactly quorum, error family selection, a replica filtered out, MaxErrors 0 and MaxErrors >= len(Instances), failed RPCs counting for every key in them, and outcomes recorded after the context is canceled. TestDoBatch_EveryCompletionOrder checks every result and completion order over small layouts. Randomized tests, one over a real ring, check concurrent completion against the quorum of each key, and that DoBatch never answers success before every key has quorum among the RPCs that have returned. Signed-off-by: Alan Protasio <alanprot@gmail.com> * distributor: test Push when series are rejected by their ingesters Push fails when a series is rejected by all its ingesters while the other series replicate fully. mockIngester can now reject chosen series the way a real ingester does: store the others and fail the whole RPC with 400. Tests pin how such a failure counts against every series in the RPC. Signed-off-by: Alan Protasio <alanprot@gmail.com> * CHANGELOG: DoBatch quorum fix Signed-off-by: Alan Protasio <alanprot@gmail.com> * CHANGELOG: add PR number for the DoBatch quorum fix Signed-off-by: Alan Protasio <alanprot@gmail.com> --------- Signed-off-by: Alan Protasio <alanprot@gmail.com>
1 parent 52d7bff commit fcc660d

4 files changed

Lines changed: 1272 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
* [BUGFIX] Querier: Increment `cortex_query_evictions_total` and deregister the victim before cancelling it in the query evictor, fixing double-counted evictions of still-unwinding queries. #7616
4141
* [BUGFIX] Ring: Ignore READONLY ingesters when assigning tokens so the active series remain balanced. #7946
4242
* [BUGFIX] Distributor: Fix a `panic: send on closed channel` crash during shutdown when `-distributor.num-push-workers` or `-distributor.num-query-workers` is greater than 0. #7964
43+
* [BUGFIX] Ring: Fix `DoBatch` counting a key more than once when more replicas than the quorum succeed, which in rare cases could hide a write error from a key that did not reach quorum. A distributor push now always waits until every series reaches quorum, so it returns the error of a series that misses quorum, and takes as long as its slowest series to reach quorum. #7975
4344

4445
## 1.22.0 2026-11-19
4546

‎pkg/distributor/distributor_test.go‎

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
package distributor
22

33
import (
4+
"cmp"
45
"context"
56
"fmt"
67
"io"
78
"maps"
89
"math"
910
"math/rand"
1011
"net/http"
12+
"slices"
1113
"sort"
1214
"strconv"
1315
"strings"
@@ -1384,6 +1386,252 @@ func TestDistributor_PushInstanceLimits(t *testing.T) {
13841386
}
13851387
}
13861388

1389+
// A request whose series all replicate fully, except one rejected by every
1390+
// ingester it is sharded to, must fail: that series is stored nowhere.
1391+
func TestDistributor_Push_ShouldFailWhenASeriesIsRejectedByAllItsIngesters(t *testing.T) {
1392+
t.Parallel()
1393+
1394+
const userID = "user"
1395+
replicated := labels.FromStrings(model.MetricNameLabel, "replicated")
1396+
rejected := labels.FromStrings(model.MetricNameLabel, "rejected")
1397+
replicatedToken := shardByAllLabels(userID, cortexpb.FromLabelsToLabelAdapters(replicated))
1398+
rejectedToken := shardByAllLabels(userID, cortexpb.FromLabelsToLabelAdapters(rejected))
1399+
require.NotEqual(t, replicatedToken, rejectedToken)
1400+
require.Less(t, max(replicatedToken, rejectedToken), uint32(math.MaxUint32-3))
1401+
1402+
// Ingesters 0-2 own the tokens right after the replicated series and
1403+
// ingesters 3-5 those right after the rejected one, so with RF 3 each series
1404+
// is written to exactly one group.
1405+
tokens := make([][]uint32, 0, 6)
1406+
for _, token := range []uint32{replicatedToken, rejectedToken} {
1407+
for i := range uint32(3) {
1408+
tokens = append(tokens, []uint32{token + 1 + i})
1409+
}
1410+
}
1411+
1412+
tests := map[string]struct {
1413+
err error
1414+
wantCode int32
1415+
}{
1416+
"4xx": {err: httpgrpc.Errorf(http.StatusBadRequest, "per-user series limit exceeded"), wantCode: http.StatusBadRequest},
1417+
"5xx": {err: errFail, wantCode: http.StatusInternalServerError},
1418+
}
1419+
for name, tc := range tests {
1420+
t.Run(name, func(t *testing.T) {
1421+
t.Parallel()
1422+
1423+
ds, ingesters, _, _ := prepare(t, prepConfig{
1424+
numIngesters: 6,
1425+
happyIngesters: 3,
1426+
numDistributors: 1,
1427+
shardByAllLabels: true,
1428+
replicationFactor: 3,
1429+
errFail: tc.err,
1430+
tokens: tokens,
1431+
})
1432+
1433+
// Hold the rejections until the replicated series has been written
1434+
// to all three of its ingesters.
1435+
rejections := make(chan struct{})
1436+
releaseRejections := sync.OnceFunc(func() { close(rejections) })
1437+
t.Cleanup(releaseRejections)
1438+
for _, ing := range ingesters[3:] {
1439+
ing.pushGate = rejections
1440+
}
1441+
1442+
ctx := user.InjectOrgID(context.Background(), userID)
1443+
req := mockWriteRequest([]labels.Labels{replicated, rejected}, 1, time.Now().UnixMilli(), false)
1444+
result := make(chan error, 1)
1445+
go func() {
1446+
_, err := ds[0].Push(ctx, req)
1447+
result <- err
1448+
}()
1449+
1450+
for _, ing := range ingesters[:3] {
1451+
test.Poll(t, time.Second, 1, func() any { return len(ing.series()) })
1452+
}
1453+
// A slow machine can only make this miss an early return of the bug,
1454+
// never fail a correct Push.
1455+
select {
1456+
case err := <-result:
1457+
require.FailNow(t, "Push returned before the rejected series was answered", "err: %v", err)
1458+
case <-time.After(100 * time.Millisecond):
1459+
}
1460+
releaseRejections()
1461+
1462+
err := <-result
1463+
require.Error(t, err)
1464+
resp, ok := httpgrpc.HTTPResponseFromError(err)
1465+
require.True(t, ok, "not an HTTP error: %v", err)
1466+
require.Equal(t, tc.wantCode, resp.Code, "unexpected error: %v", err)
1467+
1468+
// The rejected series was sent to all three of its ingesters.
1469+
for _, ing := range ingesters[3:] {
1470+
test.Poll(t, time.Second, 1, func() any { return ing.countCalls("Push") })
1471+
}
1472+
})
1473+
}
1474+
}
1475+
1476+
// rejectSeries returns a mockIngester.rejectSeries hook rejecting exactly lbls.
1477+
func rejectSeries(lbls labels.Labels) func([]cortexpb.LabelAdapter) bool {
1478+
return func(series []cortexpb.LabelAdapter) bool {
1479+
return labels.Equal(cortexpb.FromLabelAdaptersToLabels(series), lbls)
1480+
}
1481+
}
1482+
1483+
// An ingester that rejects one series fails its whole Push, and the distributor
1484+
// counts that failure against every series in the Push. A valid series sharing
1485+
// such ingesters with a series rejected everywhere is reported along with it.
1486+
func TestDistributor_Push_PartialRejectionFailsEverySeriesInTheRPC(t *testing.T) {
1487+
t.Parallel()
1488+
1489+
const userID = "user"
1490+
series := []labels.Labels{
1491+
labels.FromStrings(model.MetricNameLabel, "alpha_total"),
1492+
labels.FromStrings(model.MetricNameLabel, "bravo_seconds"),
1493+
labels.FromStrings(model.MetricNameLabel, "charlie_bytes"),
1494+
labels.FromStrings(model.MetricNameLabel, "delta_ratio"),
1495+
}
1496+
type hashedSeries struct {
1497+
lbls labels.Labels
1498+
token uint32
1499+
}
1500+
hashed := make([]hashedSeries, 0, len(series))
1501+
for _, lbls := range series {
1502+
hashed = append(hashed, hashedSeries{lbls, shardByAllLabels(userID, cortexpb.FromLabelsToLabelAdapters(lbls))})
1503+
}
1504+
slices.SortFunc(hashed, func(a, b hashedSeries) int { return cmp.Compare(a.token, b.token) })
1505+
q := []uint32{hashed[0].token, hashed[1].token, hashed[2].token}
1506+
require.Greater(t, q[0], uint32(2))
1507+
require.Greater(t, q[1], q[0]+1)
1508+
require.GreaterOrEqual(t, q[2], q[1]+3)
1509+
1510+
// With RF 3 these tokens put the first series on ingesters 2-4, the
1511+
// second (rejected) on 3-5, and the other two on 0-2.
1512+
tokens := [][]uint32{{q[0] - 2}, {q[0] - 1}, {q[0] + 1}, {q[1] + 1}, {q[1] + 2}, {q[1] + 3}}
1513+
rejected := hashed[1].lbls
1514+
1515+
ds, ingesters, _, _ := prepare(t, prepConfig{
1516+
numIngesters: 6,
1517+
happyIngesters: 6,
1518+
numDistributors: 1,
1519+
shardByAllLabels: true,
1520+
replicationFactor: 3,
1521+
tokens: tokens,
1522+
})
1523+
for _, ing := range ingesters[3:] {
1524+
ing.rejectSeries = rejectSeries(rejected)
1525+
}
1526+
1527+
ctx := user.InjectOrgID(context.Background(), userID)
1528+
_, err := ds[0].Push(ctx, mockWriteRequest(series, 1, time.Now().UnixMilli(), false))
1529+
require.Error(t, err)
1530+
resp, ok := httpgrpc.HTTPResponseFromError(err)
1531+
require.True(t, ok, "not an HTTP error: %v", err)
1532+
require.Equal(t, int32(http.StatusBadRequest), resp.Code, "unexpected error: %v", err)
1533+
1534+
// The first series was stored on all of its ingesters despite the error.
1535+
for _, ing := range ingesters[2:5] {
1536+
test.Poll(t, time.Second, true, func() any { _, found := ing.series()[hashed[0].token]; return found })
1537+
}
1538+
}
1539+
1540+
// Two ingesters each reject a different series, so a series sent to both is
1541+
// counted as failed on two of its three ingesters although all three store it.
1542+
// The push fails with 400 whatever the order of the responses: DoBatch only
1543+
// sees whole-RPC results. Before quorum was counted once per series, it could
1544+
// return success or 400 depending on that order.
1545+
func TestDistributor_Push_RejectionsOnTwoIngestersFailASeriesStoredOnAll(t *testing.T) {
1546+
t.Parallel()
1547+
1548+
const userID = "user"
1549+
type hashedSeries struct {
1550+
lbls labels.Labels
1551+
token uint32
1552+
}
1553+
var hashed []hashedSeries
1554+
// shardByAllLabels is FNV-1: names differing only in their last bytes hash
1555+
// a few units apart. Find six series whose tokens are spread enough.
1556+
for base := 0; ; base++ {
1557+
hashed = hashed[:0]
1558+
for i := range 6 {
1559+
lbls := labels.FromStrings(model.MetricNameLabel, fmt.Sprintf("series_%d_total", base*6+i))
1560+
hashed = append(hashed, hashedSeries{lbls, shardByAllLabels(userID, cortexpb.FromLabelsToLabelAdapters(lbls))})
1561+
}
1562+
slices.SortFunc(hashed, func(a, b hashedSeries) int { return cmp.Compare(a.token, b.token) })
1563+
spread := hashed[5].token < uint32(math.MaxUint32-2)
1564+
for i := 1; i < len(hashed); i++ {
1565+
spread = spread && hashed[i].token >= hashed[i-1].token+4
1566+
}
1567+
if spread {
1568+
break
1569+
}
1570+
}
1571+
token := func(i int) uint32 { return hashed[i].token }
1572+
1573+
// With RF 3: series 0 -> ingesters 0-2, series 1 -> 1-3, series 2-4 -> 2-4,
1574+
// series 5 -> 5, 0, 1.
1575+
tokens := [][]uint32{{token(0) + 1}, {token(1) + 1}, {token(4) + 1}, {token(4) + 2}, {token(4) + 3}, {token(5) + 1}}
1576+
all := make([]labels.Labels, 0, len(hashed))
1577+
for _, h := range hashed {
1578+
all = append(all, h.lbls)
1579+
}
1580+
1581+
ds, ingesters, _, _ := prepare(t, prepConfig{
1582+
numIngesters: 6,
1583+
happyIngesters: 6,
1584+
numDistributors: 1,
1585+
shardByAllLabels: true,
1586+
replicationFactor: 3,
1587+
tokens: tokens,
1588+
})
1589+
// Ingester 0 rejects series 5 and ingester 1 rejects series 1. Series 0 is
1590+
// sent to both. Hold both until the other ingesters have answered, the order
1591+
// in which unfixed code answered success.
1592+
rejections := make(chan struct{})
1593+
releaseRejections := sync.OnceFunc(func() { close(rejections) })
1594+
t.Cleanup(releaseRejections)
1595+
ingesters[0].pushGate = rejections
1596+
ingesters[0].rejectSeries = rejectSeries(hashed[5].lbls)
1597+
ingesters[1].pushGate = rejections
1598+
ingesters[1].rejectSeries = rejectSeries(hashed[1].lbls)
1599+
1600+
ctx := user.InjectOrgID(context.Background(), userID)
1601+
result := make(chan error, 1)
1602+
go func() {
1603+
_, err := ds[0].Push(ctx, mockWriteRequest(all, 1, time.Now().UnixMilli(), false))
1604+
result <- err
1605+
}()
1606+
for _, ing := range ingesters[2:] {
1607+
test.Poll(t, time.Second, 1, func() any { return ing.countCalls("Push") })
1608+
}
1609+
releaseRejections()
1610+
1611+
err := <-result
1612+
require.Error(t, err)
1613+
resp, ok := httpgrpc.HTTPResponseFromError(err)
1614+
require.True(t, ok, "not an HTTP error: %v", err)
1615+
require.Equal(t, int32(http.StatusBadRequest), resp.Code, "unexpected error: %v", err)
1616+
1617+
// Every series is stored on at least two of its ingesters, series 0 on all three.
1618+
for i, h := range hashed {
1619+
want := 2
1620+
if i == 0 {
1621+
want = 3
1622+
}
1623+
test.Poll(t, time.Second, true, func() any {
1624+
stored := 0
1625+
for _, ing := range ingesters {
1626+
if _, found := ing.series()[h.token]; found {
1627+
stored++
1628+
}
1629+
}
1630+
return stored >= want
1631+
})
1632+
}
1633+
}
1634+
13871635
func TestDistributor_PushHAInstances(t *testing.T) {
13881636
t.Parallel()
13891637
ctx := user.InjectOrgID(context.Background(), "user")
@@ -3758,6 +4006,11 @@ type mockIngester struct {
37584006
calls map[string]int
37594007
lblsValues []string
37604008
lastDiscardOutOfOrder bool
4009+
// pushGate, when set, holds every Push until it is closed. Set before the first Push.
4010+
pushGate chan struct{}
4011+
// rejectSeries, when set, makes Push behave like a real ingester rejecting
4012+
// some series: store the others and fail the whole RPC with 400. Set before the first Push.
4013+
rejectSeries func([]cortexpb.LabelAdapter) bool
37614014
}
37624015

37634016
func newMockIngester(id int, ps *prepState, cfg prepConfig) *mockIngester {
@@ -3823,6 +4076,10 @@ func (i *mockIngester) PushStreamConnection(ctx context.Context, in *cortexpb.Wr
38234076
}
38244077

38254078
func (i *mockIngester) Push(ctx context.Context, req *cortexpb.WriteRequest, opts ...grpc.CallOption) (*cortexpb.WriteResponse, error) {
4079+
if i.pushGate != nil {
4080+
<-i.pushGate
4081+
}
4082+
38264083
i.Lock()
38274084
defer i.Unlock()
38284085

@@ -3848,8 +4105,13 @@ func (i *mockIngester) Push(ctx context.Context, req *cortexpb.WriteRequest, opt
38484105
return nil, err
38494106
}
38504107

4108+
var partialErr error
38514109
for j := range req.Timeseries {
38524110
series := req.Timeseries[j]
4111+
if i.rejectSeries != nil && i.rejectSeries(series.Labels) {
4112+
partialErr = httpgrpc.Errorf(http.StatusBadRequest, "per-metric series limit exceeded")
4113+
continue
4114+
}
38534115
hash := shardByAllLabels(orgid, series.Labels)
38544116
existing, ok := i.timeseries[hash]
38554117
if !ok {
@@ -3878,6 +4140,9 @@ func (i *mockIngester) Push(ctx context.Context, req *cortexpb.WriteRequest, opt
38784140
set[*m] = struct{}{}
38794141
}
38804142

4143+
if partialErr != nil {
4144+
return &cortexpb.WriteResponse{}, partialErr
4145+
}
38814146
return &cortexpb.WriteResponse{}, nil
38824147
}
38834148

‎pkg/ring/batch.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ func DoBatch(ctx context.Context, op Operation, r ReadRing, e util.AsyncExecutor
9696
cleanup()
9797
return err
9898
}
99-
itemTrackers[i].minSuccess = len(replicationSet.Instances) - replicationSet.MaxErrors
99+
// record counts a key on the success equal to minSuccess, so it must be at least 1.
100+
itemTrackers[i].minSuccess = max(1, len(replicationSet.Instances)-replicationSet.MaxErrors)
100101
itemTrackers[i].maxFailures = replicationSet.MaxErrors
101102
itemTrackers[i].remaining.Store(int32(len(replicationSet.Instances)))
102103

@@ -153,7 +154,7 @@ func (b *batchTracker) record(instance instance, err error) {
153154
// number of pending samples by one.
154155
//
155156
// The use of atomic increments here is needed as:
156-
// * rpcsPending and rpcsPending guarantees only a single sendSamples goroutine will write to either channel
157+
// * rpcsPending and rpcsFailed guarantees only a single sendSamples goroutine will write to either channel
157158
// * succeeded, failed4xx, failed5xx and remaining guarantees that the "return decision" is made atomically
158159
// avoiding race condition
159160
sampleTrackers := instance.itemTrackers
@@ -185,9 +186,9 @@ func (b *batchTracker) record(instance instance, err error) {
185186
continue
186187
}
187188
} else {
188-
// If we successfully push all samples to min success instances,
189-
// wake up the waiting rpc so it can return early.
190-
if sampleTrackers[i].succeeded.Inc() >= int32(sampleTrackers[i].minSuccess) {
189+
// Count each key once, on the success that reaches its quorum.
190+
succeeded := sampleTrackers[i].succeeded.Inc()
191+
if succeeded == int32(sampleTrackers[i].minSuccess) {
191192
if b.rpcsPending.Dec() == 0 {
192193
b.done <- struct{}{}
193194
}
@@ -197,7 +198,7 @@ func (b *batchTracker) record(instance instance, err error) {
197198
// If we succeeded to call this particular ingester but we dont have any remaining ingesters to try
198199
// and we did not succeeded calling `minSuccess` ingesters we need to return the last error
199200
// Ex: 4xx, 5xx, 2xx
200-
if sampleTrackers[i].remaining.Dec() == 0 {
201+
if succeeded < int32(sampleTrackers[i].minSuccess) && sampleTrackers[i].remaining.Dec() == 0 {
201202
if b.rpcsFailed.Inc() == 1 {
202203
b.err <- httpgrpcutil.WrapHTTPGrpcError(
203204
sampleTrackers[i].getError(), "not enough remaining instances to try, addr=%s state=%s zone=%s",

0 commit comments

Comments
 (0)