Compare commits

...

6 Commits

Author SHA1 Message Date
srikanthccv
2225513317 test(querier): keep one behaviour test for each new formula rule
Removes the differential test, which compared the evaluator with a second
implementation inside the test, and the cancellation tests that counted
calls on a fake context or checked a result that no user sees.

The stop of the workers on a cancelled request has no test. It shows only
in time or in internal calls.

Assisted-by: Claude Fable 5.2
2026-11-20 12:59:55 +05:30
srikanthccv
a69672437a test(querier): cover a formula that is cancelled after it starts
The first test used a context that was done before the call, so the
evaluation never started and the stop of the workers had no test.

Assisted-by: Claude Fable 5.2
2026-11-20 04:23:42 +05:30
srikanthccv
8f47f61520 test(querier): benchmark formulas at the group counts of large scalar results
The largest benchmark had 10,000 series, where a scan of all series for
each group still ends in seconds. These have 100,000 and 626,950 groups,
in the three shapes that took a scan before: a grouped query with a total,
two queries grouped by the same key, and a query with mixed key sets.

Assisted-by: Claude Fable 5.2
2026-11-20 04:23:42 +05:30
srikanthccv
514ce5e77d fix(querier): stop formula evaluation when the request is cancelled
The evaluator took no context, so a request that timed out or lost its
client kept its CPU until the formula ended. The request now fails with a
timeout or cancelled error, and does not answer without the formula.

Building the lookup is not interrupted. The check is between two label
sets of the result.

Assisted-by: Claude Fable 5.2
2026-11-20 04:11:03 +05:30
srikanthccv
319eace8b2 perf(querier): look up formula series by key set for every input
A variable whose series have different label keys took a scan of its
series for each result label set. Each key set now has its own index, so
the scan is gone and one rule decides a match.

The signature keeps the type of a label value, as the comparison on main
does: "200" and 200 do not match. A float NaN is equal to itself here. On
main it is equal to nothing.

Assisted-by: Claude Fable 5.2
2026-11-20 04:04:47 +05:30
srikanthccv
6d6feaea79 chore: temp commit 2026-11-20 03:31:27 +05:30
5 changed files with 591 additions and 212 deletions

View File

@@ -93,7 +93,10 @@ func (q *querier) postProcessResults(ctx context.Context, orgID valuer.UUID, res
}
// Apply formula calculations
typedResults = q.applyFormulas(ctx, typedResults, req)
typedResults, err := q.applyFormulas(ctx, typedResults, req)
if err != nil {
return nil, err
}
// Filter out disabled queries
typedResults = q.filterDisabledQueries(typedResults, req)
@@ -349,7 +352,7 @@ func (q *querier) applyFunctions(result *qbtypes.Result, functions []qbtypes.Fun
}
// applyFormulas processes formula queries in the composite query.
func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) map[string]*qbtypes.Result {
func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes.Result, req *qbtypes.QueryRangeRequest) (map[string]*qbtypes.Result, error) {
// Collect formula queries
formulaQueries := make(map[string]qbtypes.QueryBuilderFormula)
@@ -396,9 +399,19 @@ func (q *querier) applyFormulas(ctx context.Context, results map[string]*qbtypes
// For scalar results, apply limit by processScalarFormula itself since it needs to be applied before converting back to scalar format
results[name] = result
}
// A formula stops when the request is cancelled or out of time, and
// leaves no result. The request must fail then, and not answer
// without the formula.
if err := ctx.Err(); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, errors.WrapTimeoutf(err, errors.CodeTimeout, "query timed out")
}
return nil, errors.WrapCanceledf(err, errors.CodeCanceled, "query canceled")
}
}
return results
return results, nil
}
// processTimeSeriesFormula handles formula evaluation for time series data.
@@ -427,9 +440,12 @@ func (q *querier) processTimeSeriesFormula(
}
// Evaluate the formula
formulaSeries, err := evaluator.EvaluateFormula(timeSeriesData)
formulaSeries, err := evaluator.EvaluateFormula(ctx, timeSeriesData)
if err != nil {
q.logger.ErrorContext(ctx, "failed to evaluate formula", errors.Attr(err), slog.String("formula", formula.Name))
// applyFormulas returns the error of a done ctx
if ctx.Err() == nil {
q.logger.ErrorContext(ctx, "failed to evaluate formula", errors.Attr(err), slog.String("formula", formula.Name))
}
return nil
}
@@ -668,9 +684,12 @@ func (q *querier) processScalarFormula(
return nil
}
formulaSeries, err := evaluator.EvaluateFormula(timeSeriesData)
formulaSeries, err := evaluator.EvaluateFormula(ctx, timeSeriesData)
if err != nil {
q.logger.ErrorContext(ctx, "failed to evaluate formula", errors.Attr(err), slog.String("formula", formula.Name))
// applyFormulas returns the error of a done ctx
if ctx.Err() == nil {
q.logger.ErrorContext(ctx, "failed to evaluate formula", errors.Attr(err), slog.String("formula", formula.Name))
}
return nil
}

