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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix: use numerical comparison instead of lexicographical for string-encoded numbers (#9154)
Nityananda Gohain8c29debb5297
diff --git a/pkg/querybuilder/fallback_expr.go b/pkg/querybuilder/fallback_expr.goindex b7ac4d70c0..ef64db4de0 100644--- a/pkg/querybuilder/fallback_expr.go+++ b/pkg/querybuilder/fallback_expr.go@@ -94,7 +94,7 @@ func CollisionHandledFinalExpr(return "", nil, err}colName, _ = fm.FieldFor(ctx, key)- colName, _ = telemetrytypes.DataTypeCollisionHandledFieldName(key, dummyValue, colName)+ colName, _ = DataTypeCollisionHandledFieldName(key, dummyValue, colName, qbtypes.FilterOperatorUnknown)stmts = append(stmts, colName)}}@@ -109,7 +109,7 @@ func CollisionHandledFinalExpr(return "", nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "Group by/Aggregation isn't available for the body column")// colName, _ = jsonKeyToKey(context.Background(), field, qbtypes.FilterOperatorUnknown, dummyValue)} else {- colName, _ = telemetrytypes.DataTypeCollisionHandledFieldName(field, dummyValue, colName)+ colName, _ = DataTypeCollisionHandledFieldName(field, dummyValue, colName, qbtypes.FilterOperatorUnknown)}stmts = append(stmts, colName)@@ -194,3 +194,109 @@ func FormatFullTextSearch(input string) string {}return input}++func DataTypeCollisionHandledFieldName(key *telemetrytypes.TelemetryFieldKey, value any, tblFieldName string, operator qbtypes.FilterOperator) (string, any) {+ // This block of code exists to handle the data type collisions+ // We don't want to fail the requests when there is a key with more than one data type+ // Let's take an example of `http.status_code`, and consider user sent a string value and number value+ // When they search for `http.status_code=200`, we will search across both the number columns and string columns+ // and return the results from both the columns+ // While we expect user not to send the mixed data types, it inevitably happens+ // So we handle the data type collisions here+ switch key.FieldDataType {+ case telemetrytypes.FieldDataTypeString:+ switch v := value.(type) {+ case float64:+ // try to convert the string value to to number+ tblFieldName = castFloat(tblFieldName)+ case []any:+ if allFloats(v) {+ tblFieldName = castFloat(tblFieldName)+ } else if hasString(v) {+ _, value = castString(tblFieldName), toStrings(v)+ }+ case bool:+ // we don't have a toBoolOrNull in ClickHouse, so we need to convert the bool to a string+ value = fmt.Sprintf("%t", v)+ }++ case telemetrytypes.FieldDataTypeFloat64, telemetrytypes.FieldDataTypeInt64, telemetrytypes.FieldDataTypeNumber:+ switch v := value.(type) {+ // why? ; CH returns an error for a simple check+ // attributes_number['http.status_code'] = 200 but not for attributes_number['http.status_code'] >= 200+ // DB::Exception: Bad get: has UInt64, requested Float64.+ // How is it working in v4? v4 prepares the full query with values in query string+ // When we format the float it becomes attributes_number['http.status_code'] = 200.000+ // Which CH gladly accepts and doesn't throw error+ // However, when passed as query args, the default formatter+ // https://github.com/ClickHouse/clickhouse-go/blob/757e102f6d8c6059d564ce98795b4ce2a101b1a5/bind.go#L393+ // is used which prepares the+ // final query as attributes_number['http.status_code'] = 200 giving this error+ // This following is one way to workaround it++ // if the key is a number, the value is a string, we will let clickHouse handle the conversion+ case float32, float64:+ tblFieldName = castFloatHack(tblFieldName)+ case string:+ // check if it's a number inside a string+ isNumber := false+ if _, err := strconv.ParseFloat(v, 64); err == nil {+ isNumber = true+ }++ if !operator.IsComparisonOperator() || !isNumber {+ // try to convert the number attribute to string+ tblFieldName = castString(tblFieldName) // numeric col vs string literal+ } else {+ tblFieldName = castFloatHack(tblFieldName)+ }+ case []any:+ if allFloats(v) {+ tblFieldName = castFloatHack(tblFieldName)+ } else if hasString(v) {+ tblFieldName, value = castString(tblFieldName), toStrings(v)+ }+ }++ case telemetrytypes.FieldDataTypeBool:+ switch v := value.(type) {+ case string:+ tblFieldName = castString(tblFieldName)+ case []any:+ if hasString(v) {+ tblFieldName, value = castString(tblFieldName), toStrings(v)+ }+ }+ }+ return tblFieldName, value+}++func castFloat(col string) string { return fmt.Sprintf("toFloat64OrNull(%s)", col) }+func castFloatHack(col string) string { return fmt.Sprintf("toFloat64(%s)", col) }+func castString(col string) string { return fmt.Sprintf("toString(%s)", col) }++func allFloats(in []any) bool {+ for _, x := range in {+ if _, ok := x.(float64); !ok {+ return false+ }+ }+ return true+}++func hasString(in []any) bool {+ for _, x := range in {+ if _, ok := x.(string); ok {+ return true+ }+ }+ return false+}++func toStrings(in []any) []any {+ out := make([]any, len(in))+ for i, x := range in {+ out[i] = fmt.Sprintf("%v", x)+ }+ return out+}diff --git a/pkg/querybuilder/fallback_expr_test.go b/pkg/querybuilder/fallback_expr_test.gonew file mode 100644index 0000000000..659fca9fc4--- /dev/null+++ b/pkg/querybuilder/fallback_expr_test.go@@ -0,0 +1,165 @@+package querybuilder++import (+ "testing"++ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/stretchr/testify/assert"+)++func TestDataTypeCollisionHandledFieldName(t *testing.T) {+ tests := []struct {+ name string+ key *telemetrytypes.TelemetryFieldKey+ value any+ tblFieldName string+ expectedFieldName string+ expectedValue any+ operator qbtypes.FilterOperator+ }{+ {+ name: "http_status_code_string_field_with_numeric_value",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.status_code",+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ value: float64(200),+ tblFieldName: "attribute_string_http$$status_code",+ expectedFieldName: "toFloat64OrNull(attribute_string_http$$status_code)",+ expectedValue: float64(200),+ },+ {+ name: "service_enabled_string_field_with_bool_value",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "service.enabled",+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ value: true,+ tblFieldName: "attribute_string_service$$enabled",+ expectedFieldName: "attribute_string_service$$enabled",+ expectedValue: "true",+ },+ {+ name: "http_method_string_field_with_string_value",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.method",+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ value: "GET",+ tblFieldName: "attribute_string_http$$method",+ expectedFieldName: "attribute_string_http$$method",+ expectedValue: "GET",+ },+ {+ name: "response_times_string_field_with_numeric_array",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "response.times",+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ value: []any{float64(100.5), float64(200.3), float64(150.7)},+ tblFieldName: "attribute_string_response$$times",+ expectedFieldName: "toFloat64OrNull(attribute_string_response$$times)",+ expectedValue: []any{float64(100.5), float64(200.3), float64(150.7)},+ },+ {+ name: "error_codes_string_field_with_mixed_array",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "error.codes",+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+ value: []any{float64(500), "TIMEOUT", float64(503)},+ tblFieldName: "attribute_string_error$$codes",+ expectedFieldName: "attribute_string_error$$codes",+ expectedValue: []any{"500", "TIMEOUT", "503"},+ },++ // numbers+ {+ // we cast the key to string if the value is not a number or operator is not a comparison operator+ name: "http_request_duration_float_field_with_string_value",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.request.duration",+ FieldDataType: telemetrytypes.FieldDataTypeFloat64,+ },+ value: "1234.56",+ tblFieldName: "attribute_float64_http$$request$$duration",+ expectedFieldName: "toString(attribute_float64_http$$request$$duration)",+ expectedValue: "1234.56",+ operator: qbtypes.FilterOperatorEqual,+ },+ {+ // we cast to float64 if it's a comparison operator and the value is a stringified number+ // reason:- https://github.com/SigNoz/signoz/pull/9154#issuecomment-3369941207+ name: "http_request_duration_float_field_with_string_value_comparison_operator",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.request.duration",+ FieldDataType: telemetrytypes.FieldDataTypeFloat64,+ },+ value: "9",+ tblFieldName: "attribute_float64_http$$request$$duration",+ expectedFieldName: "toFloat64(attribute_float64_http$$request$$duration)",+ expectedValue: "9",+ operator: qbtypes.FilterOperatorGreaterThan,+ },+ {+ // we cast to float64 if it's a comparison operator and the value is a stringified number+ // reason:- https://github.com/SigNoz/signoz/pull/9154#issuecomment-3369941207+ name: "http_request_duration_float_field_with_string_value_comparison_operator_1",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.request.duration",+ FieldDataType: telemetrytypes.FieldDataTypeFloat64,+ },+ value: "9.11",+ tblFieldName: "attribute_float64_http$$request$$duration",+ expectedFieldName: "toFloat64(attribute_float64_http$$request$$duration)",+ expectedValue: "9.11",+ operator: qbtypes.FilterOperatorGreaterThan,+ },+ {+ // we cast the key to string if the value is not a number or operator is not a comparison operator+ name: "http_request_duration_float_field_with_string_value_comparison_operator_2",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "http.request.duration",+ FieldDataType: telemetrytypes.FieldDataTypeFloat64,+ },+ value: "ERROR",+ tblFieldName: "attribute_float64_http$$request$$duration",+ expectedFieldName: "toString(attribute_float64_http$$request$$duration)",+ expectedValue: "ERROR",+ operator: qbtypes.FilterOperatorGreaterThan,+ },++ // bools+ {+ name: "feature_enabled_bool_field_with_string_value",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "feature.enabled",+ FieldDataType: telemetrytypes.FieldDataTypeBool,+ },+ value: "true",+ tblFieldName: "attribute_bool_feature$$enabled",+ expectedFieldName: "toString(attribute_bool_feature$$enabled)",+ expectedValue: "true",+ },+ {+ name: "feature_flags_bool_field_with_mixed_array",+ key: &telemetrytypes.TelemetryFieldKey{+ Name: "feature.flags",+ FieldDataType: telemetrytypes.FieldDataTypeBool,+ },+ value: []any{true, "enabled", false},+ tblFieldName: "attribute_bool_feature$$flags",+ expectedFieldName: "toString(attribute_bool_feature$$flags)",+ expectedValue: []any{"true", "enabled", "false"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ resultFieldName, resultValue := DataTypeCollisionHandledFieldName(tt.key, tt.value, tt.tblFieldName, tt.operator)+ assert.Equal(t, tt.expectedFieldName, resultFieldName)+ assert.Equal(t, tt.expectedValue, resultValue)+ })+ }+}diff --git a/pkg/telemetrylogs/condition_builder.go b/pkg/telemetrylogs/condition_builder.goindex 15671fd837..a5af55f932 100644--- a/pkg/telemetrylogs/condition_builder.go+++ b/pkg/telemetrylogs/condition_builder.go@@ -55,7 +55,7 @@ func (c *conditionBuilder) conditionFor(tblFieldName, value = GetBodyJSONKey(ctx, key, operator, value)}- tblFieldName, value = telemetrytypes.DataTypeCollisionHandledFieldName(key, value, tblFieldName)+ tblFieldName, value = querybuilder.DataTypeCollisionHandledFieldName(key, value, tblFieldName, operator)// make use of case insensitive index for bodyif tblFieldName == "body" {diff --git a/pkg/telemetrylogs/filter_expr_logs_test.go b/pkg/telemetrylogs/filter_expr_logs_test.goindex 64d55f0688..8ccbec37d3 100644--- a/pkg/telemetrylogs/filter_expr_logs_test.go+++ b/pkg/telemetrylogs/filter_expr_logs_test.go@@ -424,6 +424,16 @@ func TestFilterExprLogs(t *testing.T) {expectedArgs: []any{"critical", "resolved", "open", true},expectedErrorContains: "",},+ {+ // this will result in failure from the DB side.+ // user will have to use attribute.status:string > open+ category: "FREETEXT with conditions",+ query: "critical NOT resolved status > open",+ shouldPass: true,+ expectedQuery: "WHERE (match(LOWER(body), LOWER(?)) AND NOT (match(LOWER(body), LOWER(?))) AND (toString(attributes_number['status']) > ? AND mapContains(attributes_number, 'status') = ?))",+ expectedArgs: []any{"critical", "resolved", "open", true},+ expectedErrorContains: "",+ },{category: "FREETEXT with conditions",query: "database error type=mysql",diff --git a/pkg/telemetrymetadata/condition_builder.go b/pkg/telemetrymetadata/condition_builder.goindex 2a08a29a6e..f943533b36 100644--- a/pkg/telemetrymetadata/condition_builder.go+++ b/pkg/telemetrymetadata/condition_builder.go@@ -55,7 +55,7 @@ func (c *conditionBuilder) ConditionFor(return "", nil}- tblFieldName, value = telemetrytypes.DataTypeCollisionHandledFieldName(key, value, tblFieldName)+ tblFieldName, value = querybuilder.DataTypeCollisionHandledFieldName(key, value, tblFieldName, operator)// key must exists to apply main filterexpr := `if(mapContains(%s, %s), %s, true)`diff --git a/pkg/telemetrytraces/condition_builder.go b/pkg/telemetrytraces/condition_builder.goindex 44f89c1493..cec1e63e97 100644--- a/pkg/telemetrytraces/condition_builder.go+++ b/pkg/telemetrytraces/condition_builder.go@@ -73,7 +73,7 @@ func (c *conditionBuilder) conditionFor(}}} else {- tblFieldName, value = telemetrytypes.DataTypeCollisionHandledFieldName(key, value, tblFieldName)+ tblFieldName, value = querybuilder.DataTypeCollisionHandledFieldName(key, value, tblFieldName, operator)}// regular operatorsdiff --git a/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go b/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.goindex 06c4c93a69..9452dcf766 100644--- a/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go+++ b/pkg/types/querybuildertypes/querybuildertypesv5/builder_elements.go@@ -137,6 +137,14 @@ func (f FilterOperator) IsNegativeOperator() bool {return true}+func (f FilterOperator) IsComparisonOperator() bool {+ switch f {+ case FilterOperatorGreaterThan, FilterOperatorGreaterThanOrEq, FilterOperatorLessThan, FilterOperatorLessThanOrEq:+ return true+ }+ return false+}+type OrderDirection struct {valuer.String}diff --git a/pkg/types/telemetrytypes/field.go b/pkg/types/telemetrytypes/field.goindex ac5aee727d..13376e05ab 100644--- a/pkg/types/telemetrytypes/field.go+++ b/pkg/types/telemetrytypes/field.go@@ -136,97 +136,3 @@ type FieldValueSelector struct {Value string `json:"value"`Limit int `json:"limit"`}--func DataTypeCollisionHandledFieldName(key *TelemetryFieldKey, value any, tblFieldName string) (string, any) {- // This block of code exists to handle the data type collisions- // We don't want to fail the requests when there is a key with more than one data type- // Let's take an example of `http.status_code`, and consider user sent a string value and number value- // When they search for `http.status_code=200`, we will search across both the number columns and string columns- // and return the results from both the columns- // While we expect user not to send the mixed data types, it inevitably happens- // So we handle the data type collisions here- switch key.FieldDataType {- case FieldDataTypeString:- switch v := value.(type) {- case float64:- // try to convert the string value to to number- tblFieldName = castFloat(tblFieldName)- case []any:- if allFloats(v) {- tblFieldName = castFloat(tblFieldName)- } else if hasString(v) {- _, value = castString(tblFieldName), toStrings(v)- }- case bool:- // we don't have a toBoolOrNull in ClickHouse, so we need to convert the bool to a string- value = fmt.Sprintf("%t", v)- }-- case FieldDataTypeFloat64, FieldDataTypeInt64, FieldDataTypeNumber:- switch v := value.(type) {- // why? ; CH returns an error for a simple check- // attributes_number['http.status_code'] = 200 but not for attributes_number['http.status_code'] >= 200- // DB::Exception: Bad get: has UInt64, requested Float64.- // How is it working in v4? v4 prepares the full query with values in query string- // When we format the float it becomes attributes_number['http.status_code'] = 200.000- // Which CH gladly accepts and doesn't throw error- // However, when passed as query args, the default formatter- // https://github.com/ClickHouse/clickhouse-go/blob/757e102f6d8c6059d564ce98795b4ce2a101b1a5/bind.go#L393- // is used which prepares the- // final query as attributes_number['http.status_code'] = 200 giving this error- // This following is one way to workaround it- case float32, float64:- tblFieldName = castFloatHack(tblFieldName)- case string:- // try to convert the number attribute to string- tblFieldName = castString(tblFieldName) // numeric col vs string literal- case []any:- if allFloats(v) {- tblFieldName = castFloatHack(tblFieldName)- } else if hasString(v) {- tblFieldName, value = castString(tblFieldName), toStrings(v)- }- }-- case FieldDataTypeBool:- switch v := value.(type) {- case string:- tblFieldName = castString(tblFieldName)- case []any:- if hasString(v) {- tblFieldName, value = castString(tblFieldName), toStrings(v)- }- }- }- return tblFieldName, value-}--func castFloat(col string) string { return fmt.Sprintf("toFloat64OrNull(%s)", col) }-func castFloatHack(col string) string { return fmt.Sprintf("toFloat64(%s)", col) }-func castString(col string) string { return fmt.Sprintf("toString(%s)", col) }--func allFloats(in []any) bool {- for _, x := range in {- if _, ok := x.(float64); !ok {- return false- }- }- return true-}--func hasString(in []any) bool {- for _, x := range in {- if _, ok := x.(string); ok {- return true- }- }- return false-}--func toStrings(in []any) []any {- out := make([]any, len(in))- for i, x := range in {- out[i] = fmt.Sprintf("%v", x)- }- return out-}diff --git a/pkg/types/telemetrytypes/field_test.go b/pkg/types/telemetrytypes/field_test.goindex dc2494ab41..179e6ee093 100644--- a/pkg/types/telemetrytypes/field_test.go+++ b/pkg/types/telemetrytypes/field_test.go@@ -2,8 +2,6 @@ package telemetrytypesimport ("testing"-- "github.com/stretchr/testify/assert")func TestGetFieldKeyFromKeyText(t *testing.T) {@@ -93,115 +91,3 @@ func TestGetFieldKeyFromKeyText(t *testing.T) {}}}--func TestDataTypeCollisionHandledFieldName(t *testing.T) {- tests := []struct {- name string- key *TelemetryFieldKey- value any- tblFieldName string- expectedFieldName string- expectedValue any- }{- {- name: "http_status_code_string_field_with_numeric_value",- key: &TelemetryFieldKey{- Name: "http.status_code",- FieldDataType: FieldDataTypeString,- },- value: float64(200),- tblFieldName: "attribute_string_http$$status_code",- expectedFieldName: "toFloat64OrNull(attribute_string_http$$status_code)",- expectedValue: float64(200),- },- {- name: "service_enabled_string_field_with_bool_value",- key: &TelemetryFieldKey{- Name: "service.enabled",- FieldDataType: FieldDataTypeString,- },- value: true,- tblFieldName: "attribute_string_service$$enabled",- expectedFieldName: "attribute_string_service$$enabled",- expectedValue: "true",- },- {- name: "http_method_string_field_with_string_value",- key: &TelemetryFieldKey{- Name: "http.method",- FieldDataType: FieldDataTypeString,- },- value: "GET",- tblFieldName: "attribute_string_http$$method",- expectedFieldName: "attribute_string_http$$method",- expectedValue: "GET",- },- {- name: "response_times_string_field_with_numeric_array",- key: &TelemetryFieldKey{- Name: "response.times",- FieldDataType: FieldDataTypeString,- },- value: []any{float64(100.5), float64(200.3), float64(150.7)},- tblFieldName: "attribute_string_response$$times",- expectedFieldName: "toFloat64OrNull(attribute_string_response$$times)",- expectedValue: []any{float64(100.5), float64(200.3), float64(150.7)},- },- {- name: "error_codes_string_field_with_mixed_array",- key: &TelemetryFieldKey{- Name: "error.codes",- FieldDataType: FieldDataTypeString,- },- value: []any{float64(500), "TIMEOUT", float64(503)},- tblFieldName: "attribute_string_error$$codes",- expectedFieldName: "attribute_string_error$$codes",- expectedValue: []any{"500", "TIMEOUT", "503"},- },-- // numbers- {- name: "http_request_duration_float_field_with_string_value",- key: &TelemetryFieldKey{- Name: "http.request.duration",- FieldDataType: FieldDataTypeFloat64,- },- value: "1234.56",- tblFieldName: "attribute_float64_http$$request$$duration",- expectedFieldName: "toString(attribute_float64_http$$request$$duration)",- expectedValue: "1234.56",- },-- // bools- {- name: "feature_enabled_bool_field_with_string_value",- key: &TelemetryFieldKey{- Name: "feature.enabled",- FieldDataType: FieldDataTypeBool,- },- value: "true",- tblFieldName: "attribute_bool_feature$$enabled",- expectedFieldName: "toString(attribute_bool_feature$$enabled)",- expectedValue: "true",- },- {- name: "feature_flags_bool_field_with_mixed_array",- key: &TelemetryFieldKey{- Name: "feature.flags",- FieldDataType: FieldDataTypeBool,- },- value: []any{true, "enabled", false},- tblFieldName: "attribute_bool_feature$$flags",- expectedFieldName: "toString(attribute_bool_feature$$flags)",- expectedValue: []any{"true", "enabled", "false"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- resultFieldName, resultValue := DataTypeCollisionHandledFieldName(tt.key, tt.value, tt.tblFieldName)- assert.Equal(t, tt.expectedFieldName, resultFieldName)- assert.Equal(t, tt.expectedValue, resultValue)- })- }-}diff --git a/tests/integration/src/querier/a_logs.py b/tests/integration/src/querier/a_logs.pyindex f7ddf91679..4f19e69095 100644--- a/tests/integration/src/querier/a_logs.py+++ b/tests/integration/src/querier/a_logs.py@@ -816,3 +816,429 @@ def test_logs_time_series_count(),"value": 9,} in series[1]["values"]+++def test_datatype_collision(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_jwt_token: Callable[[str, str], str],+ insert_logs: Callable[[List[Logs]], None],+) -> None:+ """+ Setup:+ Insert logs with data type collision scenarios to test DataTypeCollisionHandledFieldName function++ Tests:+ 1. severity_number comparison with string value+ 2. http.status_code with mixed string/number values+ 3. response.time with string values in numeric field+ 4. Edge cases: empty strings+ """+ now = datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ logs: List[Logs] = []++ # Logs with string values in numeric fields+ severity_levels = ["DEBUG", "INFO", "WARN"]+ for i in range(3):+ logs.append(+ Logs(+ timestamp=now - timedelta(microseconds=i + 1),+ resources={+ "deployment.environment": "production",+ "service.name": "java",+ "os.type": "linux",+ "host.name": f"linux-00{i%2}",+ "cloud.provider": "integration",+ "cloud.account.id": f"00{i%2}",+ },+ attributes={+ "log.iostream": "stdout",+ "logtag": "F",+ "code.file": "/opt/Integration.java",+ "code.function": "com.example.Integration.process",+ "code.line": i + 1,+ "telemetry.sdk.language": "java",+ "http.status_code": "200", # String value+ "response.time": "123.45", # String value+ },+ body=f"Test log {i+1} with string values",+ severity_text=severity_levels[i], # DEBUG(5-8), INFO(9-12), WARN(13-16)+ )+ )++ # Logs with numeric values in string fields+ severity_levels_2 = ["ERROR", "FATAL", "TRACE", "DEBUG"]+ for i in range(4):+ logs.append(+ Logs(+ timestamp=now - timedelta(microseconds=i + 10),+ resources={+ "deployment.environment": "production",+ "service.name": "go",+ "os.type": "linux",+ "host.name": f"linux-00{i%2}",+ "cloud.provider": "integration",+ "cloud.account.id": f"00{i%2}",+ },+ attributes={+ "log.iostream": "stdout",+ "logtag": "F",+ "code.file": "/opt/integration.go",+ "code.function": "com.example.Integration.process",+ "code.line": i + 1,+ "telemetry.sdk.language": "go",+ "http.status_code": 404, # Numeric value+ "response.time": 456.78, # Numeric value+ },+ body=f"Test log {i+4} with numeric values",+ severity_text=severity_levels_2[i], # ERROR(17-20), FATAL(21-24), TRACE(1-4), DEBUG(5-8)+ )+ )++ # Edge case: empty string and zero value+ logs.append(+ Logs(+ timestamp=now - timedelta(microseconds=20),+ resources={+ "deployment.environment": "production",+ "service.name": "python",+ "os.type": "linux",+ "host.name": "linux-002",+ "cloud.provider": "integration",+ "cloud.account.id": "002",+ },+ attributes={+ "log.iostream": "stdout",+ "logtag": "F",+ "code.file": "/opt/integration.py",+ "code.function": "com.example.Integration.process",+ "code.line": 1,+ "telemetry.sdk.language": "python",+ "http.status_code": "", # Empty string+ "response.time": 0, # Zero value+ },+ body="Edge case test log",+ severity_text="ERROR",+ )+ )++ insert_logs(logs)++ token = get_jwt_token(email=USER_ADMIN_EMAIL, password=USER_ADMIN_PASSWORD)++ # count() of all logs for the where severity_number > '7'+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "severity_number > '7'"},+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ assert count == 5++ # count() of all logs for the where severity_number > '7.0'+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "severity_number > '7.0'"},+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ assert count == 5++ # Test 2: severity_number comparison with string value+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "severity_number = '13'"}, # String comparison with numeric field+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ # WARN severity maps to 13-16 range, so should find 1 log with severity_number = 13+ assert count == 1++ # Test 3: http.status_code with numeric value (query contains number, actual value is string "200")+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "http.status_code = 200"}, # Numeric comparison with string field+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ # Should return 3 logs with http.status_code = "200" (first 3 logs have string value "200")+ assert count == 3++ # Test 4: http.status_code with string value (query contains string, actual value is numeric 404)+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "http.status_code = '404'"}, # String comparison with numeric field+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ # Should return 4 logs with http.status_code = 404 (next 4 logs have numeric value 404)+ assert count == 4+++ # Test 5: Edge case - empty string comparison+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v5/query_range"),+ timeout=2,+ headers={+ "authorization": f"Bearer {token}",+ },+ json={+ "schemaVersion": "v1",+ "start": int(+ (+ datetime.now(tz=timezone.utc).replace(second=0, microsecond=0)+ - timedelta(minutes=5)+ ).timestamp()+ * 1000+ ),+ "end": int(+ datetime.now(tz=timezone.utc)+ .replace(second=0, microsecond=0)+ .timestamp()+ * 1000+ ),+ "requestType": "scalar",+ "compositeQuery": {+ "queries": [+ {+ "type": "builder_query",+ "spec": {+ "name": "A",+ "signal": "logs",+ "stepInterval": 60,+ "disabled": False,+ "filter": {"expression": "http.status_code = ''"}, # Empty string comparison+ "having": {"expression": ""},+ "aggregations": [{"expression": "count()"}],+ },+ }+ ]+ },+ "formatOptions": {"formatTableResultForUI": True, "fillGaps": False},+ },+ )++ assert response.status_code == HTTPStatus.OK+ assert response.json()["status"] == "success"++ results = response.json()["data"]["data"]["results"]+ assert len(results) == 1++ count = results[0]["data"][0][0]+ # Should return 1 log with empty http.status_code (edge case log)+ assert count == 1\ No newline at end of file