Skip to content

Query priority is ignored when the query-frontend uses a query-scheduler #7949

Open

Description

@sandy2008

AI Tool Usage Notice
If you used an AI tool to help draft this issue,
please make sure you have reviewed and validated all content before submitting.
You are responsible for the accuracy and quality of everything in this report.
Low-quality or unreviewed AI-generated submissions may be closed without further investigation.
See our Generative AI Contribution Policy for details.

Describe the bug
When the query-frontend uses a query-scheduler (-frontend.scheduler-address), query_priority has no effect on how queries are queued. The query-frontend still assigns the priority, and its query stats log line shows priority=100, but the query-scheduler enqueues every request at priority 0. So:

  • a higher-priority query is not dequeued ahead of the tenant's other queries;
  • queriers reserved with reserved_queriers never receive any of the tenant's queries, because none of them reaches the reserved priority level. They sit idle for that tenant, and high-priority queries wait for the other queriers like everything else;
  • cortex_query_scheduler_queue_length and cortex_request_queue_requests_total only ever have priority="0" series.

With the same limits and no scheduler (frontend v1), priorities are applied, as long as query stats are enabled (see Additional Context).

The tripperware stores the priority in the query stats in the request context (query_attribute_matcher.go#L50-L60). Frontend v1 keeps that context with the queued request and reads the priority from it (v1/frontend.go#L98-L105). Frontend v2 sends the scheduler only the httpgrpc request, the user ID, the query ID, its own address and statsEnabled (frontend_scheduler_worker.go#L256-L264). FrontendToScheduler has no priority field (scheduler.proto#L80-L94), and no header carries it either. The scheduler's schedulerRequest.Priority() still reads stats.FromContext(s.ctx) (scheduler.go#L208-L215). But s.ctx is derived from the context.Background() that the scheduler creates for each connected frontend, plus a cancel func and the queued span (scheduler.go#L318-L328, scheduler.go#L393-L427). That context never holds query stats, so LoadPriority() returns (0, false) for every request. A querier reserved for priority 100 then refuses all of the tenant's requests, because dequeueRequest returns nil whenever the head of the queue is below the querier's minimum priority (queue.go#L156-L164, user_request_queue.go#L63-L66).

The scheduler started reading the priority from the context in #5758, when it moved from an X-Cortex-Query-Priority request header into the query stats. #5605 and #5758 both shipped in v1.17.0, and the relevant code is the same in every release up to v1.21.1. The CHANGELOG entries for both PRs say "Query Frontend/Scheduler" (CHANGELOG.md#L547, #L564). Neither the query_priority config reference nor the query priority blog post says that a scheduler isn't supported.

To Reproduce
Steps to reproduce the behavior:

  1. Start Cortex (SHA or version): master at 19336a5. Run a query-frontend with -frontend.scheduler-address and -frontend.query-stats-enabled=true, a query-scheduler, two queriers (-querier.id=querier-1 and -querier.id=querier-2, each with -querier.worker-parallelism=1), and these limits for the tenant:
    max_queriers_per_tenant: 2
    query_priority:
      enabled: true
      priorities:
        - priority: 100
          reserved_queriers: 1
          query_attributes:
            - regex: ".*alert.*"
  2. Perform Operations(Read/Write/Others): Read. While a slow query keeps querier-2 busy, send sum(rate(alertmanager_notifications_total[5m])). The query-frontend logs it with priority=100 and the scheduler counts it under priority="0". querier-1, the querier reserved for priority 100, never gets it, and the query runs on querier-2 after the slow query finishes. Without -frontend.scheduler-address, the query runs on querier-1 straight away.

I reproduced this in-process with the test below, not on a deployment. The test wires the real query-frontend handler and tripperware the same way pkg/cortex/modules.go does, plus frontend v1 or v2, a query-scheduler on a localhost gRPC listener, and two querier workers. A slow query keeps querier-2 busy for 1s while the priority-100 query is sent:

=== RUN   TestQueryPriorityWithScheduler/scheduler=false,query-stats=true
    priority-100 query: served by querier-1 after 1ms; query-frontend log: "priority=100"
    cortex_query_frontend_queue_length{priority="0",type="priority",user="team-a"} 0
    cortex_query_frontend_queue_length{priority="100",type="priority",user="team-a"} 0
    cortex_request_queue_requests_total{priority="0",user="team-a"} 1
    cortex_request_queue_requests_total{priority="100",user="team-a"} 1
=== RUN   TestQueryPriorityWithScheduler/scheduler=true,query-stats=true
    priority-100 query: served by querier-2 after 1.007s; query-frontend log: "priority=100"
    cortex_query_scheduler_queue_length{priority="0",type="priority",user="team-a"} 0
    cortex_request_queue_requests_total{priority="0",user="team-a"} 2
=== RUN   TestQueryPriorityWithScheduler/scheduler=false,query-stats=false
    priority-100 query: served by querier-2 after 1.003s; query-frontend log: ""
    cortex_query_frontend_queue_length{priority="0",type="priority",user="team-a"} 0
    cortex_request_queue_requests_total{priority="0",user="team-a"} 2

Five runs with -race gave the same result. In a variant with one busy querier, I queued a normal query and then a priority-100 query behind it. Frontend v1 dispatched the priority-100 query first, and the scheduler dispatched the normal query first.

Test (pkg/frontend, external test package)
package frontend_test

import (
	"bytes"
	"context"
	"fmt"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/go-kit/log"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/stretchr/testify/require"
	"github.com/thanos-io/thanos/pkg/querysharding"
	httpgrpc_server "github.com/weaveworks/common/httpgrpc/server"
	"github.com/weaveworks/common/middleware"
	"google.golang.org/grpc"
	"gopkg.in/yaml.v2"

	"github.com/cortexproject/cortex/pkg/frontend"
	"github.com/cortexproject/cortex/pkg/frontend/transport"
	"github.com/cortexproject/cortex/pkg/frontend/v1/frontendv1pb"
	"github.com/cortexproject/cortex/pkg/frontend/v2/frontendv2pb"
	"github.com/cortexproject/cortex/pkg/querier/tenantfederation"
	"github.com/cortexproject/cortex/pkg/querier/tripperware"
	"github.com/cortexproject/cortex/pkg/querier/tripperware/instantquery"
	"github.com/cortexproject/cortex/pkg/querier/tripperware/queryrange"
	querier_worker "github.com/cortexproject/cortex/pkg/querier/worker"
	"github.com/cortexproject/cortex/pkg/scheduler"
	"github.com/cortexproject/cortex/pkg/scheduler/schedulerpb"
	"github.com/cortexproject/cortex/pkg/util/fakeauth"
	"github.com/cortexproject/cortex/pkg/util/flagext"
	"github.com/cortexproject/cortex/pkg/util/services"
	"github.com/cortexproject/cortex/pkg/util/validation"
)

const tenantLimits = `
max_queriers_per_tenant: 2
query_priority:
  enabled: true
  priorities:
    - priority: 100
      reserved_queriers: 1
      query_attributes:
        - regex: ".*alert.*"
`

const (
	slowQuery  = `sum(rate(http_requests_total[5m]))`
	alertQuery = `sum(rate(alertmanager_notifications_total[5m]))`
)

type syncBuf struct {
	mu sync.Mutex
	b  bytes.Buffer
}

func (s *syncBuf) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) }

