Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

34.3 KB
Raw Blame
package tracestelemetryschema

import (
	"context"
	"testing"
	"time"

	"github.com/SigNoz/signoz/pkg/querybuilder"
	qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
	"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
	"github.com/SigNoz/signoz/pkg/types/telemetrytypes/telemetrytypestest"
	"github.com/huandu/go-sqlbuilder"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

var (
	attrJSONRelease = time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)

	attrWindowBefore   = [2]uint64{tsNano(2024, 1), tsNano(2024, 6)}
	attrWindowAfter    = [2]uint64{tsNano(2025, 6), tsNano(2025, 7)}
	attrWindowStraddle = [2]uint64{tsNano(2024, 6), tsNano(2025, 6)}
)

func readSQL(ctx context.Context, storage qbtypes.Storage, startNs, endNs uint64, key *telemetrytypes.TelemetryFieldKey) (string, error) {
	read, err := storage.Read(ctx, qbtypes.QueryInfo{StartNs: startNs, EndNs: endNs, TraceAttrsJSONOn: true}, key)
	return read.SQL, err
}

func tsNano(y int, m time.Month) uint64 {
	return uint64(time.Date(y, m, 1, 0, 0, 0, 0, time.UTC).UnixNano())
}

func attrKey(name string, dt telemetrytypes.FieldDataType, evo []*telemetrytypes.EvolutionEntry) telemetrytypes.TelemetryFieldKey {
	return telemetrytypes.TelemetryFieldKey{
		Name:          name,
		FieldContext:  telemetrytypes.FieldContextAttribute,
		FieldDataType: dt,
		Evolutions:    evo,
	}
}

// TestFieldForAttributeJSONEvolution asserts the value expression across the rollout window:
// before release the legacy Map lookup (byte-for-byte today), after release the type-aware JSON
// cast, straddling a dual-read multiIf with the JSON column first.
func TestFieldForAttributeJSONEvolution(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	testCases := []struct {
		name     string
		dataType telemetrytypes.FieldDataType
		window   [2]uint64
		expected string
	}{
		{"string before -> map", telemetrytypes.FieldDataTypeString, attrWindowBefore, "attributes_string['user.id']"},
		{"string after -> json", telemetrytypes.FieldDataTypeString, attrWindowAfter, "attributes.`user.id`::String"},
		{"string straddle -> dual", telemetrytypes.FieldDataTypeString, attrWindowStraddle, "multiIf(attributes.`user.id` IS NOT NULL, attributes.`user.id`::String, mapContains(attributes_string, 'user.id'), attributes_string['user.id'], NULL)"},
		{"number before -> map", telemetrytypes.FieldDataTypeNumber, attrWindowBefore, "attributes_number['user.id']"},
		{"number after -> json", telemetrytypes.FieldDataTypeNumber, attrWindowAfter, "toFloat64OrNull(attributes.`user.id`::String)"},
		{"number straddle -> dual", telemetrytypes.FieldDataTypeNumber, attrWindowStraddle, "multiIf(toFloat64OrNull(attributes.`user.id`::String) IS NOT NULL, toFloat64OrNull(attributes.`user.id`::String), mapContains(attributes_number, 'user.id'), attributes_number['user.id'], NULL)"},
		{"int64 after -> json", telemetrytypes.FieldDataTypeInt64, attrWindowAfter, "toFloat64OrNull(attributes.`user.id`::String)"},
		{"bool before -> map", telemetrytypes.FieldDataTypeBool, attrWindowBefore, "attributes_bool['user.id']"},
		{"bool after -> json", telemetrytypes.FieldDataTypeBool, attrWindowAfter, "if(dynamicType(attributes.`user.id`) = 'Bool', accurateCastOrNull(attributes.`user.id`, 'Bool'), NULL)"},
		{"bool straddle -> dual", telemetrytypes.FieldDataTypeBool, attrWindowStraddle, "multiIf(if(dynamicType(attributes.`user.id`) = 'Bool', accurateCastOrNull(attributes.`user.id`, 'Bool'), NULL) IS NOT NULL, if(dynamicType(attributes.`user.id`) = 'Bool', accurateCastOrNull(attributes.`user.id`, 'Bool'), NULL), mapContains(attributes_bool, 'user.id'), attributes_bool['user.id'], NULL)"},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			key := attrKey("user.id", tc.dataType, evo)
			got, err := readSQL(ctx, storage, tc.window[0], tc.window[1], &key)
			require.NoError(t, err)
			assert.Equal(t, tc.expected, got)
		})
	}
}