View File

@@ -3,7 +3,9 @@ package querier
import (
"context"
"testing"
"time"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -115,7 +117,8 @@ func TestProcessScalarFormula_AppliesOrderAndLimit(t *testing.T) {
Limit: 2,
}
out := q.applyFormulas(context.Background(), makeInputs(), makeReq(formula))
out, err := q.applyFormulas(context.Background(), makeInputs(), makeReq(formula))
require.NoError(t, err)
got, ok := out["F1"]
require.True(t, ok, "formula result missing")
scalar, ok := got.Value.(*qbtypes.ScalarData)
@@ -136,7 +139,8 @@ func TestProcessScalarFormula_AppliesOrderAndLimit(t *testing.T) {
Order: orderByFormula("F1", qbtypes.OrderDirectionAsc),
}
out := q.applyFormulas(context.Background(), makeInputs(), makeReq(formula))
out, err := q.applyFormulas(context.Background(), makeInputs(), makeReq(formula))
require.NoError(t, err)
got, ok := out["F1"]
require.True(t, ok)
scalar, ok := got.Value.(*qbtypes.ScalarData)
@@ -150,6 +154,57 @@ func TestProcessScalarFormula_AppliesOrderAndLimit(t *testing.T) {
})
}
func TestApplyFormulas_ContextDone_FailsWithTheCause(t *testing.T) {
q := &querier{
logger: instrumentationtest.New().Logger(),
}
canceled, cancel := context.WithCancel(context.Background())
cancel()
expired, cancelExpired := context.WithDeadline(context.Background(), time.Unix(0, 0))
defer cancelExpired()
testCases := []struct {
name string
ctx context.Context
// the cause, and the type that decides the status of the response
expectedCause error
expectedType string
}{
{name: "Canceled", ctx: canceled, expectedCause: context.Canceled, expectedType: errors.TypeCanceled.String()},
{name: "DeadlineExceeded", ctx: expired, expectedCause: context.DeadlineExceeded, expectedType: errors.TypeTimeout.String()},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
rows := []struct {
service string
value float64
}{
{"cart", 4},
{"checkout", 2},
}
results := map[string]*qbtypes.Result{"A": scalarInputResult("A", rows), "B": scalarInputResult("B", rows)}
req := &qbtypes.QueryRangeRequest{
RequestType: qbtypes.RequestTypeScalar,
CompositeQuery: qbtypes.CompositeQuery{
Queries: []qbtypes.QueryEnvelope{
{Type: qbtypes.QueryTypeBuilder, Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{Name: "A"}},
{Type: qbtypes.QueryTypeBuilder, Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{Name: "B"}},
{Type: qbtypes.QueryTypeFormula, Spec: qbtypes.QueryBuilderFormula{Name: "F1", Expression: "A + B"}},
},
},
}
out, err := q.applyFormulas(testCase.ctx, results, req)
require.ErrorIs(t, err, testCase.expectedCause)
assert.Nil(t, out, "the request must fail, and not return the other results without the formula")
typ, _, _, _, _, _ := errors.Unwrapb(err)
assert.Equal(t, testCase.expectedType, typ.String(), "the error type decides the status of the response")
})
}
}
func TestPostProcessMetricQuery_LimitRanksByReducedValue(t *testing.T) {
q := &querier{
logger: instrumentationtest.New().Logger(),

View File

@@ -2,11 +2,14 @@ package querybuildertypesv5
import (
"bytes"
"context"
"fmt"
"math"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"slices"
@@ -166,15 +169,27 @@ type aggregationRef struct {
Alias *string // Alias-based reference (e.g., A.my_alias)
}
// seriesLookup provides lookup for series data.
// seriesEntry is one series of a variable.
type seriesEntry struct {
labels []*Label
// index of the series in its aggregation bucket
position int
data map[int64]float64 // timestamp -> value
}
// keySetIndex holds the series of a variable that share one set of label keys.
type keySetIndex struct {
keys []string // sorted label key names
// value signature (see valueSignature) -> the first series in the bucket
// with those values
series map[string]*seriesEntry
}
// seriesLookup provides lookup for series data, grouped by variable. A variable
// has one keySetIndex for each set of label keys among its series. A group by
// gives every series the same keys, so there is usually one.
type seriesLookup struct {
// seriesKey -> timestamp -> value
data map[string]map[int64]float64
// seriesKey -> original series for metadata preservation
seriesMetadata map[string]*TimeSeries
// maps a variable to its series keys, letting evaluation iterate a single
// variable's series directly.
variableToSeriesKeys map[string][]string
byVariable map[string][]*keySetIndex
}
// FormulaEvaluator handles formula evaluation b/w time series from different aggregations
@@ -230,6 +245,12 @@ type FormulaEvaluator struct {
timestampPool sync.Pool
valuesPool sync.Pool
// tsSetPool holds map[int64]struct{} scratch maps used to build the union of
// timestamps for a label set.
tsSetPool sync.Pool
// matchedPool holds []map[int64]float64 scratch slices indexed by variable
// position, holding each variable's matched series data for a label set.
matchedPool sync.Pool
}
// NewFormulaEvaluator creates a formula evaluator.
@@ -283,6 +304,14 @@ func NewFormulaEvaluator(expressionStr string, canDefaultZero map[string]bool) (
evaluator.valuesPool.New = func() any {
return make(map[string]any, len(evaluator.variables))
}
evaluator.tsSetPool.New = func() any {
return make(map[int64]struct{}, 512)
}
nVars := len(evaluator.variables)
evaluator.matchedPool.New = func() any {
s := make([]map[int64]float64, 0, nVars)
return &s
}
return evaluator, nil
}
@@ -324,65 +353,79 @@ func parseAggregationReference(variable string) (aggregationRef, error) {
}
// EvaluateFormula processes multiple time series with proper aggregation handling.
func (fe *FormulaEvaluator) EvaluateFormula(timeSeriesData map[string]*TimeSeriesData) ([]*TimeSeries, error) {
// When ctx is done it stops between two label sets of the result and returns
// the error of ctx. Building the lookup is not interrupted.
func (fe *FormulaEvaluator) EvaluateFormula(ctx context.Context, timeSeriesData map[string]*TimeSeriesData) ([]*TimeSeries, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
// Build lookup structures for all referenced aggregations
lookup := fe.buildSeriesLookup(timeSeriesData)
// Find all unique label combinations across referenced series
uniqueLabelSets := fe.findUniqueLabelSets(lookup)
// Work per label-set is cheap enough that spawning a goroutine per item
// costs more in scheduler signaling than it saves in parallelism.
const numWorkers = 4
workCh := make(chan []*Label, len(uniqueLabelSets))
resultChan := make(chan *TimeSeries, len(uniqueLabelSets))
n := len(uniqueLabelSets)
if n == 0 {
return nil, nil
}
var wg sync.WaitGroup
wg.Add(numWorkers)
for range numWorkers {
go func() {
defer wg.Done()
for labels := range workCh {
series := fe.evaluateForLabelSet(labels, lookup)
if series != nil && len(series.Values) > 0 {
resultChan <- series
// Each label set is evaluated independently into its own slot, so we can write
// results without any synchronization and compact afterwards. This avoids the
// per-label-set goroutine + semaphore + channel churn that previously
// dominated the profile (runtime.pthread_cond_signal).
results := make([]*TimeSeries, n)
// For small inputs the goroutine machinery costs more than it saves.
const parallelThreshold = 8
if n < parallelThreshold {
for i, labelSet := range uniqueLabelSets {
results[i] = fe.evaluateForLabelSet(labelSet, lookup)
}
} else {
workers := min(runtime.GOMAXPROCS(0), n)
// A shared cursor hands out label-set indices to a fixed pool of workers,
// balancing load (series sizes vary) with a single atomic add per item.
var next atomic.Int64
var wg sync.WaitGroup
wg.Add(workers)
for range workers {
go func() {
defer wg.Done()
for {
i := int(next.Add(1)) - 1
if i >= n || ctx.Err() != nil {
return
}
results[i] = fe.evaluateForLabelSet(uniqueLabelSets[i], lookup)
}
}
}()
}()
}
wg.Wait()
}
for _, labelSet := range uniqueLabelSets {
workCh <- labelSet
if err := ctx.Err(); err != nil {
return nil, err
}
close(workCh)
wg.Wait()
close(resultChan)
resultSeries := make([]*TimeSeries, 0, len(uniqueLabelSets))
for series := range resultChan {
resultSeries = append(resultSeries, series)
// Compact non-empty results in place (results[j] is read before it is
// overwritten, since j <= i throughout).
resultSeries := results[:0]
for _, series := range results {
if series != nil && len(series.Values) > 0 {
resultSeries = append(resultSeries, series)
}
}
return resultSeries, nil
}
// buildSeriesLookup creates lookup structure for all referenced aggregations.
// buildSeriesLookup creates the per-variable matching index for all referenced
// aggregations.
func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSeriesData) *seriesLookup {
lookup := &seriesLookup{
// data is a map of series key to timestamp to value
// series key is a unique identifier for a series
// timestamp is the timestamp of the value
// value is the value of the series at the timestamp
data: make(map[string]map[int64]float64),
// seriesMetadata is a map of series key to series metadata
// series metadata is the metadata of the series
// this is used to preserve the original label structure and metadata
// when the series is returned to the caller
// It's also used for finding matching series for a variable
seriesMetadata: make(map[string]*TimeSeries),
variableToSeriesKeys: make(map[string][]string),
byVariable: make(map[string][]*keySetIndex, len(fe.aggRefs)),
}
for variable, aggRef := range fe.aggRefs {
@@ -403,13 +446,10 @@ func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSer
continue
}
// Find the specific aggregation bucket
// Now, that we have the data for the query, we look for the specific aggregation bucket
// referenced in the formula expression.
// For example, if the formula expression is `B.2`, the above `data` would be the
// time series data for the query B.
// The following code will find the aggregation at the index 2
// so we can build the series key -> timestamp -> value map for the expr evaluation
// Find the specific aggregation bucket referenced in the formula
// expression. For example, if the expression is `B.2`, the above `data`
// is the time series data for query B and we pick the aggregation at
// index 2.
var targetBucket *AggregationBucket
for _, bucket := range data.Aggregations {
if aggRef.Index != nil && bucket.Index == *aggRef.Index {
@@ -426,64 +466,128 @@ func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSer
continue
}
// Process all series in the target bucket
for seriesIdx, series := range targetBucket.Series {
seriesKey := fe.buildSeriesKey(variable, seriesIdx, series.Labels)
var indexes []*keySetIndex
byKeys := make(map[string]*keySetIndex)
var index *keySetIndex
// Initialize timestamp map
if _, exists := lookup.data[seriesKey]; !exists {
lookup.data[seriesKey] = make(map[int64]float64, len(series.Values))
lookup.seriesMetadata[seriesKey] = series
lookup.variableToSeriesKeys[variable] = append(lookup.variableToSeriesKeys[variable], seriesKey)
// Process all series in the target bucket.
for position, series := range targetBucket.Series {
// Consecutive series almost always have the same keys.
if index == nil || !hasExactKeys(series.Labels, index.keys) {
keys := make([]string, len(series.Labels))
for i, label := range series.Labels {
keys[i] = label.Key.Name
}
slices.Sort(keys)
keysSig := keysSignature(keys)
index = byKeys[keysSig]
if index == nil {
sizeHint := 0
if len(indexes) == 0 {
// A group by gives every series the same keys, so the
// first key set usually holds all of them.
sizeHint = len(targetBucket.Series)
}
index = &keySetIndex{keys: keys, series: make(map[string]*seriesEntry, sizeHint)}
byKeys[keysSig] = index
indexes = append(indexes, index)
}
}
// Store all timestamp-value pairs
signature, _ := valueSignature(series.Labels, index.keys)
if _, exists := index.series[signature]; exists {
// The first series with a label set wins, matching the original
// "first match" behaviour; a later duplicate's points are ignored.
continue
}
data := make(map[int64]float64, len(series.Values))
for _, value := range series.Values {
lookup.data[seriesKey][value.Timestamp] = value.Value
data[value.Timestamp] = value.Value
}
index.series[signature] = &seriesEntry{labels: series.Labels, position: position, data: data}
}
lookup.byVariable[variable] = indexes
}
return lookup
}
// buildSeriesKey creates a unique key for a series within a specific aggregation.
func (fe *FormulaEvaluator) buildSeriesKey(variable string, seriesIndex int, labels []*Label) string {
// Create a deterministic key that includes variable and label information
// Why is variable name needed?
// Because we need to maintain if a certain series belongs to a query.
// The variable name here is the name of the query.
// Why is series index needed?
// Since we support multiple aggregations in the same query, we need to
// make use the series index to differentiate between series from different aggregations.
// Perhaps, we can reduce the allocations here and use the hash of the variable and series index
// to create a unique key.
// However, the number of labels and series from query result should be small,
// and not be a bottleneck.
// So, we can keep it simple for now.
var keyParts []string
keyParts = append(keyParts, variable)
keyParts = append(keyParts, strconv.Itoa(seriesIndex))
// Sort labels by key name for consistent ordering
sortedLabels := make([]*Label, len(labels))
copy(sortedLabels, labels)
slices.SortFunc(sortedLabels, func(i, j *Label) int {
if i.Key.Name < j.Key.Name {
return -1
// hasExactKeys reports whether the key names of labels are exactly keys.
func hasExactKeys(labels []*Label, keys []string) bool {
if len(labels) != len(keys) {
return false
}
for _, key := range keys {
if _, ok := findLabelValue(labels, key); !ok {
return false
}
if i.Key.Name > j.Key.Name {
return 1
}
return 0
})
}
return true
}
for _, label := range sortedLabels {
keyParts = append(keyParts, fmt.Sprintf("%s=%v", label.Key.Name, label.Value))
// writeSized writes s with its length first, so that the end of s is known
// without a separator, which s could contain.
func writeSized(sb *strings.Builder, s string) {
sb.WriteString(strconv.Itoa(len(s)))
sb.WriteByte(':')
sb.WriteString(s)
}
// keysSignature is the same for two sorted lists of key names exactly when the
// names are the same.
func keysSignature(keys []string) string {
var sb strings.Builder
for _, key := range keys {
writeSized(&sb, key)
}
return sb.String()
}
// valueSignature returns the values of labels for keys, in the order of keys.
// It is the same for two label sets exactly when each value has the same type
// and the same value, so the string "200" and the number 200 differ. It returns
// false when labels has no value for one of the keys.
func valueSignature(labels []*Label, keys []string) (string, bool) {
// Checked first, so that a label set without the keys costs no allocation.
for _, key := range keys {
if _, ok := findLabelValue(labels, key); !ok {
return "", false
}
}
return strings.Join(keyParts, "|")
var sb strings.Builder
sb.Grow(len(keys) * 24)
for _, key := range keys {
value, _ := findLabelValue(labels, key)
switch v := value.(type) {
case string:
sb.WriteByte('s')
writeSized(&sb, v)
continue
// -0 and 0 are equal values with a different text.
case float64:
value = v + 0
case float32:
value = v + 0
}
sb.WriteByte('o')
writeSized(&sb, fmt.Sprintf("%T:%v", value, value))
}
return sb.String(), true
}
// findLabelValue returns the value for key in labels, scanning linearly since
// label sets are small.
func findLabelValue(labels []*Label, key string) (any, bool) {
for _, label := range labels {
if label.Key.Name == key {
return label.Value, true
}
}
return nil, false
}
// perhaps this could be named better. The job of this function is to find all unique and supersets
@@ -497,131 +601,176 @@ func (fe *FormulaEvaluator) buildSeriesKey(variable string, seriesIndex int, lab
// and `{"service": "frontend"}` would be the series with `{"service": "frontend", "operation": "GET /api"}`
// So, we create a set of labels sets that can be termed as candidates for the final result.
func (fe *FormulaEvaluator) findUniqueLabelSets(lookup *seriesLookup) [][]*Label {
var allLabelSets [][]*Label
// Collect all label sets from series metadata
for _, series := range lookup.seriesMetadata {
allLabelSets = append(allLabelSets, series.Labels)
type candidates struct {
keys []string
// value signature -> labels
labelSets map[string][]*Label
}
// sort the label sets by the number of labels in descending order
slices.SortFunc(allLabelSets, func(i, j []*Label) int {
if len(i) > len(j) {
return -1
}
if len(i) < len(j) {
return 1
}
return 0
})
// Find unique label sets using proper label comparison
var uniqueSets [][]*Label
var uniqueMaps []map[string]any
for _, labelSet := range allLabelSets {
isUnique := true
for _, uniqueMap := range uniqueMaps {
if isSubset(uniqueMap, labelSet) {
isUnique = false
break
// Merge the label sets of all variables by key set. Two variables with the
// same label set (e.g. A and B grouped identically) give one candidate.
byKeys := make(map[string]*candidates)
for _, indexes := range lookup.byVariable {
for _, index := range indexes {
keysSig := keysSignature(index.keys)
group := byKeys[keysSig]
if group == nil {
group = &candidates{keys: index.keys, labelSets: make(map[string][]*Label, len(index.series))}
byKeys[keysSig] = group
}
for signature, entry := range index.series {
if _, exists := group.labelSets[signature]; !exists {
group.labelSets[signature] = entry.labels
}
}
}
if isUnique {
uniqueSets = append(uniqueSets, labelSet)
uniqueMaps = append(uniqueMaps, labelsToMap(labelSet))
}
// A label set is a subset of another one only when its keys are a subset of
// the other's keys, so only a label set with more keys can remove it. A label
// set that is removed here still removes its own subsets, because the label
// set that removed it has them as subsets too.
for _, larger := range byKeys {
for _, smaller := range byKeys {
if smaller == larger || !keysSubset(smaller.keys, larger.keys) {
continue
}
for _, labels := range larger.labelSets {
if signature, ok := valueSignature(labels, smaller.keys); ok {
delete(smaller.labelSets, signature)
}
}
}
}
count := 0
for _, group := range byKeys {
count += len(group.labelSets)
}
if count == 0 {
return nil
}
uniqueSets := make([][]*Label, 0, count)
for _, group := range byKeys {
for _, labels := range group.labelSets {
uniqueSets = append(uniqueSets, labels)
}
}
return uniqueSets
}
func labelsToMap(labels []*Label) map[string]any {
m := make(map[string]any, len(labels))
for _, label := range labels {
m[label.Key.Name] = label.Value
// keysSubset reports whether the sorted key set a is a subset of the sorted key
// set b.
func keysSubset(a, b []string) bool {
if len(a) > len(b) {
return false
}
return m
}
// isSubset reports whether every label in subset is present with the same value in
// supersetMap (i.e. subset ⊆ superset).
func isSubset(supersetMap map[string]any, subset []*Label) bool {
for _, label := range subset {
if val, ok := supersetMap[label.Key.Name]; !ok || val != label.Value {
i := 0
for _, x := range a {
for i < len(b) && b[i] < x {
i++
}
if i >= len(b) || b[i] != x {
return false
}
i++
}
return true
}
// evaluateForLabelSet performs formula evaluation for a specific label set.
func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *seriesLookup) *TimeSeries {
// Find matching series for each variable
variableData := make(map[string]map[int64]float64)
// not every series would have a value for every timestamp
// so we need to collect all timestamps from the series that have a value
// for the variable
var allTimestamps = make(map[int64]struct{})
nVars := len(fe.variables)
// targetLabels is fixed for this call, so build its lookup once and reuse it
// across every series comparison below.
targetMap := labelsToMap(targetLabels)
// matched[i] holds the timestamp->value data for fe.variables[i], or nil if
// no series matched. Indexed by position to avoid a per-call map.
mptr := fe.matchedPool.Get().(*[]map[int64]float64)
matched := *mptr
if cap(matched) < nVars {
matched = make([]map[int64]float64, nVars)
} else {
matched = matched[:nVars]
for i := range matched {
matched[i] = nil
}
}
defer func() {
*mptr = matched[:0]
fe.matchedPool.Put(mptr)
}()
for variable := range fe.aggRefs {
// only this variable's series.
for _, seriesKey := range lookup.variableToSeriesKeys[variable] {
if isSubset(targetMap, lookup.seriesMetadata[seriesKey].Labels) {
if timestampData, exists := lookup.data[seriesKey]; exists {
variableData[variable] = timestampData
// Collect all timestamps
for ts := range timestampData {
allTimestamps[ts] = struct{}{}
}
break // Found matching series for this variable
}
// not every series has a value for every timestamp, so collect the union of
// timestamps across the matched series.
allTimestamps := fe.tsSetPool.Get().(map[int64]struct{})
clear(allTimestamps)
defer fe.tsSetPool.Put(allTimestamps)
for i, variable := range fe.variables {
// The series of a variable to use is the first one in its bucket whose
// labels are a subset of the target. Each key set has at most one such
// series: the one with the target's values for those keys.
var match *seriesEntry
for _, index := range lookup.byVariable[variable] {
signature, ok := valueSignature(targetLabels, index.keys)
if !ok {
continue
}
if entry, exists := index.series[signature]; exists && (match == nil || entry.position < match.position) {
match = entry
}
}
if match != nil {
matched[i] = match.data
for ts := range match.data {
allTimestamps[ts] = struct{}{}
}
}
}
// Convert timestamps to sorted slice
// Convert timestamps to a sorted slice.
tsPtr := fe.timestampPool.Get().(*[]int64)
timestamps := (*tsPtr)[:0]
for ts := range allTimestamps {
timestamps = append(timestamps, ts)
}
slices.Sort(timestamps)
defer func() {
*tsPtr = timestamps[:0]
fe.timestampPool.Put(tsPtr)
}()
for ts := range allTimestamps {
timestamps = append(timestamps, ts)
if len(timestamps) == 0 {
return nil
}
slices.Sort(timestamps)
// backing slab-allocates all values in one block; resultValues holds interior
// pointers into it. Fixed length and never appended to, so it never moves.
backing := make([]TimeSeriesValue, len(timestamps))
resultValues := make([]*TimeSeriesValue, 0, len(timestamps))
n := 0
values := fe.valuesPool.Get().(map[string]any)
defer fe.valuesPool.Put(values)
for _, timestamp := range timestamps {
// Clear previous values
for k := range values {
delete(values, k)
}
// Allocate the values backing array once (cap = number of timestamps); the
// returned pointers reference into it, so no per-point allocation is needed.
backing := make([]TimeSeriesValue, 0, len(timestamps))
// Collect values for this timestamp
for _, timestamp := range timestamps {
clear(values)
// Collect values for this timestamp. fe.variables may contain a variable
// more than once (e.g. "A * B - A"); values is keyed by name, but each
// data-present occurrence still increments validCount, matching the target
// count of len(fe.variables) below.
validCount := 0
for _, variable := range fe.variables {
if varData, exists := variableData[variable]; exists {
if value, exists := varData[timestamp]; exists {
for i, variable := range fe.variables {
if data := matched[i]; data != nil {
if value, exists := data[timestamp]; exists {
values[variable] = value
validCount++
}
}
}
// Apply default zeros where allowed
// Apply default zeros where allowed. A defaulted variable is only counted
// once even if it appears multiple times, since the second occurrence finds
// the value already set.
for _, variable := range fe.variables {
if _, exists := values[variable]; !exists && fe.canDefaultZero[variable] {
values[variable] = 0.0
@@ -629,12 +778,11 @@ func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *s
}
}
// Skip if we don't have all required variables
if validCount != len(fe.variables) {
// Skip if we don't have all required variables.
if validCount != nVars {
continue
}
// Evaluate expression
result, err := fe.expression.Evaluate(values)
if err != nil {
continue
@@ -645,19 +793,22 @@ func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *s
continue
}
backing[n] = TimeSeriesValue{
backing = append(backing, TimeSeriesValue{
Timestamp: timestamp,
Value: value,
}
resultValues = append(resultValues, &backing[n])
n++
})
}
if len(resultValues) == 0 {
if len(backing) == 0 {
return nil
}
// Preserve original label structure and metadata
resultValues := make([]*TimeSeriesValue, len(backing))
for i := range backing {
resultValues[i] = &backing[i]
}
// Preserve the original label structure for the result series.
resultLabels := make([]*Label, len(targetLabels))
copy(resultLabels, targetLabels)

View File

@@ -1,6 +1,7 @@
package querybuildertypesv5
import (
"context"
"fmt"
"testing"
@@ -85,7 +86,7 @@ func BenchmarkFormulaEvaluator_10k_Series_300_Points(b *testing.B) {
numSeries, numPoints, totalDataPoints)
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(timeSeriesData)
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
@@ -116,7 +117,7 @@ func BenchmarkFormulaEvaluator_1k_Series_300_Points(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(timeSeriesData)
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
@@ -142,7 +143,7 @@ func BenchmarkFormulaEvaluator_5k_Series_300_Points(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(timeSeriesData)
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
@@ -170,7 +171,7 @@ func BenchmarkFormulaEvaluator_10k_Series_Complex(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(timeSeriesData)
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
@@ -198,7 +199,7 @@ func BenchmarkFormulaEvaluator_Memory_Reuse(b *testing.B) {
// Run multiple times to test pool reuse
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(timeSeriesData)
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
@@ -264,3 +265,80 @@ func BenchmarkFormulaEvaluator_EvaluationOnly(b *testing.B) {
}
}
}
// BenchmarkFormulaEvaluator_ScalarGroups evaluates A / B on the series of a
// scalar request, which have one point each. The group counts are the ones
// where a scan of all series for each group does not end in a useful time.
func BenchmarkFormulaEvaluator_ScalarGroups(b *testing.B) {
label := func(name, value string) *Label {
return &Label{Key: telemetrytypes.TelemetryFieldKey{Name: name}, Value: value}
}
series := func(value float64, labels ...*Label) *TimeSeries {
return &TimeSeries{Labels: labels, Values: []*TimeSeriesValue{{Timestamp: 0, Value: value}}}
}
data := func(queryName string, series []*TimeSeries) *TimeSeriesData {
return &TimeSeriesData{QueryName: queryName, Aggregations: []*AggregationBucket{{Index: 0, Series: series}}}
}
// one query grouped by a key with a distinct value in each group, and one total
groupedAndTotal := func(groups int) map[string]*TimeSeriesData {
grouped := make([]*TimeSeries, groups)
for i := range grouped {
grouped[i] = series(float64(i+1), label("url", fmt.Sprintf("/shop/v2/products/%09d/variations", i)))
}
return map[string]*TimeSeriesData{"A": data("A", grouped), "B": data("B", []*TimeSeries{series(1000)})}
}
// both queries grouped by the same key, with the same values
sameKey := func(groups int) map[string]*TimeSeriesData {
left, right := make([]*TimeSeries, groups), make([]*TimeSeries, groups)
for i := range left {
left[i] = series(float64(i+1), label("url", fmt.Sprintf("/shop/v2/products/%09d/variations", i)))
right[i] = series(float64(i+2), label("url", fmt.Sprintf("/shop/v2/products/%09d/variations", i)))
}
return map[string]*TimeSeriesData{"A": data("A", left), "B": data("B", right)}
}
// one query where half of the series have one more label, and one total
mixedKeySets := func(groups int) map[string]*TimeSeriesData {
mixed := make([]*TimeSeries, groups)
for i := range mixed {
if i%2 == 0 {
mixed[i] = series(float64(i+1), label("svc", fmt.Sprintf("service-%09d", i)))
} else {
mixed[i] = series(float64(i+1), label("svc", fmt.Sprintf("service-%09d", i)), label("op", "GET"))
}
}
return map[string]*TimeSeriesData{"A": data("A", mixed), "B": data("B", []*TimeSeries{series(1000)})}
}
benchmarks := []struct {
name string
groups int
input func(groups int) map[string]*TimeSeriesData
}{
{name: "GroupedAndTotal_100k", groups: 100_000, input: groupedAndTotal},
{name: "GroupedAndTotal_627k", groups: 626_950, input: groupedAndTotal},
{name: "SameKey_100k", groups: 100_000, input: sameKey},
{name: "MixedKeySets_100k", groups: 100_000, input: mixedKeySets},
}
for _, benchmark := range benchmarks {
b.Run(benchmark.name, func(b *testing.B) {
timeSeriesData := benchmark.input(benchmark.groups)
evaluator, err := NewFormulaEvaluator("A / B", map[string]bool{"A": false, "B": false})
require.NoError(b, err)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
result, err := evaluator.EvaluateFormula(context.Background(), timeSeriesData)
if err != nil {
b.Fatal(err)
}
if len(result) != benchmark.groups {
b.Fatalf("Expected %d result series, got %d", benchmark.groups, len(result))
}
}
})
}
}

View File

@@ -1,6 +1,7 @@
package querybuildertypesv5
import (
"context"
"testing"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
@@ -249,7 +250,7 @@ func TestBasicFormulaEvaluation(t *testing.T) {
evaluator, err := NewFormulaEvaluator(tt.expression, map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tt.tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tt.tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -305,7 +306,7 @@ func TestErrorRateCalculation(t *testing.T) {
evaluator, err := NewFormulaEvaluator("B/A", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -360,7 +361,7 @@ func TestNoGroupKeysOnLeftSide(t *testing.T) {
evaluator, err := NewFormulaEvaluator("B/A", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -450,7 +451,7 @@ func TestSameGroupKeys(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A/B", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -540,7 +541,7 @@ func TestGroupKeysDifferentValues(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A/B", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -618,7 +619,7 @@ func TestLeftSideSuperset(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A/B", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -677,7 +678,7 @@ func TestNoDefaultZero(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A + B", map[string]bool{"A": false, "B": false})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
// Should have no result series since labels don't match and no default zero
@@ -727,7 +728,7 @@ func TestMixedQueries(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A / B", map[string]bool{"A": true, "B": true, "C": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -832,7 +833,7 @@ func TestComplexExpression(t *testing.T) {
evaluator, err := NewFormulaEvaluator("A/B + C", map[string]bool{"A": true, "B": true, "C": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -1003,7 +1004,7 @@ func TestCaseInsensitiveQueryNames(t *testing.T) {
evaluator, err := NewFormulaEvaluator(tt.expression, map[string]bool{"a": true, "A": true, "b": true, "B": true, "c": true, "C": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tt.tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tt.tsData)
require.NoError(t, err)
require.NotNil(t, result)
@@ -1041,7 +1042,7 @@ func TestAbsValueExpression(t *testing.T) {
evaluator, err := NewFormulaEvaluator("abs(A) + abs(B)", map[string]bool{"A": true, "B": true})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(tsData)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, 1, len(result))
@@ -1051,3 +1052,78 @@ func TestAbsValueExpression(t *testing.T) {
assert.Equal(t, 15.0, series.Values[0].Value) // |−10| + |5| = 15
assert.Equal(t, 24.0, series.Values[1].Value) // |20| + |−4| = 24
}
func TestEvaluateFormula_SameTextDifferentType_DoesNotMatch(t *testing.T) {
tsData := map[string]*TimeSeriesData{
"A": createFormulaTestTimeSeriesData("A", []*TimeSeries{{
Labels: []*Label{{Key: telemetrytypes.TelemetryFieldKey{Name: "status"}, Value: "404"}},
Values: []*TimeSeriesValue{{Timestamp: 1, Value: 10}},
}}),
"B": createFormulaTestTimeSeriesData("B", []*TimeSeries{{
Labels: []*Label{{Key: telemetrytypes.TelemetryFieldKey{Name: "status"}, Value: float64(404)}},
Values: []*TimeSeriesValue{{Timestamp: 1, Value: 5}},
}}),
}
evaluator, err := NewFormulaEvaluator("A / B", map[string]bool{"A": false, "B": false})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
assert.Empty(t, result, "the string 404 and the number 404 are different label values, so no series has both A and B")
}
func TestEvaluateFormula_MixedKeySets_FirstSeriesInBucketMatches(t *testing.T) {
label := func(name, value string) *Label {
return &Label{Key: telemetrytypes.TelemetryFieldKey{Name: name}, Value: value}
}
point := func(value float64) []*TimeSeriesValue {
return []*TimeSeriesValue{{Timestamp: 1, Value: value}}
}
testCases := []struct {
name string
// the series of B, whose labels have different key sets
b []*TimeSeries
expected float64
}{
{
name: "SeriesWithLabelFirst",
b: []*TimeSeries{
{Labels: []*Label{label("svc", "cart")}, Values: point(10)},
{Labels: nil, Values: point(1000)},
},
expected: 10,
},
{
// the key set of svc comes first in the bucket, and its matching series comes last
name: "SeriesWithoutLabelsBeforeTheMatchOfAnEarlierKeySet",
b: []*TimeSeries{
{Labels: []*Label{label("svc", "checkout")}, Values: point(1)},
{Labels: nil, Values: point(1000)},
{Labels: []*Label{label("svc", "cart")}, Values: point(10)},
},
expected: 0.1,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
tsData := map[string]*TimeSeriesData{
"A": createFormulaTestTimeSeriesData("A", []*TimeSeries{
{Labels: []*Label{label("svc", "cart"), label("op", "add")}, Values: point(100)},
}),
"B": createFormulaTestTimeSeriesData("B", testCase.b),
}
evaluator, err := NewFormulaEvaluator("A / B", map[string]bool{"A": false, "B": false})
require.NoError(t, err)
result, err := evaluator.EvaluateFormula(context.Background(), tsData)
require.NoError(t, err)
require.Len(t, result, 1, "the only label set that is not a subset of another one is svc=cart, op=add")
require.Len(t, result[0].Values, 1)
assert.Equal(t, testCase.expected, result[0].Values[0].Value, "A must be divided by the first series of B in the bucket whose labels are in svc=cart, op=add")
})
}
}