Skip to content

Commit b1a7e67

Browse files
authored
feat(ruler): add limit to list-rules API (#7785)
This commit adds a limit to the number of rules returned by the ListRules prometheus API, after which the API will truncate the result and return a pagination token for the next page. If a single rule group is larger than the max, that rule group will still be returned. This is being implemented after we found that JSON serializing a very large number of rules massively spikes the ruler CPU, which causes issues with rule evaluations and request timeouts. Signed-off-by: Kyle Stang <kylestng@amazon.com>
1 parent 7c30059 commit b1a7e67

11 files changed

Lines changed: 423 additions & 47 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
* [ENHANCEMENT] Update build image and Go version to 1.27.0. #7814
7777
* [ENHANCEMENT] Querier: Reduce merge iterator `BatchSize` from 12 to 8. #7823
7878
* [ENHANCEMENT] Upgrade promql-engine to latest. #7841
79+
* [ENHANCEMENT] Ruler: Add new limit `-ruler.list-rules-max-rules` on the total number of rules returned by the Prometheus ListRules API. Responses exceeding the limit are truncated on a rule group boundary and return a `groupNextToken` for retrieving the remaining groups. A rule group is never split, so a single group larger than the limit is still returned whole. Defaults to 0, which is unlimited. #7785
7980
* [BUGFIX] Querier: Fix queryWithRetry and labelsWithRetry returning (nil, nil) on cancelled context by propagating ctx.Err(). #7370
8081
* [BUGFIX] Metrics Helper: Fix non-deterministic bucket order in merged histograms by sorting buckets after map iteration, matching Prometheus client library behavior. #7380
8182
* [BUGFIX] Distributor: Return HTTP 401 Unauthorized when tenant ID resolution fails in the Prometheus Remote Write 2.0 path. #7389

‎docs/configuration/config-file-reference.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6238,6 +6238,14 @@ ring:
62386238
# CLI flag: -ruler.disabled-tenants
62396239
[disabled_tenants: <string> | default = ""]
62406240

6241+
# Maximum number of rules returned by the Prometheus ListRules API. If there are
6242+
# more rulegroups, the response will include a pagination token which can be
6243+
# used to fetch the next set. The API will always return at least one rulegroup,
6244+
# even if it contains more rules than the limit. Defaults to 0, which is
6245+
# unlimited
6246+
# CLI flag: -ruler.list-rules-max-rules
6247+
[list_rules_max_rules: <int> | default = 0]
6248+
62416249
# Report query statistics for ruler queries to complete as a per user metric and
62426250
# as an info level log message.
62436251
# CLI flag: -ruler.query-stats-enabled

‎pkg/ruler/api.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ func (a *API) PrometheusRules(w http.ResponseWriter, req *http.Request) {
186186
}
187187

188188
w.Header().Set("Content-Type", "application/json")
189-
response, err := a.ruler.GetRules(req.Context(), rulesRequest)
189+
response, err := a.ruler.GetRules(req.Context(), rulesRequest, a.ruler.cfg.ListRulesMaxRules)
190190

191191
if err != nil {
192192
util_api.RespondError(logger, w, v1.ErrServer, err.Error(), http.StatusInternalServerError)
@@ -346,7 +346,7 @@ func (a *API) PrometheusAlerts(w http.ResponseWriter, req *http.Request) {
346346
Type: alertingRuleFilter,
347347
MaxRuleGroups: -1,
348348
}
349-
rulesResponse, err := a.ruler.GetRules(req.Context(), rulesRequest)
349+
rulesResponse, err := a.ruler.GetRules(req.Context(), rulesRequest, 0)
350350

351351
if err != nil {
352352
util_api.RespondError(logger, w, v1.ErrServer, err.Error(), http.StatusInternalServerError)

‎pkg/ruler/api_test.go‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414

1515
"github.com/go-kit/log"
1616
"github.com/gorilla/mux"
17+
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
1718
"github.com/stretchr/testify/require"
1819
"github.com/weaveworks/common/user"
1920

@@ -426,6 +427,135 @@ func TestRuler_rules_limit(t *testing.T) {
426427
require.JSONEq(t, string(expectedResponse), string(actual))
427428
}
428429

430+
func TestRuler_rules_max_rules(t *testing.T) {
431+
// mockRulesNamespaces gives user1 two groups of two rules each: namespace2/fail
432+
// sorts before namespace1/group1 in rule group token order, so it is the group
433+
// that survives truncation. Filters and pagination vary how many rules a single
434+
// request returns.
435+
for _, tc := range []struct {
436+
name string
437+
rules map[string]rulespb.RuleGroupList
438+
userID string
439+
maxRules uint
440+
queryParams string
441+
expectedGroups int
442+
expectedRules int
443+
expectedNextToken string
444+
}{
445+
{
446+
name: "limit disabled returns every rule",
447+
rules: mockRulesNamespaces,
448+
userID: "user1",
449+
maxRules: 0,
450+
expectedGroups: 2,
451+
expectedRules: 4,
452+
},
453+
{
454+
name: "count below the limit",
455+
rules: mockRulesNamespaces,
456+
userID: "user1",
457+
maxRules: 10,
458+
expectedGroups: 2,
459+
expectedRules: 4,
460+
},
461+
{
462+
name: "count exactly at the limit",
463+
rules: mockRulesNamespaces,
464+
userID: "user1",
465+
maxRules: 4,
466+
expectedGroups: 2,
467+
expectedRules: 4,
468+
},
469+
{
470+
name: "count over the limit is truncated, summed across groups",
471+
rules: mockRulesNamespaces,
472+
userID: "user1",
473+
maxRules: 3,
474+
expectedGroups: 1,
475+
expectedRules: 2,
476+
expectedNextToken: GetRuleGroupNextToken("namespace2", "fail"),
477+
},
478+
{
479+
name: "only the rules matching the filters are counted",
480+
rules: mockRulesNamespaces,
481+
userID: "user1",
482+
maxRules: 3,
483+
queryParams: "?type=alert",
484+
expectedGroups: 2,
485+
expectedRules: 2,
486+
},
487+
{
488+
name: "paginating below the limit succeeds",
489+
rules: mockRulesNamespaces,
490+
userID: "user1",
491+
maxRules: 3,
492+
queryParams: "?group_limit=1",
493+
expectedGroups: 1,
494+
expectedRules: 2,
495+
expectedNextToken: GetRuleGroupNextToken("namespace2", "fail"),
496+
},
497+
{
498+
// A rule group is indivisible, so the response is allowed to exceed the
499+
// limit rather than return an unusable empty page. It is the only group, so
500+
// there is nothing left to page to and no token is returned.
501+
name: "a lone rule group over the limit is returned whole",
502+
rules: mockRules,
503+
userID: "user1",
504+
maxRules: 1,
505+
expectedGroups: 1,
506+
expectedRules: 2,
507+
},
508+
{
509+
name: "limit applies per request: tenant under the limit",
510+
rules: mockRules,
511+
userID: "user2",
512+
maxRules: 1,
513+
expectedGroups: 1,
514+
expectedRules: 1,
515+
},
516+
} {
517+
t.Run(tc.name, func(t *testing.T) {
518+
cfg := defaultRulerConfig(t)
519+
cfg.ListRulesMaxRules = tc.maxRules
520+
521+
r := newTestRuler(t, cfg, newMockRuleStore(tc.rules, nil), nil)
522+
defer services.StopAndAwaitTerminated(context.Background(), r) //nolint:errcheck
523+
524+
a := NewAPI(r, r.store, log.NewNopLogger())
525+
526+
req := requestFor(t, http.MethodGet, "https://localhost:8080/api/prom/api/v1/rules"+tc.queryParams, nil, tc.userID)
527+
w := httptest.NewRecorder()
528+
a.PrometheusRules(w, req)
529+
530+
resp := w.Result()
531+
body, err := io.ReadAll(resp.Body)
532+
require.NoError(t, err)
533+
534+
// util_api.Response holds Data as an any, so decode into a shape that
535+
// exposes the rule groups directly.
536+
parsed := struct {
537+
Status string `json:"status"`
538+
Data RuleDiscovery `json:"data"`
539+
ErrorType v1.ErrorType `json:"errorType"`
540+
Error string `json:"error"`
541+
}{}
542+
require.NoError(t, json.Unmarshal(body, &parsed))
543+
544+
require.Equal(t, http.StatusOK, resp.StatusCode)
545+
require.Equal(t, "success", parsed.Status)
546+
require.Empty(t, parsed.Error)
547+
require.Len(t, parsed.Data.RuleGroups, tc.expectedGroups)
548+
549+
rulesCount := 0
550+
for _, g := range parsed.Data.RuleGroups {
551+
rulesCount += len(g.Rules)
552+
}
553+
require.Equal(t, tc.expectedRules, rulesCount)
554+
require.Equal(t, tc.expectedNextToken, parsed.Data.GroupNextToken)
555+
})
556+
}
557+
}
558+
429559
func TestRuler_alerts(t *testing.T) {
430560
store := newMockRuleStore(mockRules, nil)
431561
cfg := defaultRulerConfig(t)

‎pkg/ruler/merger.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ import (
1010
// mergeGroupStateDesc removes duplicates from the provided []*GroupStateDesc by keeping the GroupStateDesc with the
1111
// latest information. It uses the EvaluationTimestamp of the GroupStateDesc and the EvaluationTimestamp of the
1212
// ActiveRules in a GroupStateDesc to determine the which GroupStateDesc has the latest information.
13-
// It also truncates rule groups if maxRuleGroups > 0
14-
func mergeGroupStateDesc(ruleResponses []*RulesResponse, maxRuleGroups int32, dedup bool) *RulesResponse {
13+
// It also truncates rule groups if maxRuleGroups > 0 or maxRules > 0
14+
func mergeGroupStateDesc(ruleResponses []*RulesResponse, maxRuleGroups int32, maxRules uint, dedup bool) *RulesResponse {
1515

1616
var groupsStateDescs []*GroupStateDesc
1717

@@ -44,10 +44,10 @@ func mergeGroupStateDesc(ruleResponses []*RulesResponse, maxRuleGroups int32, de
4444
groups = groupsStateDescs
4545
}
4646

47-
if maxRuleGroups > 0 {
47+
if maxRuleGroups > 0 || maxRules > 0 {
4848
//Need to sort here before we truncate
4949
sort.Sort(PaginatedGroupStates(groups))
50-
result, nextToken := generatePage(groups, int(maxRuleGroups))
50+
result, nextToken := generatePage(groups, int(maxRuleGroups), maxRules)
5151
return &RulesResponse{
5252
Groups: result,
5353
NextToken: nextToken,

‎pkg/ruler/merger_test.go‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ func TestMergeGroupStateDesc(t *testing.T) {
7272
input []*RulesResponse
7373
expectedOutput *RulesResponse
7474
maxRuleGroups int32
75+
maxRules uint
7576
}
7677

7778
testCases := map[string]testCase{
@@ -189,20 +190,60 @@ func TestMergeGroupStateDesc(t *testing.T) {
189190
},
190191
maxRuleGroups: 1,
191192
},
193+
// gs1 (ns1/g1) sorts before gs2 (ns1/g2) in token order, and both hold two
194+
// active rules, so a maxRules of 2 keeps gs1 and pages at gs1.
195+
"maxRules truncates the merged page without maxRuleGroups": {
196+
input: []*RulesResponse{
197+
{
198+
Groups: []*GroupStateDesc{&gs1, &gs2},
199+
NextToken: "",
200+
},
201+
},
202+
expectedOutput: &RulesResponse{
203+
Groups: []*GroupStateDesc{&gs1},
204+
NextToken: GetRuleGroupNextToken(gs1.Group.Namespace, gs1.Group.Name),
205+
},
206+
maxRules: 2,
207+
},
208+
"maxRules leaves the merged page intact when the total fits": {
209+
input: []*RulesResponse{
210+
{
211+
Groups: []*GroupStateDesc{&gs1, &gs2},
212+
NextToken: "",
213+
},
214+
},
215+
expectedOutput: &RulesResponse{
216+
Groups: []*GroupStateDesc{&gs1, &gs2},
217+
NextToken: "",
218+
},
219+
maxRules: 4,
220+
},
221+
"both limits disabled returns everything untruncated": {
222+
input: []*RulesResponse{
223+
{
224+
Groups: []*GroupStateDesc{&gs1, &gs2},
225+
NextToken: "",
226+
},
227+
},
228+
expectedOutput: &RulesResponse{
229+
Groups: []*GroupStateDesc{&gs1, &gs2},
230+
NextToken: "",
231+
},
232+
},
192233
}
193234

194235
for name, tc := range testCases {
195236
t.Run(name, func(t *testing.T) {
196237

197-
out := mergeGroupStateDesc(tc.input, tc.maxRuleGroups, true)
238+
out := mergeGroupStateDesc(tc.input, tc.maxRuleGroups, tc.maxRules, true)
198239
slices.SortFunc(out.Groups, func(a, b *GroupStateDesc) int {
199240
fileCompare := strings.Compare(a.Group.Namespace, b.Group.Namespace)
200241
if fileCompare != 0 {
201242
return fileCompare
202243
}
203244
return strings.Compare(a.Group.Name, b.Group.Name)
204245
})
205-
require.Equal(t, int(tc.maxRuleGroups), len(out.Groups))
246+
require.Len(t, out.Groups, len(tc.expectedOutput.Groups))
206247
t.Log(tc.expectedOutput)
207248
t.Log(out)
208249
require.True(t, reflect.DeepEqual(tc.expectedOutput, out))

‎pkg/ruler/ruler.go‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,8 @@ type Config struct {
168168
EnabledTenants flagext.StringSliceCSV `yaml:"enabled_tenants"`
169169
DisabledTenants flagext.StringSliceCSV `yaml:"disabled_tenants"`
170170

171+
ListRulesMaxRules uint `yaml:"list_rules_max_rules"`
172+
171173
RingCheckPeriod time.Duration `yaml:"-"`
172174

173175
// Field will be populated during runtime.
@@ -268,6 +270,8 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
268270
f.Var(&cfg.EnabledTenants, "ruler.enabled-tenants", "Comma separated list of tenants whose rules this ruler can evaluate. If specified, only these tenants will be handled by ruler, otherwise this ruler can process rules from all tenants. Subject to sharding.")
269271
f.Var(&cfg.DisabledTenants, "ruler.disabled-tenants", "Comma separated list of tenants whose rules this ruler cannot evaluate. If specified, a ruler that would normally pick the specified tenant(s) for processing will ignore them instead. Subject to sharding.")
270272

273+
f.UintVar(&cfg.ListRulesMaxRules, "ruler.list-rules-max-rules", 0, "Maximum number of rules returned by the Prometheus ListRules API. If there are more rulegroups, the response will include a pagination token which can be used to fetch the next set. The API will always return at least one rulegroup, even if it contains more rules than the limit. Defaults to 0, which is unlimited")
274+
271275
f.BoolVar(&cfg.EnableQueryStats, "ruler.query-stats-enabled", false, "Report query statistics for ruler queries to complete as a per user metric and as an info level log message.")
272276
f.BoolVar(&cfg.DisableRuleGroupLabel, "ruler.disable-rule-group-label", false, "Disable the rule_group label on exported metrics")
273277

@@ -1192,14 +1196,14 @@ func (r *Ruler) filterBackupRuleGroups(userID string, ruleGroups []*rulespb.Rule
11921196

11931197
// GetRules retrieves the running rules from this ruler and all running rulers in the ring if
11941198
// sharding is enabled
1195-
func (r *Ruler) GetRules(ctx context.Context, rulesRequest RulesRequest) (*RulesResponse, error) {
1199+
func (r *Ruler) GetRules(ctx context.Context, rulesRequest RulesRequest, maxRules uint) (*RulesResponse, error) {
11961200
userID, err := users.TenantID(ctx)
11971201
if err != nil {
11981202
return nil, fmt.Errorf("no user id found in context")
11991203
}
12001204

12011205
if r.cfg.EnableSharding {
1202-
resp, err := r.getShardedRules(ctx, userID, rulesRequest)
1206+
resp, err := r.getShardedRules(ctx, userID, rulesRequest, maxRules)
12031207
if resp == nil {
12041208
return &RulesResponse{
12051209
Groups: make([]*GroupStateDesc, 0),
@@ -1209,11 +1213,11 @@ func (r *Ruler) GetRules(ctx context.Context, rulesRequest RulesRequest) (*Rules
12091213
return resp, err
12101214
}
12111215

1212-
response, err := r.getLocalRules(userID, rulesRequest, false)
1216+
response, err := r.getLocalRules(userID, rulesRequest, maxRules, false)
12131217
return &response, err
12141218
}
12151219

1216-
func (r *Ruler) getLocalRules(userID string, rulesRequest RulesRequest, includeBackups bool) (RulesResponse, error) {
1220+
func (r *Ruler) getLocalRules(userID string, rulesRequest RulesRequest, maxRules uint, includeBackups bool) (RulesResponse, error) {
12171221
groups := r.manager.GetRules(userID)
12181222

12191223
groupDescs := make([]*GroupStateDesc, 0, len(groups))
@@ -1375,7 +1379,7 @@ func (r *Ruler) getLocalRules(userID string, rulesRequest RulesRequest, includeB
13751379
combinedRuleStateDescs = append(combinedRuleStateDescs, backupGroupDescs...)
13761380
}
13771381

1378-
if rulesRequest.MaxRuleGroups <= 0 {
1382+
if rulesRequest.MaxRuleGroups <= 0 && maxRules == 0 {
13791383
return RulesResponse{
13801384
Groups: combinedRuleStateDescs,
13811385
NextToken: "",
@@ -1398,7 +1402,7 @@ func (r *Ruler) getLocalRules(userID string, rulesRequest RulesRequest, includeB
13981402
}
13991403
}
14001404

1401-
resultingGroupDescs, nextToken := generatePage(resultingGroupDescs, int(rulesRequest.MaxRuleGroups))
1405+
resultingGroupDescs, nextToken := generatePage(resultingGroupDescs, int(rulesRequest.MaxRuleGroups), maxRules)
14021406
return RulesResponse{
14031407
Groups: resultingGroupDescs,
14041408
NextToken: nextToken,
@@ -1519,7 +1523,7 @@ func (r *Ruler) getShardSizeForUser(userID string) int {
15191523
return max(newShardSize, r.cfg.Ring.ReplicationFactor)
15201524
}
15211525

1522-
func (r *Ruler) getShardedRules(ctx context.Context, userID string, rulesRequest RulesRequest) (*RulesResponse, error) {
1526+
func (r *Ruler) getShardedRules(ctx context.Context, userID string, rulesRequest RulesRequest, maxRules uint) (*RulesResponse, error) {
15231527
ring := ring.ReadRing(r.ring)
15241528

15251529
if shardSize := r.limits.RulerTenantShardSize(userID); shardSize > 0 && r.cfg.ShardingStrategy == util.ShardingStrategyShuffle {
@@ -1598,17 +1602,15 @@ func (r *Ruler) getShardedRules(ctx context.Context, userID string, rulesRequest
15981602
return nil
15991603
})
16001604

1601-
if err == nil {
1602-
if r.cfg.RulesBackupEnabled() || r.cfg.APIDeduplicateRules {
1603-
return mergeGroupStateDesc(merged, rulesRequest.MaxRuleGroups, true), nil
1604-
}
1605-
return mergeGroupStateDesc(merged, rulesRequest.MaxRuleGroups, false), nil
1605+
if err != nil {
1606+
return &RulesResponse{
1607+
Groups: make([]*GroupStateDesc, 0),
1608+
NextToken: "",
1609+
}, err
16061610
}
16071611

1608-
return &RulesResponse{
1609-
Groups: make([]*GroupStateDesc, 0),
1610-
NextToken: "",
1611-
}, err
1612+
backup := r.cfg.RulesBackupEnabled() || r.cfg.APIDeduplicateRules
1613+
return mergeGroupStateDesc(merged, rulesRequest.MaxRuleGroups, maxRules, backup), nil
16121614
}
16131615

16141616
// Rules implements the rules service
@@ -1619,7 +1621,7 @@ func (r *Ruler) Rules(ctx context.Context, in *RulesRequest) (*RulesResponse, er
16191621
return nil, fmt.Errorf("no user id found in context")
16201622
}
16211623

1622-
response, err := r.getLocalRules(userID, *in, r.cfg.RulesBackupEnabled())
1624+
response, err := r.getLocalRules(userID, *in, 0, r.cfg.RulesBackupEnabled())
16231625
if err != nil {
16241626
return nil, err
16251627
}

0 commit comments

Comments
 (0)