// TestFieldForAttributeNoEvolutionParity proves the JSON column is untouched until the evolution
// entry is registered: a key with no evolutions resolves to the Map column for every window.
func TestFieldForAttributeNoEvolutionParity(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)

	for _, dt := range []struct {
		dataType telemetrytypes.FieldDataType
		expected string
	}{
		{telemetrytypes.FieldDataTypeString, "attributes_string['user.id']"},
		{telemetrytypes.FieldDataTypeNumber, "attributes_number['user.id']"},
		{telemetrytypes.FieldDataTypeBool, "attributes_bool['user.id']"},
	} {
		key := attrKey("user.id", dt.dataType, nil)
		got, err := readSQL(ctx, storage, attrWindowAfter[0], attrWindowAfter[1], &key)
		require.NoError(t, err)
		assert.Equal(t, dt.expected, got, "no evolution entry must keep the Map path")
	}
}

// TestAttributeJSONFlagOffParity proves the evolution entry alone does not switch reads to the
// JSON column: with use_trace_attributes_json off, the read and every condition are the Map's for
// every window.
func TestAttributeJSONFlagOffParity(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)
	windows := map[string][2]uint64{
		"BeforeRelease":     attrWindowBefore,
		"AfterRelease":      attrWindowAfter,
		"StraddlingRelease": attrWindowStraddle,
	}

	testCases := []struct {
		name     string
		operator qbtypes.FilterOperator
		value    any
		expected string
	}{
		{"Equal", qbtypes.FilterOperatorEqual, float64(1), "WHERE (toFloat64(attributes_number['user.id']) = ? AND mapContains(attributes_number, 'user.id'))"},
		{"NotEqual", qbtypes.FilterOperatorNotEqual, float64(1), "WHERE toFloat64(ifNull(attributes_number['user.id'], 0)) <> ?"},
		{"Exists", qbtypes.FilterOperatorExists, nil, "WHERE mapContains(attributes_number, 'user.id')"},
		{"NotExists", qbtypes.FilterOperatorNotExists, nil, "WHERE NOT mapContains(attributes_number, 'user.id')"},
	}

	for windowName, window := range windows {
		q := qbtypes.QueryInfo{StartNs: window[0], EndNs: window[1]}
		key := attrKey("user.id", telemetrytypes.FieldDataTypeNumber, evo)

		t.Run(windowName+"_Read", func(t *testing.T) {
			read, err := storage.Read(ctx, q, &key)
			require.NoError(t, err)
			assert.Equal(t, qbtypes.Read{
				SQL:        "attributes_number['user.id']",
				Presence:   "mapContains(attributes_number, 'user.id')",
				Absence:    "NOT mapContains(attributes_number, 'user.id')",
				WhenAbsent: qbtypes.AbsentIsSentinel,
			}, read)
		})

		for _, testCase := range testCases {
			t.Run(windowName+"_"+testCase.name, func(t *testing.T) {
				sb := sqlbuilder.NewSelectBuilder()
				conds, _, err := querybuilder.Conditions(ctx, q, storage, &key, testCase.operator, testCase.value, map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, false, sb)
				require.NoError(t, err)
				sb.Where(conds...)
				sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
				assert.Equal(t, testCase.expected, sql)
			})
		}
	}
}