func TestQueryPriorityWithScheduler(t *testing.T) {
	for _, c := range []struct{ scheduler, queryStats bool }{{false, true}, {true, true}, {false, false}} {
		t.Run(fmt.Sprintf("scheduler=%v,query-stats=%v", c.scheduler, c.queryStats), func(t *testing.T) {
			ctx := context.Background()
			reg := prometheus.NewRegistry()
			var l validation.Limits
			flagext.DefaultValues(&l)
			require.NoError(t, yaml.Unmarshal([]byte(tenantLimits), &l))
			limits := validation.NewOverrides(l, nil)

			var cfg frontend.CombinedFrontendConfig
			flagext.DefaultValues(&cfg)
			cfg.Handler.QueryStatsEnabled = c.queryStats

			// query-frontend gRPC server (queriers pull from it with v1, send results to it with v2)
			feLis, err := net.Listen("tcp", "127.0.0.1:0")
			require.NoError(t, err)
			feSrv := grpc.NewServer(grpc.UnaryInterceptor(fakeauth.ServerUserHeaderInterceptor))
			t.Cleanup(feSrv.Stop)
			queueAddr := feLis.Addr().String()
			if c.scheduler {
				var sCfg scheduler.Config
				flagext.DefaultValues(&sCfg)
				s, err := scheduler.NewScheduler(sCfg, limits, nil, log.NewNopLogger(), reg, false)
				require.NoError(t, err)
				sLis, err := net.Listen("tcp", "127.0.0.1:0")
				require.NoError(t, err)
				sSrv := grpc.NewServer()
				schedulerpb.RegisterSchedulerForFrontendServer(sSrv, s)
				schedulerpb.RegisterSchedulerForQuerierServer(sSrv, s)
				require.NoError(t, services.StartAndAwaitRunning(ctx, s))
				go func() { _ = sSrv.Serve(sLis) }()
				t.Cleanup(func() { sSrv.Stop(); _ = services.StopAndAwaitTerminated(ctx, s) })
				queueAddr = sLis.Addr().String()
				host, port, _ := net.SplitHostPort(feLis.Addr().String())
				cfg.FrontendV2.SchedulerAddress, cfg.FrontendV2.Addr = queueAddr, host
				cfg.FrontendV2.Port, _ = strconv.Atoi(port)
			}
			rt, v1, v2, err := frontend.InitFrontend(cfg, limits, nil, 0, log.NewNopLogger(), reg, transport.NewRetry(0, nil))
			require.NoError(t, err)
			var fe services.Service = v1
			if v1 != nil {
				frontendv1pb.RegisterFrontendServer(feSrv, v1)
			} else {
				frontendv2pb.RegisterFrontendForQuerierServer(feSrv, v2)
				fe = v2
			}
			require.NoError(t, services.StartAndAwaitRunning(ctx, fe))
			t.Cleanup(func() { _ = services.StopAndAwaitTerminated(ctx, fe) })
			go func() { _ = feSrv.Serve(feLis) }()

			// handler -> tripperware -> frontend, wired like pkg/cortex/modules.go
			promCodec, shardedCodec := queryrange.NewPrometheusCodec(false, "", "json"), queryrange.NewPrometheusCodec(true, "", "json")
			instantCodec := instantquery.NewInstantQueryCodec("", "json")
			analyzer := querysharding.NewQueryAnalyzer()
			var qrCfg queryrange.Config
			flagext.DefaultValues(&qrCfg)
			rangeMW, _, err := queryrange.Middlewares(qrCfg, log.NewNopLogger(), limits, queryrange.PrometheusResponseExtractor{}, reg, analyzer, promCodec, shardedCodec, 5*time.Minute, time.Minute, false, nil, nil)
			require.NoError(t, err)
			instantMW, err := instantquery.Middlewares(log.NewNopLogger(), limits, instantCodec, analyzer, 5*time.Minute, time.Minute, false, nil)
			require.NoError(t, err)
			tw := tripperware.NewQueryTripperware(log.NewNopLogger(), reg, nil, rangeMW, instantMW, promCodec, instantCodec, limits, analyzer, time.Minute, 0, 5*time.Minute)
			logs := &syncBuf{}
			handler := middleware.AuthenticateUser.Wrap(transport.NewHandler(cfg.Handler, tenantfederation.Config{}, nil, tw(rt), log.NewLogfmtLogger(logs), reg))

			// Two queriers, one stream each. querier-1 is the one reserved for priority >= 100.
			var mu sync.Mutex
			servedBy := map[string]string{}
			started, release := make(chan string, 4), make(chan struct{})
			for _, id := range []string{"querier-1", "querier-2"} {
				var wCfg querier_worker.Config
				flagext.DefaultValues(&wCfg)
				wCfg.QuerierID, wCfg.Parallelism, wCfg.MaxConcurrentRequests, wCfg.InstanceAddr = id, 1, 1, "127.0.0.1"
				if c.scheduler {
					wCfg.SchedulerAddress = queueAddr
				} else {
					wCfg.FrontendAddress = queueAddr
				}
				w, err := querier_worker.NewQuerierWorker(wCfg, httpgrpc_server.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					_ = r.ParseForm()
					mu.Lock()
					servedBy[r.Form.Get("query")] = id
					mu.Unlock()
					started <- r.Form.Get("query")
					if r.Form.Get("query") == slowQuery {
						<-release
					}
					w.Header().Set("Content-Type", "application/json")
					_, _ = w.Write([]byte(`{"status":"success","data":{"resultType":"vector","result":[]}}`))
				})), log.NewNopLogger(), nil)
				require.NoError(t, err)
				require.NoError(t, services.StartAndAwaitRunning(ctx, w))
				t.Cleanup(func() { _ = services.StopAndAwaitTerminated(ctx, w) })
			}
			connected := map[bool]string{false: "cortex_query_frontend_connected_clients", true: "cortex_query_scheduler_connected_querier_clients"}[c.scheduler]
			require.Eventually(t, func() bool { return strings.Contains(gather(t, reg, connected), "} 2") }, 5*time.Second, 5*time.Millisecond)

			type result struct {
				code int
				took time.Duration
			}
			query := func(q string) <-chan result {
				done := make(chan result, 1)
				go func() {
					req := httptest.NewRequest("GET", "/prometheus/api/v1/query?"+url.Values{"query": {q}}.Encode(), nil)
					req.Header.Set("X-Scope-OrgID", "team-a")
					start, rec := time.Now(), httptest.NewRecorder()
					handler.ServeHTTP(rec, req)
					done <- result{rec.Code, time.Since(start)}
				}()
				return done
			}
			slowDone := query(slowQuery) // a slow priority-0 query keeps querier-2 busy for 1s
			require.Equal(t, slowQuery, <-started)
			alertDone := query(alertQuery)
			time.AfterFunc(time.Second, func() { close(release) })
			alert, slow := <-alertDone, <-slowDone
			require.Equal(t, 200, alert.code)
			require.Equal(t, 200, slow.code)

			queue := map[bool]string{false: "cortex_query_frontend_queue_length", true: "cortex_query_scheduler_queue_length"}[c.scheduler]
			logs.mu.Lock()
			prio := regexp.MustCompile(`priority=\S+(?: \S+)* param_query=sum\(rate\(alertmanager`).FindString(logs.b.String())
			logs.mu.Unlock()
			prio, _, _ = strings.Cut(prio, " ")
			mu.Lock()
			defer mu.Unlock()
			t.Logf("priority-100 query: served by %s after %v; query-frontend log: %q\n%s", servedBy[alertQuery], alert.took.Round(time.Millisecond), prio,
				gather(t, reg, "cortex_request_queue_requests_total", queue))
		})
	}
}

