From a5f86c3fb6c394ba1c3e4d9934e4af5601ba33a4 Mon Sep 17 00:00:00 2001 From: Arve Knudsen Date: Tue, 27 Jan 2026 10:02:16 +0100 Subject: [PATCH] cmd/prometheus: fix flaky TestQueryLog race condition (#17933) Add waitForQueryLog helper that polls for query log entries to appear before asserting, rather than reading the file immediately after making a query. This fixes a race condition where the query log wasn't flushed to disk before the test read the file. The helper uses a 5 second timeout with 100ms polling intervals, which is generous enough to handle slow CI environments while keeping the test responsive. Signed-off-by: Arve Knudsen --- cmd/prometheus/query_log_test.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/cmd/prometheus/query_log_test.go b/cmd/prometheus/query_log_test.go index 5e5a9ac3b7..e410f836a9 100644 --- a/cmd/prometheus/query_log_test.go +++ b/cmd/prometheus/query_log_test.go @@ -334,7 +334,8 @@ func (p *queryLogTest) run(t *testing.T) { p.query(t) - ql := readQueryLog(t, queryLogFile.Name()) + // Wait for query log entry to be written (avoid race with file I/O). + ql := waitForQueryLog(t, queryLogFile.Name(), 1) qc := len(ql) if p.exactQueryCount() { require.Equal(t, 1, qc) @@ -361,7 +362,8 @@ func (p *queryLogTest) run(t *testing.T) { p.query(t) qc++ - ql = readQueryLog(t, queryLogFile.Name()) + // Wait for query log entry to be written (avoid race with file I/O). + ql = waitForQueryLog(t, queryLogFile.Name(), qc) if p.exactQueryCount() { require.Len(t, ql, qc) } else { @@ -392,7 +394,8 @@ func (p *queryLogTest) run(t *testing.T) { qc++ - ql = readQueryLog(t, newFile.Name()) + // Wait for query log entry to be written (avoid race with file I/O). + ql = waitForQueryLog(t, newFile.Name(), qc) if p.exactQueryCount() { require.Len(t, ql, qc) } else { @@ -404,7 +407,8 @@ func (p *queryLogTest) run(t *testing.T) { p.query(t) - ql = readQueryLog(t, queryLogFile.Name()) + // Wait for query log entry to be written (avoid race with file I/O). + ql = waitForQueryLog(t, queryLogFile.Name(), 1) qc = len(ql) if p.exactQueryCount() { require.Equal(t, 1, qc) @@ -446,6 +450,18 @@ func readQueryLog(t *testing.T, path string) []queryLogLine { return ql } +// waitForQueryLog waits for the query log to contain at least minEntries entries, +// polling at regular intervals until the timeout is reached. +func waitForQueryLog(t *testing.T, path string, minEntries int) []queryLogLine { + t.Helper() + var ql []queryLogLine + require.Eventually(t, func() bool { + ql = readQueryLog(t, path) + return len(ql) >= minEntries + }, 5*time.Second, 100*time.Millisecond, "timed out waiting for query log to have at least %d entries, got %d", minEntries, len(ql)) + return ql +} + func TestQueryLog(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.")