// TestConditionForAttributeJSON asserts the emitted WHERE fragment per operator against the JSON
// column (window fully after release). Positive operators carry the raw-path existence guard;
// numeric comparisons keep numeric semantics; existence never tests the ::String cast.
func TestConditionForAttributeJSON(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	testCases := []struct {
		name     string
		key      telemetrytypes.TelemetryFieldKey
		operator qbtypes.FilterOperator
		value    any
		expected string
	}{
		{
			name:     "equal string",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorEqual, value: "admin",
			expected: "(attributes.`user.id`::String = ? AND attributes.`user.id` IS NOT NULL)",
		},
		{
			name:     "not equal string has no exists guard",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorNotEqual, value: "admin",
			expected: "attributes.`user.id`::String <> ?",
		},
		{
			name:     "greater than number",
			key:      attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo),
			operator: qbtypes.FilterOperatorGreaterThan, value: float64(200),
			expected: "toFloat64OrNull(attributes.`http.status_code`::String) > ?",
		},
		{
			name:     "ilike string",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorILike, value: "%adm%",
			expected: "LOWER(attributes.`user.id`::String) LIKE LOWER(?)",
		},
		{
			name:     "exists uses raw path",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorExists, value: nil,
			expected: "attributes.`user.id` IS NOT NULL",
		},
		{
			name:     "not exists uses raw path",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorNotExists, value: nil,
			expected: "attributes.`user.id` IS NULL",
		},
		{
			name:     "in string",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorIn, value: []any{"a", "b"},
			expected: "((attributes.`user.id`::String = ? OR attributes.`user.id`::String = ?) AND attributes.`user.id` IS NOT NULL)",
		},
		{
			name:     "not in string has no exists guard",
			key:      attrKey("user.id", telemetrytypes.FieldDataTypeString, evo),
			operator: qbtypes.FilterOperatorNotIn, value: []any{"a", "b"},
			expected: "(attributes.`user.id`::String <> ? AND attributes.`user.id`::String <> ?)",
		},
		{
			name:     "between number",
			key:      attrKey("latency", telemetrytypes.FieldDataTypeNumber, evo),
			operator: qbtypes.FilterOperatorBetween, value: []any{float64(1), float64(9)},
			expected: "toFloat64OrNull(attributes.`latency`::String) BETWEEN ? AND ?",
		},
		{
			name:     "In_Number",
			key:      attrKey("http.status_code", telemetrytypes.FieldDataTypeNumber, evo),
			operator: qbtypes.FilterOperatorIn, value: []any{float64(200), float64(404)},
			expected: "(toFloat64OrNull(attributes.`http.status_code`::String) = ? OR toFloat64OrNull(attributes.`http.status_code`::String) = ?)",
		},
		{
			name:     "GreaterThan_NumericString",
			key:      attrKey("http.status_code", telemetrytypes.FieldDataTypeNumber, evo),
			operator: qbtypes.FilterOperatorGreaterThan, value: "200",
			expected: "toFloat64OrNull(attributes.`http.status_code`::String) > ?",
		},
		{
			name:     "Equal_NonNumericString_CastsToString",
			key:      attrKey("http.status_code", telemetrytypes.FieldDataTypeNumber, evo),
			operator: qbtypes.FilterOperatorEqual, value: "ok",
			expected: "toString(toFloat64OrNull(attributes.`http.status_code`::String)) = ?",
		},
		{
			name:     "Equal_Bool_CastsToString",
			key:      attrKey("http.status_code", telemetrytypes.FieldDataTypeNumber, evo),
			operator: qbtypes.FilterOperatorEqual, value: true,
			expected: "toString(toFloat64OrNull(attributes.`http.status_code`::String)) = ?",
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			sb := sqlbuilder.NewSelectBuilder()
			conds, _, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &tc.key, tc.operator, tc.value, map[string][]*telemetrytypes.TelemetryFieldKey{tc.key.Name: {&tc.key}}, false, sb)
			require.NoError(t, err)
			sb.Where(conds...)
			sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
			assert.Contains(t, sql, tc.expected)
		})
	}
}

// TestConditionForAttributeJSONNotExistsDualRead covers NOT EXISTS across both homes during the
// dual-read window: it must AND the JSON IS NULL with NOT mapContains so a row present in either
// home is excluded (De Morgan), including rows that predate the JSON column.
func TestConditionForAttributeJSONNotExistsDualRead(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	key := attrKey("user.id", telemetrytypes.FieldDataTypeString, evo)
	sb := sqlbuilder.NewSelectBuilder()
	conds, _, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowStraddle[0], EndNs: attrWindowStraddle[1], TraceAttrsJSONOn: true}, storage, &key, qbtypes.FilterOperatorNotExists, nil, map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, false, sb)
	require.NoError(t, err)
	sb.Where(conds...)
	sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
	// the value multiIf resolves the row's home; NOT EXISTS negates the whole thing to IS NULL
	assert.Contains(t, sql, "IS NULL")
	assert.Contains(t, sql, "attributes.`user.id` IS NOT NULL")
	assert.Contains(t, sql, "mapContains(attributes_string, 'user.id')")
}