func gather(t *testing.T, reg *prometheus.Registry, names ...string) string {
	mfs, err := reg.Gather()
	require.NoError(t, err)
	var out []string
	for _, mf := range mfs {
		for _, name := range names {
			if mf.GetName() != name {
				continue
			}
			for _, m := range mf.GetMetric() {
				var lbls []string
				for _, lp := range m.GetLabel() {
					lbls = append(lbls, fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()))
				}
				out = append(out, fmt.Sprintf("%s{%s} %g", name, strings.Join(lbls, ","), m.GetGauge().GetValue()+m.GetCounter().GetValue()))
			}
		}
	}
	return strings.Join(out, "\n")
}

Expected behavior
The query-scheduler queues each request at the priority the query-frontend assigned, as frontend v1 does, so that priority ordering and reserved_queriers also work with a scheduler. One way would be a priority field on FrontendToScheduler, filled in by frontend v2 from the request context and used by schedulerRequest.Priority(). Another would be for the scheduler to put the received priority into the context it builds for the request. If query priority isn't meant to work with a scheduler, the query_priority docs should say so.

Environment:

  • Infrastructure: laptop (in-process test against master)
  • Deployment tool: none

Additional Context
The third case shows a related problem that also affects frontend v1. The priority is only assigned when -frontend.query-stats-enabled=true, because it's stored in the query stats object, and the handler only creates that object when query stats are enabled (handler.go#L273-L283). With query stats disabled, every query is queued at priority 0 even without a scheduler. This isn't documented and isn't checked at startup (timeout classification, which has the same dependency, is checked: cortex.go#L330-L332). A scheduler fix that takes the priority from the same stats object would have the same dependency.

The repro sets max_queriers_per_tenant because reserved queriers are only picked inside the tenant's querier shard. getPriorityList gets the shard size, which is 0 without shuffle sharding, so no querier is reserved at all (queue.go#L99-L100, user_queues.go#L389-L409). The same happens with frontend v1.

#7942 (open) changes the priority that the query-frontend assigns to metadata queries. With a scheduler, that value doesn't reach the queue either.

This issue was drafted with AI assistance, and the evidence was reproduced against master at 19336a5.

Activity

  1. perfogic commented on Nov 30, 2026

    @perfogic

    interested, can i take this ?

  2. perfogic commented on Nov 30, 2026

    @perfogic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions