Compare commits

..

8 Commits

Author SHA1 Message Date
Naman Verma
105f023f32 Merge branch 'main' into nv/exec-stats 2026-11-23 10:11:50 +05:30
Naman Verma
8101a79371 Merge branch 'main' into nv/exec-stats 2026-11-16 10:43:03 +05:30
Naman Verma
62d477e920 Merge branch 'main' into nv/exec-stats 2026-11-09 12:20:27 +05:30
Naman Verma
fe45b9dcae Merge branch 'main' into nv/exec-stats 2026-11-06 00:51:46 +05:30
Naman Verma
63ee60a40c fix(querier): stop cache refreshes from inflating exec stats 2026-11-06 00:51:03 +05:30
Naman Verma
29a393e47e Merge branch 'main' into nv/exec-stats 2026-11-05 10:51:11 +05:30
Naman Verma
c58f76f998 Merge branch 'main' into nv/exec-stats 2026-11-03 11:34:10 +05:30
Naman Verma
e39ad9e221 test: check how exec stats fail 2026-11-02 22:24:22 +05:30
26 changed files with 190 additions and 935 deletions

View File

@@ -11651,11 +11651,8 @@ components:
panelType:
allOf:
- $ref: '#/components/schemas/RuletypesPanelType'
description: 'How the queries are evaluated. graph runs them as time series
and matchType decides which points must satisfy op. table and value run
them as scalar: one value per group over the whole evaluation window,
compared directly, so matchType has no effect and metric aggregations
need reduceTo. promql queries and anomaly_rule support graph only.'
description: 'The panel the UI renders the queries with: graph, table or
value. Use graph for alerts.'
queries:
description: 'The queries to evaluate, at least one. Every envelope type
must match queryType: builder_query and builder_formula for builder, promql

View File

@@ -12787,7 +12787,7 @@ export enum RuletypesQueryTypeDTO {
}
export interface RuletypesAlertCompositeQueryDTO {
/**
* @description How the queries are evaluated. graph runs them as time series and matchType decides which points must satisfy op. table and value run them as scalar: one value per group over the whole evaluation window, compared directly, so matchType has no effect and metric aggregations need reduceTo. promql queries and anomaly_rule support graph only.
* @description The panel the UI renders the queries with: graph, table or value. Use graph for alerts.
*/
panelType: RuletypesPanelTypeDTO;
/**

View File

@@ -26,8 +26,9 @@ const bucketCacheCellSteps = 60
type BucketCache interface {
// cached portion + list of gaps to fetch
GetMissRanges(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step) (cached *qbtypes.Result, missing []*qbtypes.TimeRange)
// store fresh buckets for future hits
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result)
// store fresh buckets for future hits; only the ranges in the map were
// queried for fresh, the rest of it came from the cache
Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats)
}
// bucketCache implements the BucketCache interface.
@@ -116,7 +117,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Merge buckets into a single result
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings)
mergedResult := bc.mergeBuckets(ctx, relevantBuckets, cachedWarnings, startMs, endMs)
// Filter the merged result to only include values within the requested time range
mergedResult = bc.filterResultToTimeRange(mergedResult, q, startMs, endMs, stepMs)
@@ -125,7 +126,7 @@ func (bc *bucketCache) GetMissRanges(
}
// Put stores fresh query results in the cache.
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result) {
func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Query, step qbtypes.Step, fresh *qbtypes.Result, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) {
// Get query window
startMs, endMs := q.Window()
@@ -188,7 +189,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
// Convert trimmed result to buckets, one per grid cell it spans
cellWidthMs := bucketCacheCellSteps * stepMs
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs)
freshBuckets := bc.resultToBuckets(ctx, trimmedResult, cachableStartMs, cachableEndMs, cellWidthMs, execStatsForQueriedTimeRanges)
cellKeys := make([]string, len(freshBuckets))
cellEntries := make([]cachetypes.Cacheable, len(freshBuckets))
@@ -210,7 +211,7 @@ func (bc *bucketCache) Put(ctx context.Context, orgID valuer.UUID, q qbtypes.Que
cellEntry = cellEntries[i].(*qbtypes.CachedData)
}
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket)
cellBuckets, changed := bc.mergeFreshBucketIntoCell(ctx, cellEntry.Buckets, freshBucket, execStatsForQueriedTimeRanges)
if !changed {
continue
}
@@ -463,7 +464,7 @@ func (bc *bucketCache) filterRelevantBuckets(buckets []*qbtypes.CachedBucket, st
}
// mergeBuckets combines multiple cached buckets into a single result.
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string) *qbtypes.Result {
func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.CachedBucket, warnings []string, startMs, endMs uint64) *qbtypes.Result {
if len(buckets) == 0 {
return &qbtypes.Result{}
}
@@ -471,12 +472,13 @@ func (bc *bucketCache) mergeBuckets(ctx context.Context, buckets []*qbtypes.Cach
// All buckets should have the same type
resultType := buckets[0].Type
// Aggregate stats
// A bucket can reach past the window; only the part inside it is served
var totalStats qbtypes.ExecStats
for _, bucket := range buckets {
totalStats.RowsScanned += bucket.Stats.RowsScanned
totalStats.BytesScanned += bucket.Stats.BytesScanned
totalStats.DurationMS += bucket.Stats.DurationMS
servedStats := bucket.ProrateStatsToWindow(startMs, endMs)
totalStats.RowsScanned += servedStats.RowsScanned
totalStats.BytesScanned += servedStats.BytesScanned
totalStats.DurationMS += servedStats.DurationMS
}
// Merge values based on type
@@ -673,7 +675,7 @@ func (bc *bucketCache) isEmptyResult(result *qbtypes.Result) (isEmpty bool, isFi
}
// resultToBuckets converts a query result into time-based buckets.
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64) []*qbtypes.CachedBucket {
func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Result, startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) []*qbtypes.CachedBucket {
// Check if result is empty
isEmpty, isFiltered := bc.isEmptyResult(result)
@@ -685,7 +687,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
}
// Empty filtered results still become buckets, so the range is not re-queried
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs)
perCellBuckets, err := result.SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs, execStatsForQueriedTimeRanges)
if err != nil {
bc.logger.ErrorContext(ctx, "failed to convert result to buckets", errors.Attr(err))
return nil
@@ -697,7 +699,7 @@ func (bc *bucketCache) resultToBuckets(ctx context.Context, result *qbtypes.Resu
// and reports whether the cell changed: a bucket already covering the fresh
// one leaves it as is, buckets inside the fresh one are replaced, buckets
// overlapping or edge to edge with it are unioned, and the rest are kept apart.
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket) ([]*qbtypes.CachedBucket, bool) {
func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets []*qbtypes.CachedBucket, freshBucket *qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) ([]*qbtypes.CachedBucket, bool) {
keptBuckets := make([]*qbtypes.CachedBucket, 0, len(cellBuckets)+1)
touchingBuckets := []*qbtypes.CachedBucket{}
for _, cellBucket := range cellBuckets {
@@ -710,7 +712,7 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
keptBuckets = append(keptBuckets, cellBucket)
}
}
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets))
keptBuckets = append(keptBuckets, bc.unionBuckets(ctx, freshBucket, touchingBuckets, execStatsForQueriedTimeRanges))
slices.SortFunc(keptBuckets, func(a, b *qbtypes.CachedBucket) int {
return cmp.Compare(a.StartMs, b.StartMs)
@@ -721,7 +723,16 @@ func (bc *bucketCache) mergeFreshBucketIntoCell(ctx context.Context, cellBuckets
// unionBuckets widens the fresh bucket by the buckets it touches. Buckets
// inside it are replaced outright, so only a genuine partial overlap decodes
// anything.
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket) *qbtypes.CachedBucket {
func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.CachedBucket, touchingBuckets []*qbtypes.CachedBucket, execStatsForQueriedTimeRanges map[qbtypes.TimeRange]qbtypes.ExecStats) *qbtypes.CachedBucket {
// Data queried again takes the new query's cost, which the fresh bucket
// carries; a touching bucket keeps its cost only for what was not queried again
for _, touchingBucket := range touchingBuckets {
keptStats := touchingBucket.ProrateStatsToUnqueried(execStatsForQueriedTimeRanges)
freshBucket.Stats.RowsScanned += keptStats.RowsScanned
freshBucket.Stats.BytesScanned += keptStats.BytesScanned
freshBucket.Stats.DurationMS += keptStats.DurationMS
}
bucketsToMerge := []*qbtypes.CachedBucket{freshBucket}
for _, touchingBucket := range touchingBuckets {
if !freshBucket.Contains(touchingBucket) {
@@ -742,14 +753,11 @@ func (bc *bucketCache) unionBuckets(ctx context.Context, freshBucket *qbtypes.Ca
EndMs: freshBucket.EndMs,
Type: freshBucket.Type,
Value: value,
Stats: qbtypes.ExecStats{StepIntervals: freshBucket.Stats.StepIntervals},
Stats: freshBucket.Stats,
}
for _, mergedBucket := range bucketsToMerge {
unionBucket.StartMs = min(unionBucket.StartMs, mergedBucket.StartMs)
unionBucket.EndMs = max(unionBucket.EndMs, mergedBucket.EndMs)
unionBucket.Stats.RowsScanned += mergedBucket.Stats.RowsScanned
unionBucket.Stats.BytesScanned += mergedBucket.Stats.BytesScanned
unionBucket.Stats.DurationMS += mergedBucket.Stats.DurationMS
}
return unionBucket
}

View File

@@ -30,7 +30,7 @@ func BenchmarkBucketCache_GetMissRanges(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
}
// Create test queries with varying cache hit patterns
@@ -121,7 +121,7 @@ func BenchmarkBucketCache_Put(b *testing.B) {
for i := 0; i < b.N; i++ {
for j := 0; j < tc.numQueries; j++ {
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j])
bc.Put(ctx, orgID, queries[j], qbtypes.Step{Duration: 1000 * time.Millisecond}, results[j], map[qbtypes.TimeRange]qbtypes.ExecStats{{From: queries[j].startMs, To: queries[j].endMs}: results[j].Stats})
}
}
})
@@ -259,7 +259,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
}
b.ResetTimer()
@@ -284,7 +284,7 @@ func BenchmarkBucketCache_ConcurrentOperations(b *testing.B) {
endMs: uint64((i + 1) * 10000),
}
result := createBenchmarkResult(query.startMs, query.endMs, 1000)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
case 2: // Partial read
query := &mockQuery{
fingerprint: fmt.Sprintf("concurrent-query-%d", i%100),

View File

@@ -59,7 +59,7 @@ func TestBucketCacheStepAlignment(t *testing.T) {
}
// Put result in cache
bc.Put(ctx, orgID, query, step, result)
bc.Put(ctx, orgID, query, step, result, nil)
// Get cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
@@ -109,7 +109,7 @@ func TestBucketCacheNoStepInterval(t *testing.T) {
}
// Should cache the entire range when step is 0
bc.Put(ctx, orgID, query, step, result)
bc.Put(ctx, orgID, query, step, result, nil)
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
assert.NotNil(t, cached)

View File

@@ -156,7 +156,7 @@ func TestBucketCache_Put_And_Get(t *testing.T) {
}
// Store in cache
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
// Wait a bit for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -189,7 +189,7 @@ func TestBucketCache_PartialHit(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 3000, 1000),
}
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
// Wait for cache write
time.Sleep(10 * time.Millisecond)
@@ -225,7 +225,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
bc.Put(context.Background(), valuer.UUID{}, query1, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 2000, 100),
})
}, nil)
query2 := &mockQuery{
fingerprint: "test-query",
@@ -235,7 +235,7 @@ func TestBucketCache_MultipleBuckets(t *testing.T) {
bc.Put(context.Background(), valuer.UUID{}, query2, qbtypes.Step{Duration: 100 * time.Millisecond}, &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 3000, 4000, 100),
})
}, nil)
// Wait for cache writes
time.Sleep(10 * time.Millisecond)
@@ -280,7 +280,7 @@ func TestBucketCache_FluxInterval(t *testing.T) {
}
// This should not be cached due to flux interval
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// Wait a bit
time.Sleep(10 * time.Millisecond)
@@ -358,7 +358,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
{Series: []*qbtypes.TimeSeries{series1}},
},
},
})
}, nil)
// Cache second part
query2 := &mockQuery{
@@ -374,7 +374,7 @@ func TestBucketCache_MergeTimeSeriesResults(t *testing.T) {
{Series: []*qbtypes.TimeSeries{series2}},
},
},
})
}, nil)
// Wait for cache writes
time.Sleep(10 * time.Millisecond)
@@ -441,7 +441,7 @@ func TestBucketCache_RawData(t *testing.T) {
Value: rawData,
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -481,7 +481,7 @@ func TestBucketCache_ScalarData(t *testing.T) {
Value: scalarData,
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -509,7 +509,7 @@ func TestBucketCache_EmptyFingerprint(t *testing.T) {
Value: createTestTimeSeries("A", 1000, 5000, 1000),
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Should still be able to retrieve
@@ -564,7 +564,7 @@ func TestBucketCache_ConcurrentAccess(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries(fmt.Sprintf("Q%d", id), query.startMs, query.endMs, 100),
}
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result)
bc.Put(context.Background(), valuer.UUID{}, query, qbtypes.Step{Duration: 100 * time.Microsecond}, result, nil)
done <- true
}(i)
}
@@ -624,7 +624,7 @@ func TestBucketCache_GetMissRanges_FluxInterval(t *testing.T) {
},
}
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, cachedResult, nil)
// Get miss ranges
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -686,7 +686,7 @@ func TestBucketCache_Put_FluxIntervalTrimming(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
// Retrieve cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -756,7 +756,7 @@ func TestBucketCache_Put_EntireRangeInFluxInterval(t *testing.T) {
}
// Put the result - should not cache anything
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// Try to get cached data - should have no cached data
cached, missing := bc.GetMissRanges(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond})
@@ -862,7 +862,7 @@ func TestBucketCache_EmptyDataHandling(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, tt.result, nil)
// Wait a bit for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -927,7 +927,7 @@ func TestBucketCache_PartialValues(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: query.startMs, To: query.endMs}: result.Stats})
// Wait for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -997,7 +997,7 @@ func TestBucketCache_AllPartialValues(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
// Wait for cache to be written
time.Sleep(10 * time.Millisecond)
@@ -1058,7 +1058,7 @@ func TestBucketCache_FilteredCachedResults(t *testing.T) {
}
// Cache the wide range
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1)
bc.Put(ctx, orgID, query1, qbtypes.Step{Duration: 1000 * time.Millisecond}, result1, nil)
time.Sleep(10 * time.Millisecond)
// Now query for a smaller range (2000-3500ms)
@@ -1125,7 +1125,7 @@ func TestBucketCache_PromQLKeepsTheValueAtTheWindowEnd(t *testing.T) {
}},
}},
},
})
}, nil)
time.Sleep(10 * time.Millisecond)
cached, missing := bc.GetMissRanges(ctx, orgID, query, step)
@@ -1291,7 +1291,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1345,7 +1345,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1397,7 +1397,7 @@ func TestBucketCache_PartialValueDetection(t *testing.T) {
}
// Put the result
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Get cached data
@@ -1454,7 +1454,7 @@ func TestBucketCache_NoCache(t *testing.T) {
}
// Put the result in cache
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result)
bc.Put(ctx, orgID, query, qbtypes.Step{Duration: 1000 * time.Millisecond}, result, nil)
time.Sleep(10 * time.Millisecond)
// Verify data is cached
@@ -1475,11 +1475,12 @@ func TestBucketCachePutSlicesAtCellBoundaries(t *testing.T) {
// a 1s step gives 60s cells, so 30s to 150s spans three of them
query := &mockQuery{fingerprint: "sliced-query", startMs: 30000, endMs: 150000}
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
result := &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 30000, 150000, 1000),
Stats: qbtypes.ExecStats{RowsScanned: 120, BytesScanned: 1200, DurationMS: 12},
})
}
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: 30000, To: 150000}: result.Stats})
type bucketShape struct {
cell, startMs, endMs, rowsScanned uint64
@@ -1539,7 +1540,7 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
name: "OverlappingWrites_BecomeOne",
firstWindow: qbtypes.TimeRange{From: 1000, To: 4000},
secondWindow: qbtypes.TimeRange{From: 3000, To: 6000},
expectedBuckets: []bucketShape{{1000, 6000, 6}},
expectedBuckets: []bucketShape{{1000, 6000, 5}},
expectedMissingRanges: []*qbtypes.TimeRange{},
expectedValueCount: 5,
},
@@ -1570,12 +1571,13 @@ func TestBucketCachePutAbsorbsWritesWithinACell(t *testing.T) {
for _, window := range []qbtypes.TimeRange{testCase.firstWindow, testCase.secondWindow} {
query := &mockQuery{fingerprint: "absorb-query", startMs: window.From, endMs: window.To}
bc.Put(ctx, orgID, query, step, &qbtypes.Result{
result := &qbtypes.Result{
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", window.From, window.To, 1000),
// one row per second, so a bucket's stats read as the seconds it was scanned for
// one row per second, so a bucket's stats read as the seconds of data it holds
Stats: qbtypes.ExecStats{RowsScanned: (window.To - window.From) / 1000},
})
}
bc.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{window: result.Stats})
}
query := &mockQuery{
@@ -1609,7 +1611,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 1000, 10000, 1000),
Warnings: []string{"from the wide write"},
})
}, nil)
// a write already covered by the cell's bucket must not rewrite the entry,
// which shows as its warnings never arriving
@@ -1618,7 +1620,7 @@ func TestBucketCachePutLeavesAnUnchangedCellAlone(t *testing.T) {
Type: qbtypes.RequestTypeTimeSeries,
Value: createTestTimeSeries("A", 3000, 5000, 1000),
Warnings: []string{"from the inside write"},
})
}, nil)
var cellEntry qbtypes.CachedData
require.NoError(t, bc.cache.Get(ctx, orgID, bc.generateCacheKey(wide, 0), &cellEntry))

View File

@@ -828,7 +828,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
return nil, err
}
// Store in cache for future use
q.bucketCache.Put(ctx, orgID, query, step, result)
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
return result, nil
}
}
@@ -884,16 +884,19 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
if err != nil {
return nil, err
}
q.bucketCache.Put(ctx, orgID, query, step, result)
startMs, endMs := query.Window()
q.bucketCache.Put(ctx, orgID, query, step, result, map[qbtypes.TimeRange]qbtypes.ExecStats{{From: startMs, To: endMs}: result.Stats})
return result, nil
}
}
// Calculate total stats and filter out nil results
validResults := make([]*qbtypes.Result, 0, len(freshResults))
for _, result := range freshResults {
execStatsForQueriedTimeRanges := make(map[qbtypes.TimeRange]qbtypes.ExecStats, len(freshResults))
for i, result := range freshResults {
if result != nil {
validResults = append(validResults, result)
execStatsForQueriedTimeRanges[*missingRanges[i]] = result.Stats
totalStats.RowsScanned += result.Stats.RowsScanned
totalStats.BytesScanned += result.Stats.BytesScanned
totalStats.DurationMS += result.Stats.DurationMS
@@ -908,7 +911,7 @@ func (q *querier) executeWithCache(ctx context.Context, orgID valuer.UUID, query
mergedResult.Stats.DurationMS += totalStats.DurationMS
// Store merged result in cache
q.bucketCache.Put(ctx, orgID, query, step, mergedResult)
q.bucketCache.Put(ctx, orgID, query, step, mergedResult, execStatsForQueriedTimeRanges)
return mergedResult, nil
}

View File

@@ -492,14 +492,6 @@ func (r *BaseRule) extractMetricAndGroupBys(ctx context.Context) (map[string][]s
// FilterNewSeries filters out items that are too new based on metadata first_seen timestamps.
// Returns the filtered series (old ones) excluding new series that are still within the grace period.
func (r *BaseRule) FilterNewSeries(ctx context.Context, ts time.Time, series []*qbtypes.TimeSeries) ([]*qbtypes.TimeSeries, error) {
return filterNewByLabels(ctx, r, ts, series, func(s *qbtypes.TimeSeries) []*qbtypes.Label { return s.Labels })
}
func (r *BaseRule) FilterNewScalarGroups(ctx context.Context, ts time.Time, groups []qbtypes.ScalarGroup) ([]qbtypes.ScalarGroup, error) {
return filterNewByLabels(ctx, r, ts, groups, func(group qbtypes.ScalarGroup) []*qbtypes.Label { return group.Labels })
}
func filterNewByLabels[T any](ctx context.Context, r *BaseRule, ts time.Time, series []T, labelsOf func(T) []*qbtypes.Label) ([]T, error) {
// Extract metric names and groupBy keys
metricToGroupedFields, err := r.extractMetricAndGroupBys(ctx)
if err != nil {
@@ -518,7 +510,7 @@ func filterNewByLabels[T any](ctx context.Context, r *BaseRule, ts time.Time, se
for i := 0; i < len(series); i++ {
valueForKey := func(key string) (string, bool) {
for _, item := range labelsOf(series[i]) {
for _, item := range series[i].Labels {
if item.Key.Name == key {
return fmt.Sprint(item.Value), true
}
@@ -571,7 +563,7 @@ func filterNewByLabels[T any](ctx context.Context, r *BaseRule, ts time.Time, se
}
// Filter series based on first_seen + delay
filteredSeries := make([]T, 0, len(series))
filteredSeries := make([]*qbtypes.TimeSeries, 0, len(series))
evalTimeMs := ts.UnixMilli()
newGroupEvalDelayMs := r.newGroupEvalDelay.Milliseconds()
@@ -613,7 +605,7 @@ func filterNewByLabels[T any](ctx context.Context, r *BaseRule, ts time.Time, se
ctx, "skipping new series",
slog.Int("series.index", i), slog.Int64("series.max_first_seen", maxFirstSeen),
slog.Int64("eval.time_ms", evalTimeMs), slog.Int64("eval.delay_ms", newGroupEvalDelayMs),
slog.Any("series.labels", labelsOf(series[i])),
slog.Any("series.labels", series[i].Labels),
)
continue
}

View File

@@ -75,7 +75,7 @@ func (r *ThresholdRule) prepareQueryRange(ctx context.Context, ts time.Time) (*q
req := &qbtypes.QueryRangeRequest{
Start: uint64(start),
End: uint64(end),
RequestType: r.Condition().CompositeQuery.PanelType.GetQueryRangeRequestType(),
RequestType: qbtypes.RequestTypeTimeSeries,
CompositeQuery: qbtypes.CompositeQuery{
Queries: make([]qbtypes.QueryEnvelope, 0),
},
@@ -132,6 +132,8 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return nil, err
}
var results []*qbtypes.TimeSeriesData
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.CodeNamespace: "rules",
instrumentationtypes.CodeFunctionName: "buildAndRunQuery",
@@ -142,22 +144,22 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return nil, err
}
for _, item := range v5Result.Data.Results {
if tsData, ok := item.(*qbtypes.TimeSeriesData); ok {
results = append(results, tsData)
} else {
// NOTE: should not happen but just to ensure we don't miss it if it happens for some reason
r.logger.WarnContext(ctx, "expected qbtypes.TimeSeriesData but got unexpected type", slog.String("item.type", reflect.TypeOf(item).String()))
}
}
selectedQuery := r.SelectedQuery(ctx)
var queryResult *qbtypes.TimeSeriesData
for _, item := range v5Result.Data.Results {
switch data := item.(type) {
case *qbtypes.TimeSeriesData:
if data.QueryName == selectedQuery {
queryResult = data
}
case *qbtypes.ScalarData:
if data.QueryName == selectedQuery {
return r.evalScalarResult(ctx, ts, data)
}
default:
// NOTE: should not happen but just to ensure we don't miss it if it happens for some reason
r.logger.WarnContext(ctx, "expected qbtypes.TimeSeriesData or qbtypes.ScalarData but got unexpected type", slog.String("item.type", reflect.TypeOf(item).String()))
for _, res := range results {
if res.QueryName == selectedQuery {
queryResult = res
break
}
}
@@ -211,44 +213,6 @@ func (r *ThresholdRule) buildAndRunQuery(ctx context.Context, orgID valuer.UUID,
return resultVector, nil
}
func (r *ThresholdRule) evalScalarResult(ctx context.Context, ts time.Time, queryResult *qbtypes.ScalarData) (ruletypes.Vector, error) {
groups := queryResult.ExtractGroups()
hasData := len(groups) > 0
if missingDataAlert := r.HandleMissingDataAlert(ctx, ts, hasData); missingDataAlert != nil {
return ruletypes.Vector{*missingDataAlert}, nil
}
var resultVector ruletypes.Vector
// Filter out new groups if newGroupEvalDelay is configured
groupsToProcess := groups
if r.ShouldSkipNewGroups() {
filteredGroups, filterErr := r.BaseRule.FilterNewScalarGroups(ctx, ts, groupsToProcess)
// In case of error we log the error and continue with the original groups
if filterErr != nil {
r.logger.ErrorContext(ctx, "error filtering new groups", errors.Attr(filterErr))
} else {
groupsToProcess = filteredGroups
}
}
for _, group := range groupsToProcess {
// the first aggregation, as the series path reads Aggregations[0]
resultSeries, err := r.Threshold.EvalScalar(group.Labels, group.Values[0], r.Unit(), ruletypes.EvalData{
ActiveAlerts: r.ActiveAlertsLabelFP(),
SendUnmatched: r.ShouldSendUnmatched(),
})
if err != nil {
return nil, err
}
resultVector = append(resultVector, resultSeries...)
}
return resultVector, nil
}
func (r *ThresholdRule) Eval(ctx context.Context, ts time.Time) (int, error) {
prevState := r.State()

View File

@@ -1,204 +0,0 @@
package rules
import (
"context"
"testing"
"time"
cmock "github.com/SigNoz/clickhouse-go-mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
"github.com/SigNoz/signoz/pkg/types/metrictypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
func scalarPanelRule(alertType ruletypes.AlertType, panelType ruletypes.PanelType, query qbtypes.QueryEnvelope, target float64, matchType ruletypes.MatchType) ruletypes.PostableRule {
return ruletypes.PostableRule{
AlertName: valuer.NewDisplayName("Scalar panel test"),
AlertType: alertType,
RuleType: ruletypes.RuleTypeThreshold,
Evaluation: &ruletypes.EvaluationEnvelope{Kind: ruletypes.RollingEvaluation, Spec: ruletypes.RollingWindow{
EvalWindow: valuer.MustParseTextDuration("5m"),
Frequency: valuer.MustParseTextDuration("1m"),
}},
RuleCondition: &ruletypes.RuleCondition{
CompositeQuery: &ruletypes.AlertCompositeQuery{
QueryType: ruletypes.QueryTypeBuilder,
PanelType: panelType,
Queries: []qbtypes.QueryEnvelope{query},
},
SelectedQuery: "A",
Thresholds: &ruletypes.RuleThresholdData{
Kind: ruletypes.BasicThresholdKind,
Spec: ruletypes.BasicRuleThresholds{{
Name: "critical",
TargetValue: &target,
MatchType: matchType,
CompareOperator: ruletypes.ValueIsAbove,
}},
},
},
}
}
// A value panel reduces the window to one number (reduceTo), so a target no
// single step crosses fires on the reduced value and matchType, which is
// about steps, no longer matters. The same rows on a graph panel keep the
// step semantics.
func TestThresholdRuleEvalScalarPanelTypeMetricsReducedOverWindow(t *testing.T) {
ts := time.Now().Truncate(time.Minute)
query := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{
Name: "A",
Signal: telemetrytypes.SignalMetrics,
StepInterval: qbtypes.Step{Duration: time.Minute},
Aggregations: []qbtypes.MetricAggregation{{
MetricName: "signoz_calls_total",
Temporality: metrictypes.Delta,
TimeAggregation: metrictypes.TimeAggregationRate,
SpaceAggregation: metrictypes.SpaceAggregationSum,
ReduceTo: qbtypes.ReduceToSum,
}},
},
}
cols := []cmock.ColumnType{
{Name: "ts", Type: "DateTime"},
{Name: "value", Type: "Float64"},
}
values := [][]any{
{ts.Add(-4 * time.Minute), float64(100)},
{ts.Add(-3 * time.Minute), float64(150)},
{ts.Add(-2 * time.Minute), float64(250)},
}
testCases := []struct {
name string
panelType ruletypes.PanelType
matchType ruletypes.MatchType
target float64
expectedAlertCount int
}{
{name: "ValuePanel_SumAboveTarget_AllTheTimes_Fires", panelType: ruletypes.PanelTypeValue, matchType: ruletypes.AllTheTimes, target: 400, expectedAlertCount: 1},
{name: "ValuePanel_SumBelowTarget_AtleastOnce_Silent", panelType: ruletypes.PanelTypeValue, matchType: ruletypes.AtleastOnce, target: 600, expectedAlertCount: 0},
{name: "GraphPanel_NoStepAboveTarget_AllTheTimes_Silent", panelType: ruletypes.PanelTypeGraph, matchType: ruletypes.AllTheTimes, target: 400, expectedAlertCount: 0},
{name: "GraphPanel_OneStepAboveTarget_AtleastOnce_Fires", panelType: ruletypes.PanelTypeGraph, matchType: ruletypes.AtleastOnce, target: 200, expectedAlertCount: 1},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, &queryMatcherAny{})
telemetryStore.Mock().
ExpectQuery("SELECT any").
WithArgs(nil, nil, nil, nil, nil, nil, nil).
WillReturnRows(cmock.NewRows(cols, values))
querier, mockMetadataStore := prepareQuerierForMetrics(t, telemetryStore)
mockMetadataStore.TypeMap["signoz_calls_total"] = metrictypes.SumType
postableRule := scalarPanelRule(ruletypes.AlertTypeMetric, testCase.panelType, query, testCase.target, testCase.matchType)
rule, err := NewThresholdRule("scalar", valuer.GenerateUUID(), &postableRule, querier, instrumentationtest.New().Logger(), mustParseURL(t, "http://localhost:8080"))
require.NoError(t, err)
alertsFound, err := rule.Eval(context.Background(), ts)
require.NoError(t, err)
assert.Equal(t, testCase.expectedAlertCount, alertsFound)
})
}
}
// A table panel over logs yields one row per group for the whole window, and
// the engine raises one alert per row that crosses the target, labelled with
// the group values.
func TestThresholdRuleEvalScalarPanelTypeLogsOneAlertPerRow(t *testing.T) {
ts := time.Now().Truncate(time.Minute)
serviceKey := telemetrytypes.TelemetryFieldKey{
Name: "service.name",
FieldContext: telemetrytypes.FieldContextResource,
FieldDataType: telemetrytypes.FieldDataTypeString,
}
query := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
Name: "A",
Signal: telemetrytypes.SignalLogs,
StepInterval: qbtypes.Step{Duration: time.Minute},
Aggregations: []qbtypes.LogAggregation{{Expression: "count()"}},
GroupBy: []qbtypes.GroupByKey{{TelemetryFieldKey: serviceKey}},
},
}
keysMap := map[string][]*telemetrytypes.TelemetryFieldKey{"service.name": {&serviceKey}}
cols := []cmock.ColumnType{
{Name: "__GROUP_BY_KEY_0_service.name", Type: "String"},
{Name: "__result_0", Type: "UInt64"},
}
testCases := []struct {
name string
rows [][]any
alertOnAbsent bool
expectedAlertCount int
expectedServices []string
expectedMissing bool
}{
{
name: "TwoGroups_OneAboveTarget_FiresForThatGroup",
rows: [][]any{{"checkout", uint64(120)}, {"cart", uint64(30)}},
expectedAlertCount: 1,
expectedServices: []string{"checkout"},
},
{
name: "TwoGroups_BothAboveTarget_FiresForEach",
rows: [][]any{{"checkout", uint64(120)}, {"cart", uint64(130)}},
expectedAlertCount: 2,
expectedServices: []string{"cart", "checkout"},
},
{
name: "NoRows_AlertOnAbsent_FiresNoData",
rows: [][]any{},
alertOnAbsent: true,
expectedAlertCount: 1,
expectedMissing: true,
},
{
name: "NoRows_WithoutAlertOnAbsent_Silent",
rows: [][]any{},
expectedAlertCount: 0,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, &queryMatcherAny{})
telemetryStore.Mock().
ExpectQuery("SELECT any").
WithArgs(nil, nil, nil, nil).
WillReturnRows(cmock.NewRows(cols, testCase.rows))
querier := prepareQuerierForLogs(t, telemetryStore, keysMap)
postableRule := scalarPanelRule(ruletypes.AlertTypeLogs, ruletypes.PanelTypeTable, query, 100, ruletypes.OnAverage)
postableRule.RuleCondition.AlertOnAbsent = testCase.alertOnAbsent
rule, err := NewThresholdRule("scalar", valuer.GenerateUUID(), &postableRule, querier, instrumentationtest.New().Logger(), mustParseURL(t, "http://localhost:8080"))
require.NoError(t, err)
alertsFound, err := rule.Eval(context.Background(), ts)
require.NoError(t, err)
assert.Equal(t, testCase.expectedAlertCount, alertsFound)
services := make([]string, 0, len(rule.Active))
for _, alert := range rule.Active {
assert.Equal(t, testCase.expectedMissing, alert.Missing)
if service := alert.QueryResultLabels.Get("service.name"); service != "" {
services = append(services, service)
}
}
assert.ElementsMatch(t, testCase.expectedServices, services)
})
}
}

View File

@@ -43,6 +43,23 @@ func (c *CachedBucket) Touches(other *CachedBucket) bool {
return c.StartMs <= other.EndMs && other.StartMs <= c.EndMs
}
// ProrateStatsToWindow returns the share of the stats for the part of the
// bucket inside [startMs, endMs).
func (c *CachedBucket) ProrateStatsToWindow(startMs, endMs uint64) ExecStats {
return c.Stats.prorate(overlapMs(c.StartMs, c.EndMs, startMs, endMs), c.EndMs-c.StartMs)
}
// ProrateStatsToUnqueried returns the share of the stats for the part of the
// bucket no queried range covers.
func (c *CachedBucket) ProrateStatsToUnqueried(execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ExecStats {
widthMs := c.EndMs - c.StartMs
queriedMs := uint64(0)
for queried := range execStatsForQueriedTimeRanges {
queriedMs += overlapMs(c.StartMs, c.EndMs, queried.From, queried.To)
}
return c.Stats.prorate(widthMs-min(queriedMs, widthMs), widthMs)
}
// CachedData represents the full cached data for a query.
type CachedData struct {
Buckets []*CachedBucket `json:"buckets"`
@@ -88,7 +105,7 @@ func (c *CachedData) Cost() int64 {
return size
}
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) ([]*CachedBucket, error) {
func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64, execStatsForQueriedTimeRanges map[TimeRange]ExecStats) ([]*CachedBucket, error) {
tsData, ok := r.Value.(*TimeSeriesData)
if !ok || tsData == nil {
return nil, errors.NewInternalf(errors.CodeInternal, "result of type %s cannot be bucketed", r.Type.StringValue())
@@ -111,18 +128,39 @@ func (r *Result) SplitIntoCacheCellBuckets(startMs, endMs, cellWidthMs uint64) (
if err != nil {
return nil, err
}
// A slice costs what was queried inside it; the rest of the result came
// out of the cache and is costed there already
sliceStats := ExecStats{StepIntervals: maps.Clone(r.Stats.StepIntervals)}
for queried, stats := range execStatsForQueriedTimeRanges {
queriedMs := overlapMs(from, to, queried.From, queried.To)
if queriedMs == 0 {
continue
}
share := stats.prorate(queriedMs, queried.To-queried.From)
sliceStats.RowsScanned += share.RowsScanned
sliceStats.BytesScanned += share.BytesScanned
sliceStats.DurationMS += share.DurationMS
}
cellBuckets = append(cellBuckets, &CachedBucket{
StartMs: from,
EndMs: to,
Type: r.Type,
Value: value,
Stats: r.Stats.prorate(to-from, endMs-startMs),
Stats: sliceStats,
})
from = to
}
return cellBuckets, nil
}
// overlapMs is the length of [aFromMs, aToMs) ∩ [bFromMs, bToMs).
func overlapMs(aFromMs, aToMs, bFromMs, bToMs uint64) uint64 {
if fromMs, toMs := max(aFromMs, bFromMs), min(aToMs, bToMs); fromMs < toMs {
return toMs - fromMs
}
return 0
}
// prorate returns the share of the stats that partMs out of wholeMs of the
// scanned window accounts for.
func (e ExecStats) prorate(partMs, wholeMs uint64) ExecStats {

View File

@@ -444,39 +444,6 @@ type ScalarData struct {
Data [][]any `json:"data" description:"The rows, each a list of values aligned with columns."`
}
// ScalarGroup is one entry of a ScalarData, the scalar counterpart of a
// TimeSeries: the group-by cells as labels and one value per aggregation, in
// column order. A cell that is not numeric reads as NaN.
type ScalarGroup struct {
Labels []*Label
Values []float64
}
func (sd *ScalarData) ExtractGroups() []ScalarGroup {
if !slices.ContainsFunc(sd.Columns, func(col *ColumnDescriptor) bool { return col.Type == ColumnTypeAggregation }) {
return nil
}
groups := make([]ScalarGroup, 0, len(sd.Data))
for _, row := range sd.Data {
group := ScalarGroup{Labels: make([]*Label, 0), Values: make([]float64, 0)}
for i, col := range sd.Columns {
var cell any
if i < len(row) {
cell = row[i]
}
switch col.Type {
case ColumnTypeGroup:
group.Labels = append(group.Labels, &Label{Key: col.TelemetryFieldKey, Value: cell})
case ColumnTypeAggregation:
group.Values = append(group.Values, numericAsFloat(cell))
}
}
groups = append(groups, group)
}
return groups
}
type RawData struct {
QueryName string `json:"queryName" description:"The name of the query that produced these rows."`
NextCursor string `json:"nextCursor" description:"The cursor to pass in the next request to continue from the last row; empty when there are no more rows."`
@@ -682,17 +649,3 @@ func (r RawData) MarshalJSON() ([]byte, error) {
type Alias RawData
return json.Marshal((*Alias)(&r))
}
func numericAsFloat(v any) float64 {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Float32, reflect.Float64:
return rv.Float()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(rv.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(rv.Uint())
default:
return math.NaN()
}
}

View File

@@ -530,52 +530,3 @@ func TestTimeSeriesDataFilterToTimeRange(t *testing.T) {
})
}
}
func TestScalarDataExtractGroups(t *testing.T) {
serviceKey := telemetrytypes.TelemetryFieldKey{Name: "service"}
groupCol := &ColumnDescriptor{TelemetryFieldKey: serviceKey, QueryName: "A", Type: ColumnTypeGroup}
countCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "__result_0"}, QueryName: "A", AggregationIndex: 0, Type: ColumnTypeAggregation}
latencyCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "p99"}, QueryName: "A", AggregationIndex: 1, Type: ColumnTypeAggregation}
testCases := []struct {
name string
scalarData *ScalarData
expectedGroups []ScalarGroup
}{
{
name: "GroupByColumn_LabelsAndOneValuePerAggregation_InResultOrder",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{groupCol, countCol, latencyCol}, Data: [][]any{
{"cart", int64(2), 20.0},
{"auth", uint64(1), float32(10)},
}},
expectedGroups: []ScalarGroup{
{Labels: []*Label{{Key: serviceKey, Value: "cart"}}, Values: []float64{2, 20}},
{Labels: []*Label{{Key: serviceKey, Value: "auth"}}, Values: []float64{1, 10}},
},
},
{
name: "NoGroupByColumn_SingleUnlabeledGroup",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{countCol}, Data: [][]any{{3.5}}},
expectedGroups: []ScalarGroup{{Labels: []*Label{}, Values: []float64{3.5}}},
},
{
name: "NoAggregationColumn_NoGroups",
scalarData: &ScalarData{Columns: []*ColumnDescriptor{groupCol}, Data: [][]any{{"cart"}}},
expectedGroups: nil,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.expectedGroups, testCase.scalarData.ExtractGroups())
})
}
}
func TestScalarDataExtractGroupsNonNumericCell(t *testing.T) {
countCol := &ColumnDescriptor{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "__result_0"}, QueryName: "A", Type: ColumnTypeAggregation}
groups := (&ScalarData{Columns: []*ColumnDescriptor{countCol}, Data: [][]any{{"n/a"}}}).ExtractGroups()
assert.Len(t, groups, 1)
assert.True(t, math.IsNaN(groups[0].Values[0]))
}

View File

@@ -87,17 +87,6 @@ func (p PanelType) Validate() error {
}
}
func (p PanelType) GetQueryRangeRequestType() qbtypes.RequestType {
switch p {
case PanelTypeTable, PanelTypeValue:
return qbtypes.RequestTypeScalar
default:
// Only the write path validates the panel, so a stored unset or
// unknown one runs as graph.
return qbtypes.RequestTypeTimeSeries
}
}
// Note: this is used to represent the state of the alert query
// i.e the active tab which should be used to represent the selection
@@ -132,7 +121,7 @@ func (q QueryType) Validate() error {
type AlertCompositeQuery struct {
Queries []qbtypes.QueryEnvelope `json:"queries" required:"true" description:"The queries to evaluate, at least one. Every envelope type must match queryType: builder_query and builder_formula for builder, promql for promql, clickhouse_sql for clickhouse_sql."`
PanelType PanelType `json:"panelType" required:"true" description:"How the queries are evaluated. graph runs them as time series and matchType decides which points must satisfy op. table and value run them as scalar: one value per group over the whole evaluation window, compared directly, so matchType has no effect and metric aggregations need reduceTo. promql queries and anomaly_rule support graph only."`
PanelType PanelType `json:"panelType" required:"true" description:"The panel the UI renders the queries with: graph, table or value. Use graph for alerts."`
QueryType QueryType `json:"queryType" required:"true" description:"The query language of every query: builder, promql or clickhouse_sql."`
Unit string `json:"unit,omitempty" description:"The unit of the query result, such as percent, ms or bytes. Used to format values in notifications and to convert thresholds given in a different targetUnit."`
}

View File

@@ -1,29 +0,0 @@
package ruletypes
import (
"testing"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/stretchr/testify/assert"
)
func TestPanelTypeGetQueryRangeRequestType(t *testing.T) {
testCases := []struct {
name string
panelType PanelType
expectedRequestType qbtypes.RequestType
}{
{name: "Graph_TimeSeries", panelType: PanelTypeGraph, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Unset_TimeSeries", panelType: PanelType{}, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Unknown_TimeSeries", panelType: PanelType{valuer.NewString("pie")}, expectedRequestType: qbtypes.RequestTypeTimeSeries},
{name: "Table_Scalar", panelType: PanelTypeTable, expectedRequestType: qbtypes.RequestTypeScalar},
{name: "Value_Scalar", panelType: PanelTypeValue, expectedRequestType: qbtypes.RequestTypeScalar},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
assert.Equal(t, testCase.expectedRequestType, testCase.panelType.GetQueryRangeRequestType())
})
}
}

View File

@@ -391,18 +391,14 @@ func (r *PostableRule) Validate() error {
if err := r.RuleCondition.CompositeQuery.PanelType.Validate(); err != nil {
errs = append(errs, err)
}
queryRangeRequestType := r.RuleCondition.CompositeQuery.PanelType.GetQueryRangeRequestType()
if len(r.RuleCondition.CompositeQuery.Queries) == 0 {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput, "condition.compositeQuery.queries: must have at least one query"))
} else {
cq := &qbtypes.CompositeQuery{Queries: r.RuleCondition.CompositeQuery.Queries}
if err := cq.Validate(qbtypes.GetValidationOptions(queryRangeRequestType)...); err != nil {
if err := cq.Validate(qbtypes.GetValidationOptions(qbtypes.RequestTypeTimeSeries)...); err != nil {
errs = append(errs, err)
}
}
if queryRangeRequestType == qbtypes.RequestTypeScalar {
errs = append(errs, r.validateScalarPanelType()...)
}
}
if r.RuleCondition.SelectedQuery == "" {
@@ -457,26 +453,6 @@ func (r *PostableRule) Validate() error {
return nil
}
func (r *PostableRule) validateScalarPanelType() []error {
var errs []error
panelType := r.RuleCondition.CompositeQuery.PanelType.StringValue()
if r.RuleType == RuleTypeAnomaly {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.compositeQuery.panelType: anomaly_rule supports %q only, got %q", PanelTypeGraph.StringValue(), panelType))
}
if r.RuleType == RuleTypeProm || r.RuleCondition.CompositeQuery.QueryType == QueryTypePromQL {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.compositeQuery.panelType: promql queries support %q only, got %q", PanelTypeGraph.StringValue(), panelType))
}
if r.RuleCondition.RequireMinPoints {
errs = append(errs, errors.NewInvalidInputf(errors.CodeInvalidInput,
"condition.requireMinPoints: not supported with panelType %q, which evaluates one value per group", panelType))
}
return errs
}
func (r *PostableRule) validateSchemaVersion() []error {
switch r.SchemaVersion {
case SchemaVersionV2Alpha1:

View File

@@ -126,9 +126,6 @@ type RuleThreshold interface {
// Eval runs the given series through the threshold rules
// using the given EvalData and returns the matching series
Eval(series *qbtypes.TimeSeries, unit string, evalData EvalData) (Vector, error)
// EvalScalar runs one value per group through the threshold rules; the
// value is compared directly, matchType plays no part.
EvalScalar(labels []*qbtypes.Label, value float64, unit string, evalData EvalData) (Vector, error)
GetRuleReceivers() []RuleReceivers
// Validate runs on the write path and before a task is built; a stored
// rule may hold a threshold that fails it and still decode.
@@ -271,37 +268,6 @@ func (r BasicRuleThresholds) Eval(s *qbtypes.TimeSeries, unit string, evalData E
return resultVector, nil
}
func (r BasicRuleThresholds) EvalScalar(labels []*qbtypes.Label, value float64, unit string, evalData EvalData) (Vector, error) {
var resultVector Vector
if math.IsNaN(value) || math.IsInf(value, 0) {
return resultVector, nil
}
thresholds := []BasicRuleThreshold(r)
sortThresholds(thresholds)
for _, threshold := range thresholds {
op := threshold.CompareOperator.Normalize()
smpl := Sample{
Point: Point{V: value},
Metric: PrepareSampleLabelsForRule(labels, threshold.Name),
Target: *threshold.TargetValue,
RecoveryTarget: threshold.RecoveryTarget,
TargetUnit: threshold.TargetUnit,
CompareOperator: threshold.CompareOperator,
MatchType: threshold.MatchType,
}
if matchesCompareOp(op, value, threshold.target(unit)) || evalData.SendUnmatched {
resultVector = append(resultVector, smpl)
continue
}
if threshold.RecoveryTarget != nil && evalData.HasActiveAlert(smpl.Metric.Hash()) && matchesCompareOp(op, value, threshold.recoveryTarget(unit)) {
smpl.IsRecovering = true
resultVector = append(resultVector, smpl)
}
}
return resultVector, nil
}
func sortThresholds(thresholds []BasicRuleThreshold) {
sort.Slice(thresholds, func(i, j int) bool {

View File

@@ -1,12 +1,10 @@
package ruletypes
import (
"math"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -450,45 +448,6 @@ func TestBasicRuleThresholdEval_UnitConversion(t *testing.T) {
}
}
func TestBasicRuleThresholdsEvalScalar(t *testing.T) {
target := 100.0
recoveryTarget := 80.0
labels := []*qbtypes.Label{{Key: telemetrytypes.TelemetryFieldKey{Name: "service"}, Value: "cart"}}
thresholds := BasicRuleThresholds{{Name: "critical", TargetValue: &target, RecoveryTarget: &recoveryTarget, CompareOperator: ValueIsAbove, MatchType: AllTheTimes}}
activeAlerts := map[uint64]struct{}{PrepareSampleLabelsForRule(labels, "critical").Hash(): {}}
testCases := []struct {
name string
value float64
evalData EvalData
expectedSampleCount int
expectedValue float64
expectedRecovering bool
}{
{name: "AboveTarget_Fires", value: 150, expectedSampleCount: 1, expectedValue: 150},
{name: "BelowTarget_Silent", value: 50},
{name: "BelowTarget_SendUnmatched_ReportsValue", value: 50, evalData: EvalData{SendUnmatched: true}, expectedSampleCount: 1, expectedValue: 50},
{name: "ActiveAlertAboveRecoveryTarget_Recovering", value: 90, evalData: EvalData{ActiveAlerts: activeAlerts}, expectedSampleCount: 1, expectedValue: 90, expectedRecovering: true},
{name: "NoActiveAlertAboveRecoveryTarget_Silent", value: 90},
{name: "NaN_Silent", value: math.NaN()},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
vector, err := thresholds.EvalScalar(labels, testCase.value, "", testCase.evalData)
require.NoError(t, err)
require.Len(t, vector, testCase.expectedSampleCount)
if testCase.expectedSampleCount == 0 {
return
}
assert.Equal(t, testCase.expectedValue, vector[0].V)
assert.Equal(t, testCase.expectedRecovering, vector[0].IsRecovering)
assert.Equal(t, "cart", vector[0].Metric.Get("service"))
assert.Equal(t, "critical", vector[0].Metric.Get(LabelThresholdName))
})
}
}
func TestPrepareSampleLabelsForRule(t *testing.T) {
alertAllHashes := make(map[uint64]struct{})
thresholdName := "test"

View File

@@ -1,8 +0,0 @@
{ "timestamp": "2026-01-29T10:00:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:00:15.000000Z", "resources": { "service.name": "cart" }, "attributes": {}, "body": "scalar panel probe: cart", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:00:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:15.000000Z", "resources": { "service.name": "cart" }, "attributes": {}, "body": "scalar panel probe: cart", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:00.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:30.000000Z", "resources": { "service.name": "checkout" }, "attributes": {}, "body": "scalar panel probe: checkout", "severity_text": "INFO" }

View File

@@ -1,72 +0,0 @@
{
"alert": "scalar_table_panel_logs",
"ruleType": "threshold_rule",
"alertType": "LOGS_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 4,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "table",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "logs",
"filter": {
"expression": "body CONTAINS 'scalar panel probe'"
},
"groupBy": [
{
"name": "service.name",
"fieldContext": "resource",
"fieldDataType": "string"
}
],
"aggregations": [
{
"expression": "count()"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -1,3 +0,0 @@
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:00:00+00:00","value":100,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:01:00+00:00","value":150,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}
{"metric_name":"active_requests_scalar_value_panel","labels":{"host":"server-01"},"timestamp":"2026-01-29T10:02:00+00:00","value":250,"temporality":"Unspecified","type_":"Gauge","is_monotonic":false,"flags":0,"description":"","unit":"","env":"default","resource_attrs":{},"scope_attrs":{}}

View File

@@ -1,66 +0,0 @@
{
"alert": "scalar_value_panel_metrics",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 400,
"matchType": "all_the_times",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "metrics",
"stepInterval": "1m",
"aggregations": [
{
"metricName": "active_requests_scalar_value_panel",
"timeAggregation": "avg",
"spaceAggregation": "sum",
"reduceTo": "sum"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -1,66 +0,0 @@
{
"alert": "scalar_value_panel_metrics_as_graph",
"ruleType": "threshold_rule",
"alertType": "METRIC_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 400,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "graph",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "metrics",
"stepInterval": "1m",
"aggregations": [
{
"metricName": "active_requests_scalar_value_panel",
"timeAggregation": "avg",
"spaceAggregation": "sum",
"reduceTo": "sum"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"schemaVersion": "v2alpha1"
}

View File

@@ -442,3 +442,55 @@ def test_builder_refreshing_a_sliding_time_range(
assert uncached.status_code == HTTPStatus.OK, uncached.text
assert_results_equal(from_cache.json(), uncached.json(), "A", "the twentieth refresh")
def test_builder_refreshing_does_not_inflate_rows_scanned(
signoz: types.SigNoz,
create_user_admin: None, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
insert_metrics: Callable[[list[Metrics]], None],
) -> None:
metric_name = f"cache_rows_scanned_{uuid4().hex[:8]}"
# 90 minutes back so even the last refresh closes clear of the flux
# interval, which holds recent data out of the cache
start_time = datetime.fromtimestamp(int((datetime.now(tz=UTC) - timedelta(minutes=90)).timestamp()) // 60 * 60, tz=UTC)
start_time_ms = int(start_time.timestamp() * 1000)
query = [build_builder_query("A", metric_name, "max", "max")]
insert_metrics(
[
Metrics(
metric_name=metric_name,
labels={"service": "api"},
timestamp=start_time + timedelta(minutes=minute),
value=minute,
type_="Gauge",
is_monotonic=False,
)
for minute in range(70)
]
)
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
# a dashboard left open on a thirty minute range, re-running a minute later
# each time. rowsScanned is a cost indicator, so a refresh served mostly out
# of the cache cannot claim more than every read made so far: the first
# full read and then one new minute per refresh, measured with the cache off
uncached_rows_scanned_so_far = 0
for refresh in range(10):
refresh_start_ms = start_time_ms + refresh * MINUTE_MS
refresh_end_ms = refresh_start_ms + 30 * MINUTE_MS
uncached_start_ms = refresh_start_ms if refresh == 0 else refresh_end_ms - MINUTE_MS
uncached_response = make_query_request(signoz, token, uncached_start_ms, refresh_end_ms, query, no_cache=True)
assert uncached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: uncached read failed: {uncached_response.text}"
uncached_rows_scanned_so_far += uncached_response.json()["data"]["meta"]["rowsScanned"]
assert uncached_rows_scanned_so_far > 0, f"refresh {refresh}: uncached read reported no rows scanned"
cached_response = make_query_request(signoz, token, refresh_start_ms, refresh_end_ms, query, no_cache=False)
assert cached_response.status_code == HTTPStatus.OK, f"refresh {refresh}: cached read failed: {cached_response.text}"
cached_rows_scanned = cached_response.json()["data"]["meta"]["rowsScanned"]
assert cached_rows_scanned <= uncached_rows_scanned_so_far, f"refresh {refresh}: cached read reported {cached_rows_scanned} rows scanned, more than the {uncached_rows_scanned_so_far} rows all uncached reads scanned so far"

View File

@@ -2,7 +2,6 @@ import time
from collections.abc import Callable
from http import HTTPStatus
import pytest
import requests
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
@@ -464,84 +463,3 @@ def test_create_rejects_channel_by_name(
"suggestions": [],
},
}
@pytest.mark.parametrize(
("rule", "expected_message"),
[
(
{**VALID_RULE, "condition": {**VALID_RULE["condition"], "compositeQuery": {**VALID_RULE["condition"]["compositeQuery"], "panelType": "value"}}},
"invalid query 'A': reduceTo is required for aggregation #1 in query 'A' for the scalar request type",
),
(
{
**VALID_RULE,
"ruleType": "anomaly_rule",
"condition": {
**VALID_RULE["condition"],
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "validation_probe_cpu", "timeAggregation": "avg", "spaceAggregation": "max", "reduceTo": "avg"}]}}],
},
},
},
'condition.compositeQuery.panelType: anomaly_rule supports "graph" only, got "value"',
),
(
{
**VALID_RULE,
"ruleType": "promql_rule",
"condition": {
**VALID_RULE["condition"],
"compositeQuery": {"queryType": "promql", "panelType": "table", "queries": [{"type": "promql", "spec": {"name": "A", "query": "up == 0", "disabled": False}}]},
},
},
'condition.compositeQuery.panelType: promql queries support "graph" only, got "table"',
),
(
{
**VALID_RULE,
"condition": {
**VALID_RULE["condition"],
"requireMinPoints": True,
"requiredNumPoints": 2,
"compositeQuery": {
"queryType": "builder",
"panelType": "value",
"queries": [{"type": "builder_query", "spec": {"name": "A", "signal": "metrics", "aggregations": [{"metricName": "validation_probe_cpu", "timeAggregation": "avg", "spaceAggregation": "max", "reduceTo": "avg"}]}}],
},
},
},
'condition.requireMinPoints: not supported with panelType "value", which evaluates one value per group',
),
],
ids=["metrics_without_reduce_to", "anomaly_rule", "promql_query", "require_min_points"],
)
def test_create_rejects_rules_a_scalar_panel_cannot_evaluate(
signoz: SigNoz,
create_user_admin: Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
rule: dict,
expected_message: str,
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
response = requests.post(
signoz.self.host_configs["8080"].get(BASE_URL),
json=rule,
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
assert response.json() == {
"status": "error",
"error": {
"type": "invalid-input",
"code": "invalid_input",
"message": "alert rule is not valid",
"errors": [{"message": expected_message, "suggestions": []}],
"suggestions": [],
},
}

View File

@@ -1,65 +0,0 @@
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
import pytest
from fixtures import types
from fixtures.alerts import (
get_rule_history_top_contributors,
labels_to_map,
wait_for_firing_timeline_entry,
)
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
def test_value_panel_fires_on_the_window_sum(
signoz: types.SigNoz,
create_alert_rule_with_channel: Callable[[str], str],
insert_alert_data: Callable[[list[types.AlertData], datetime], None],
get_token: Callable[[str, str], str],
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)
# one-minute samples of 100, 150 and 250: no step reaches the 400 target,
# their sum over the window does
insert_alert_data(
[types.AlertData(type="metrics", data_path="ruler/test_scenarios/scalar_value_panel_metrics/alert_data.jsonl")],
base_time=datetime.now(tz=UTC) - timedelta(minutes=4),
)
value_rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_value_panel_metrics/rule.json")
graph_rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_value_panel_metrics_as_graph/rule.json")
(item, _) = wait_for_firing_timeline_entry(signoz, token, value_rule_id, query_start_ms)
assert item["value"] == 500
# the same query on a graph panel compares each step, even at_least_once
# never sees 400
with pytest.raises(AssertionError, match="No firing entry recorded"):
wait_for_firing_timeline_entry(signoz, token, graph_rule_id, query_start_ms, wait_seconds=30)
def test_table_panel_fires_per_group_on_the_window_count(
signoz: types.SigNoz,
create_alert_rule_with_channel: Callable[[str], str],
insert_alert_data: Callable[[list[types.AlertData], datetime], None],
get_token: Callable[[str, str], str],
):
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
query_start_ms = int((datetime.now(tz=UTC) - timedelta(minutes=30)).timestamp() * 1000)
# checkout logs two lines a minute for three minutes, cart one line a
# minute for two: only checkout's whole-window count passes the 4 target,
# and no single minute of either does
insert_alert_data(
[types.AlertData(type="logs", data_path="ruler/test_scenarios/scalar_table_panel_logs/alert_data.jsonl")],
base_time=datetime.now(tz=UTC) - timedelta(minutes=4),
)
rule_id = create_alert_rule_with_channel("ruler/test_scenarios/scalar_table_panel_logs/rule.json")
(item, end_ms) = wait_for_firing_timeline_entry(signoz, token, rule_id, query_start_ms)
assert labels_to_map(item["labels"]).get("service.name") == "checkout"
assert item["value"] == 6
contributors = get_rule_history_top_contributors(signoz, token, rule_id, query_start_ms, end_ms)
assert {labels_to_map(contributor["labels"]).get("service.name") for contributor in contributors} == {"checkout"}