// TestColumnExpressionForAttributeJSON covers group-by (coerced to String) and aggregation
// (coerced to Float64) over a JSON attribute after release: both are exists-guarded so an absent
// path is NULL rather than a spurious ”/0, and the numeric branch keeps its toFloat64 coercion.
func TestColumnExpressionForAttributeJSON(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	t.Run("group by string", func(t *testing.T) {
		key := attrKey("user.id", telemetrytypes.FieldDataTypeString, evo)
		got, err := querybuilder.ResolveColumn(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &key, telemetrytypes.FieldDataTypeString, nil)
		require.NoError(t, err)
		assert.Equal(t, "multiIf(attributes.`user.id` IS NOT NULL, attributes.`user.id`::String, mapContains(attributes_string, 'attribute.user.id'), attributes_string['attribute.user.id'], NULL)", got)
	})

	t.Run("aggregation numeric", func(t *testing.T) {
		key := attrKey("latency", telemetrytypes.FieldDataTypeNumber, evo)
		got, err := querybuilder.ResolveColumn(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &key, telemetrytypes.FieldDataTypeFloat64, nil)
		require.NoError(t, err)
		assert.Equal(t, "multiIf(toFloat64OrNull(attributes.`latency`::String) IS NOT NULL, toFloat64OrNull(attributes.`latency`::String), mapContains(attributes_number, 'attribute.latency'), toFloat64(attributes_number['attribute.latency']), NULL)", got)
	})
}

// TestAttributeJSONNoAmbiguityWarning guards against a visible regression: the JSON column is a
// second physical home for the same logical field, not a second logical field, so a plain
// attribute filter must not emit the "ambiguous key" warning.
func TestAttributeJSONNoAmbiguityWarning(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	key := attrKey("user.id", telemetrytypes.FieldDataTypeString, evo)
	sb := sqlbuilder.NewSelectBuilder()
	_, warnings, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &key, qbtypes.FilterOperatorEqual, "x", map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, false, sb)
	require.NoError(t, err)
	assert.Empty(t, warnings, "a plain attribute filter must not emit an ambiguity warning")
}

// TestConditionForAttributeJSONTypeCollision covers a name stored under two data types (String
// and Int64) in the JSON column: an untyped filter fans out to one exists-guarded condition per
// type, both reading the same physical path with their own cast, and surfaces the ambiguity
// warning. In the JSON column the two branches share the raw path; only the cast differs.
func TestConditionForAttributeJSONTypeCollision(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	strKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeString, evo)
	intKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
	fieldKeys := map[string][]*telemetrytypes.TelemetryFieldKey{
		"http.status_code": {&strKey, &intKey},
	}

	ref := attrKey("http.status_code", telemetrytypes.FieldDataTypeUnspecified, nil)
	sb := sqlbuilder.NewSelectBuilder()
	conds, warnings, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &ref, qbtypes.FilterOperatorEqual, float64(200), fieldKeys, false, sb)
	require.NoError(t, err)
	require.Len(t, conds, 2, "a colliding name must build one condition per data type")

	sb.Where(sb.Or(conds...))
	sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
	assert.Contains(t, sql, "toFloat64OrNull(attributes.`http.status_code`::String) = ?")
	assert.Contains(t, sql, "toFloat64OrNull(attributes.`http.status_code`::String) = ?")
	assert.Contains(t, sql, "attributes.`http.status_code` IS NOT NULL")
	assert.NotEmpty(t, warnings, "a colliding name must surface the ambiguity warning")
}

// TestColumnExpressionForAttributeJSONTypeCollision covers group-by on a name stored under two
// data types. On the JSON column both interpretations read one path: the numeric branch is guarded
// by its cast (a wrong-typed row reads NULL and falls through), and the ::String branch renders any
// stored scalar faithfully (200 -> '200', true -> 'true'), so every candidate order reads each row
// as its actual stored type.
func TestColumnExpressionForAttributeJSONTypeCollision(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	strKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeString, evo)
	intKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
	fieldKeys := map[string][]*telemetrytypes.TelemetryFieldKey{
		"http.status_code": {&strKey, &intKey},
	}

	ref := attrKey("http.status_code", telemetrytypes.FieldDataTypeUnspecified, nil)
	got, err := querybuilder.ResolveColumn(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &ref, telemetrytypes.FieldDataTypeString, fieldKeys)
	require.NoError(t, err)
	assert.Equal(t,
		"multiIf(attributes.`http.status_code` IS NOT NULL, attributes.`http.status_code`::String, toFloat64OrNull(attributes.`http.status_code`::String) IS NOT NULL, toString(toFloat64OrNull(attributes.`http.status_code`::String)), NULL)",
		got)
}

// TestColumnExpressionForAttributeJSONTypeCollisionNumericAgg covers a numeric aggregation over a
// name colliding as Number and String: the cast-guarded numeric branch takes numeric rows (a
// wrong-typed row reads NULL and falls through), and the string branch parses whatever remains —
// non-numeric strings parse to NULL and stay out of the aggregate, the per-type Map union's
// coverage.
func TestColumnExpressionForAttributeJSONTypeCollisionNumericAgg(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	numKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeNumber, evo)
	strKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeString, evo)
	fieldKeys := map[string][]*telemetrytypes.TelemetryFieldKey{
		"http.status_code": {&numKey, &strKey},
	}

	ref := attrKey("http.status_code", telemetrytypes.FieldDataTypeUnspecified, nil)
	got, err := querybuilder.ResolveColumn(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, storage, &ref, telemetrytypes.FieldDataTypeFloat64, fieldKeys)
	require.NoError(t, err)
	assert.Equal(t,
		"multiIf(toFloat64OrNull(attributes.`http.status_code`::String) IS NOT NULL, toFloat64OrNull(attributes.`http.status_code`::String), attributes.`http.status_code` IS NOT NULL, toFloat64OrNull(attributes.`http.status_code`::String), NULL)",
		got)
}

// TestConditionForAttributeMapTypeCollisionParity anchors the legacy behavior the JSON path must
// preserve: before the rollout the same colliding name fans out to two separate physical map
// columns (attributes_string / attributes_number), each with its own mapContains guard.
func TestConditionForAttributeMapTypeCollisionParity(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	strKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeString, evo)
	intKey := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
	fieldKeys := map[string][]*telemetrytypes.TelemetryFieldKey{
		"http.status_code": {&strKey, &intKey},
	}

	ref := attrKey("http.status_code", telemetrytypes.FieldDataTypeUnspecified, nil)
	sb := sqlbuilder.NewSelectBuilder()
	conds, _, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowBefore[0], EndNs: attrWindowBefore[1], TraceAttrsJSONOn: true}, storage, &ref, qbtypes.FilterOperatorEqual, float64(200), fieldKeys, false, sb)
	require.NoError(t, err)
	require.Len(t, conds, 2, "a colliding name must build one condition per data type")

	sb.Where(sb.Or(conds...))
	sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
	assert.Contains(t, sql, "toFloat64OrNull(attributes_string['http.status_code']) = ?")
	assert.Contains(t, sql, "mapContains(attributes_string, 'http.status_code')")
	assert.Contains(t, sql, "toFloat64(attributes_number['http.status_code']) = ?")
	assert.Contains(t, sql, "mapContains(attributes_number, 'http.status_code')")
}

// TestColumnForUnspecifiedAttributeNoBranchFlip pins the branch-flip decision: a
// data-type-unspecified attribute key resolves to no column (even with the evolution present), so
// bare attribute keys keep taking the legacy CandidateKeys/synthesis path rather than becoming
// metadata-first resolvable.
func TestColumnForUnspecifiedAttributeNoBranchFlip(t *testing.T) {
	ctx := context.Background()
	evo := MockAttributeEvolutionData(attrJSONRelease)

	key := attrKey("user.id", telemetrytypes.FieldDataTypeUnspecified, evo)
	_, err := (&storage{}).getColumn(ctx, qbtypes.QueryInfo{StartNs: attrWindowAfter[0], EndNs: attrWindowAfter[1], TraceAttrsJSONOn: true}, &key)
	assert.ErrorIs(t, err, qbtypes.ErrColumnNotFound)
}

// TestConditionForAttributeJSONNegativeOperatorParity pins Map parity for numeric/bool attributes.
// The value reads an absent key as NULL (toFloat64OrNull, or the straddle multiIf else); a
// positive operator excludes such a row via the exists guard, but a negative operator has no guard,
// so the condition builder folds the NULL to the Map's type zero (ifNull) for negatives only.
// String needs no fold — ::String already reads absent as ”. The fold rides the attributes
// evolution: a key without it (the pre-rollout system) is byte-identical to today.
func TestConditionForAttributeJSONNegativeOperatorParity(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	build := func(t *testing.T, key telemetrytypes.TelemetryFieldKey, window [2]uint64, op qbtypes.FilterOperator, value any) string {
		t.Helper()
		sb := sqlbuilder.NewSelectBuilder()
		conds, _, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: window[0], EndNs: window[1], TraceAttrsJSONOn: true}, storage, &key, op, value, map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, false, sb)
		require.NoError(t, err)
		sb.Where(conds...)
		sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
		return sql
	}

	t.Run("not equal number after -> NULL folded to 0", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorNotEqual, float64(200))
		assert.Contains(t, sql, "toFloat64(ifNull(toFloat64OrNull(attributes.`http.status_code`::String), 0)) <> ?")
	})

	t.Run("not equal bool after -> NULL folded to false", func(t *testing.T) {
		key := attrKey("http.cache.hit", telemetrytypes.FieldDataTypeBool, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorNotEqual, true)
		assert.Contains(t, sql, "ifNull(if(dynamicType(attributes.`http.cache.hit`) = 'Bool', accurateCastOrNull(attributes.`http.cache.hit`, 'Bool'), NULL), false) <> ?")
	})

	// A numeric key compared to a non-numeric string is string-cast; the fold runs on the raw
	// read (before the cast), so the string cast wraps a non-nullable value -> toString(ifNull(..)),
	// never ifNull(toString(..), 0), which raises a String vs UInt8 type mismatch in ClickHouse.
	t.Run("not equal number after, string value -> string cast over folded read, no type mismatch", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorNotEqual, "teapot")
		assert.Contains(t, sql, "toString(ifNull(toFloat64OrNull(attributes.`http.status_code`::String), 0)) <> ?")
		assert.NotContains(t, sql, "ifNull(toString(")
	})

	t.Run("equal number after -> not folded, exists guard excludes absent", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorEqual, float64(0))
		assert.Contains(t, sql, "toFloat64OrNull(attributes.`http.status_code`::String) = ?")
		assert.NotContains(t, sql, "ifNull")
	})

	t.Run("not in number after -> each operand folded to 0", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorNotIn, []any{float64(200), float64(404)})
		assert.Contains(t, sql, "(toFloat64(ifNull(toFloat64OrNull(attributes.`http.status_code`::String), 0)) <> ? AND toFloat64(ifNull(toFloat64OrNull(attributes.`http.status_code`::String), 0)) <> ?)")
	})

	t.Run("not equal number straddle -> whole multiIf folded", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowStraddle, qbtypes.FilterOperatorNotEqual, float64(200))
		assert.Contains(t, sql, "toFloat64(ifNull(multiIf(toFloat64OrNull(attributes.`http.status_code`::String) IS NOT NULL, toFloat64OrNull(attributes.`http.status_code`::String), mapContains(attributes_number, 'http.status_code'), attributes_number['http.status_code'], NULL), 0)) <> ?")
	})

	t.Run("not equal number before -> harmless fold over the map read", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, attrWindowBefore, qbtypes.FilterOperatorNotEqual, float64(200))
		assert.Contains(t, sql, "toFloat64(ifNull(attributes_number['http.status_code'], 0)) <> ?")
	})

	t.Run("not equal number without rollout -> byte-identical to today", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, nil)
		sql := build(t, key, attrWindowBefore, qbtypes.FilterOperatorNotEqual, float64(200))
		assert.Contains(t, sql, "toFloat64(attributes_number['http.status_code']) <> ?")
		assert.NotContains(t, sql, "ifNull")
	})

	t.Run("not equal string after -> '' default, never folded", func(t *testing.T) {
		key := attrKey("user.id", telemetrytypes.FieldDataTypeString, evo)
		sql := build(t, key, attrWindowAfter, qbtypes.FilterOperatorNotEqual, "admin")
		assert.Contains(t, sql, "attributes.`user.id`::String <> ?")
		assert.NotContains(t, sql, "ifNull")
	})
}

// TestConditionForAttributeJSONStraddleAbsentKeyExclusion guards the straddle exists path: because
// the value reads absent-in-both-homes as NULL (multiIf else), a positive zero-value comparison and
// EXISTS/NOT EXISTS must still exclude a key absent from every home, rather than matching it.
func TestConditionForAttributeJSONStraddleAbsentKeyExclusion(t *testing.T) {
	ctx := context.Background()
	storage := NewStorage(nil)
	evo := MockAttributeEvolutionData(attrJSONRelease)

	build := func(t *testing.T, key telemetrytypes.TelemetryFieldKey, op qbtypes.FilterOperator, value any) string {
		t.Helper()
		sb := sqlbuilder.NewSelectBuilder()
		conds, _, err := querybuilder.Conditions(ctx, qbtypes.QueryInfo{StartNs: attrWindowStraddle[0], EndNs: attrWindowStraddle[1], TraceAttrsJSONOn: true}, storage, &key, op, value, map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, false, sb)
		require.NoError(t, err)
		sb.Where(conds...)
		sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
		return sql
	}

	guard := "multiIf(toFloat64OrNull(attributes.`http.status_code`::String) IS NOT NULL, toFloat64OrNull(attributes.`http.status_code`::String), mapContains(attributes_number, 'http.status_code'), attributes_number['http.status_code'], NULL) IS NOT NULL"

	t.Run("equal zero takes no guard: the absent read is NULL", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, qbtypes.FilterOperatorEqual, float64(0))
		assert.Contains(t, sql, "toFloat64(multiIf(")
		assert.NotContains(t, sql, guard)
	})
	t.Run("exists is the raw multiIf, not always-true", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		assert.Contains(t, build(t, key, qbtypes.FilterOperatorExists, nil), guard)
	})
	t.Run("not exists negates the raw multiIf", func(t *testing.T) {
		key := attrKey("http.status_code", telemetrytypes.FieldDataTypeInt64, evo)
		sql := build(t, key, qbtypes.FilterOperatorNotExists, nil)
		assert.Contains(t, sql, ", NULL) IS NULL")
	})
}

func TestConditionForAttributeJSONUnknownKey(t *testing.T) {
	evolutions := MockAttributeEvolutionData(attrJSONRelease)
	bare := telemetrytypes.TelemetryFieldKey{Name: "unknown.attr"}

	testCases := []struct {
		name            string
		window          [2]uint64
		flagOff         bool
		evolutions      []*telemetrytypes.EvolutionEntry
		key             telemetrytypes.TelemetryFieldKey
		operator        qbtypes.FilterOperator
		value           any
		wantContains    []string
		wantNotContains []string
	}{
		{
			name:            "BeforeRollout_ReadsMap",
			window:          attrWindowBefore,
			evolutions:      evolutions,
			key:             bare,
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes_string['unknown.attr'] = ?"},
			wantNotContains: []string{"attributes.`unknown.attr`"},
		},
		{
			name:            "AfterRollout_ReadsJSON",
			window:          attrWindowAfter,
			evolutions:      evolutions,
			key:             bare,
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes.`unknown.attr`::String = ?"},
			wantNotContains: []string{"attributes_string"},
		},
		{
			name:         "StraddlingRollout_ReadsJSONThenMap",
			window:       attrWindowStraddle,
			evolutions:   evolutions,
			key:          bare,
			operator:     qbtypes.FilterOperatorEqual,
			value:        "x",
			wantContains: []string{"multiIf(attributes.`unknown.attr` IS NOT NULL, attributes.`unknown.attr`::String, mapContains(attributes_string, 'unknown.attr'), attributes_string['unknown.attr'], NULL) = ?"},
		},
		{
			name:            "AfterRollout_NumberOperand_ReadsJSON",
			window:          attrWindowAfter,
			evolutions:      evolutions,
			key:             bare,
			operator:        qbtypes.FilterOperatorEqual,
			value:           float64(1),
			wantContains:    []string{"toFloat64OrNull(attributes.`unknown.attr`::String) = ?"},
			wantNotContains: []string{"attributes_number"},
		},
		{
			name:            "AfterRollout_Exists_ReadsJSONOnly",
			window:          attrWindowAfter,
			evolutions:      evolutions,
			key:             bare,
			operator:        qbtypes.FilterOperatorExists,
			wantContains:    []string{"attributes.`unknown.attr` IS NOT NULL"},
			wantNotContains: []string{"mapContains"},
		},
		{
			name:            "AfterRollout_AttributeContext_ReadsJSONForBothSpellings",
			window:          attrWindowAfter,
			evolutions:      evolutions,
			key:             telemetrytypes.TelemetryFieldKey{Name: "unknown.attr", FieldContext: telemetrytypes.FieldContextAttribute},
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes.`unknown.attr`::String = ?", "attributes.`attribute.unknown.attr`::String = ?"},
			wantNotContains: []string{"attributes_string"},
		},
		{
			name:            "AfterRollout_SpanContext_ReadsJSONAttribute",
			window:          attrWindowAfter,
			evolutions:      evolutions,
			key:             telemetrytypes.TelemetryFieldKey{Name: "unknown.attr", FieldContext: telemetrytypes.FieldContextSpan},
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes.`unknown.attr`::String = ?"},
			wantNotContains: []string{"attributes_string"},
		},
		{
			name:            "NoEvolutions_ReadsMap",
			window:          attrWindowAfter,
			key:             bare,
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes_string['unknown.attr'] = ?"},
			wantNotContains: []string{"attributes.`unknown.attr`"},
		},
		{
			name:            "FlagOff_ReadsMap",
			window:          attrWindowAfter,
			flagOff:         true,
			evolutions:      evolutions,
			key:             bare,
			operator:        qbtypes.FilterOperatorEqual,
			value:           "x",
			wantContains:    []string{"attributes_string['unknown.attr'] = ?"},
			wantNotContains: []string{"attributes.`unknown.attr`"},
		},
		{
			name:         "ResourceContext_IgnoresAttributeEvolutions",
			window:       attrWindowAfter,
			evolutions:   evolutions,
			key:          telemetrytypes.TelemetryFieldKey{Name: "unknown.attr", FieldContext: telemetrytypes.FieldContextResource},
			operator:     qbtypes.FilterOperatorEqual,
			value:        "x",
			wantContains: []string{"resource.`unknown.attr`::String", "resources_string['unknown.attr']"},
		},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			schemaMetadataStore := telemetrytypestest.NewMockSchemaMetadataStore(t)
			schemaMetadataStore.EXPECT().GetBaseColumnEvolutions(mock.Anything, telemetrytypes.SignalTraces, telemetrytypes.FieldContextAttribute).Return(testCase.evolutions, nil).Maybe()

			q := qbtypes.QueryInfo{StartNs: testCase.window[0], EndNs: testCase.window[1], TraceAttrsJSONOn: !testCase.flagOff}
			sb := sqlbuilder.NewSelectBuilder()
			conds, _, err := querybuilder.Conditions(context.Background(), q, NewStorage(schemaMetadataStore), &testCase.key, testCase.operator, testCase.value, map[string][]*telemetrytypes.TelemetryFieldKey{}, false, sb)
			require.NoError(t, err)
			sb.Where(conds...)
			sql, _ := sb.BuildWithFlavor(sqlbuilder.ClickHouse)

			for _, want := range testCase.wantContains {
				assert.Contains(t, sql, want)
			}
			for _, unwanted := range testCase.wantNotContains {
				assert.NotContains(t, sql, unwanted)
			}
		})
	}
}