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.

refactor(qb): build IN as an OR of equalities (#12504)

Tushar Vats092e0b7d999f
diff --git a/pkg/statementbuilder/logsstatementbuilder/stmt_builder_test.go b/pkg/statementbuilder/logsstatementbuilder/stmt_builder_test.go
index 05f959675f..d22f7c12ce 100644
--- a/pkg/statementbuilder/logsstatementbuilder/stmt_builder_test.go
+++ b/pkg/statementbuilder/logsstatementbuilder/stmt_builder_test.go
@@ -469,6 +469,8 @@ func TestStatementBuilderListQueryResourceTests(t *testing.T) {
expectedErr: nil,
},
{
+ // The `[*]` path is extracted per value, not as an Array(String) compared to a
+ // scalar — ClickHouse rejects that outright (code 130).
name: "IN operator with json search",
requestType: qbtypes.RequestTypeRaw,
query: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
@@ -479,7 +481,7 @@ func TestStatementBuilderListQueryResourceTests(t *testing.T) {
Limit: 10,
},
expected: qbtypes.Statement{
- Query: "SELECT timestamp, id, trace_id, span_id, trace_flags, severity_text, severity_number, scope_name, scope_version, body, attributes_string, attributes_number, attributes_bool, resources_string, scope_string FROM signoz_logs.distributed_logs_v2 WHERE ((JSONExtract(JSON_QUERY(body, '$.\"user_names\"[*]'), 'Array(String)') = ?) AND JSON_EXISTS(body, '$.\"user_names\"[*]')) AND timestamp >= ? AND ts_bucket_start >= ? AND timestamp < ? AND ts_bucket_start <= ? LIMIT ?",
+ Query: "SELECT timestamp, id, trace_id, span_id, trace_flags, severity_text, severity_number, scope_name, scope_version, body, attributes_string, attributes_number, attributes_bool, resources_string, scope_string FROM signoz_logs.distributed_logs_v2 WHERE ((JSON_VALUE(body, '$.\"user_names\"[*]') = ?) AND JSON_EXISTS(body, '$.\"user_names\"[*]')) AND timestamp >= ? AND ts_bucket_start >= ? AND timestamp < ? AND ts_bucket_start <= ? LIMIT ?",
Args: []any{"john_doe", "1747947419000000000", uint64(1747945619), "1747983448000000000", uint64(1747983448), 10},
Warnings: []string{querybuilder.NewKeyNotFoundWarning("user_names[*]")},
},
diff --git a/pkg/telemetryschema/audittelemetryschema/condition_builder.go b/pkg/telemetryschema/audittelemetryschema/condition_builder.go
index 0fc46888d0..daab4c1dd0 100644
--- a/pkg/telemetryschema/audittelemetryschema/condition_builder.go
+++ b/pkg/telemetryschema/audittelemetryschema/condition_builder.go
@@ -94,7 +94,11 @@ func (c *conditionBuilder) conditionFor(
}
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.E(fieldExpression, value))
+ cond, err := c.conditionFor(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.Or(conditions...), nil
case qbtypes.FilterOperatorNotIn:
@@ -104,7 +108,11 @@ func (c *conditionBuilder) conditionFor(
}
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.NE(fieldExpression, value))
+ cond, err := c.conditionFor(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorNotEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.And(conditions...), nil
case qbtypes.FilterOperatorExists, qbtypes.FilterOperatorNotExists:
diff --git a/pkg/telemetryschema/logstelemetryschema/condition_builder.go b/pkg/telemetryschema/logstelemetryschema/condition_builder.go
index 314430ade5..4df02008e5 100644
--- a/pkg/telemetryschema/logstelemetryschema/condition_builder.go
+++ b/pkg/telemetryschema/logstelemetryschema/condition_builder.go
@@ -410,7 +410,11 @@ func (c *conditionBuilder) conditionForResolvedKey(
// instead of using IN, we use `=` + `OR` to make use of index
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.E(fieldExpression, value))
+ cond, err := c.conditionForResolvedKey(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.Or(conditions...), nil
case qbtypes.FilterOperatorNotIn:
@@ -421,7 +425,11 @@ func (c *conditionBuilder) conditionForResolvedKey(
// instead of using NOT IN, we use `!=` + `AND` to make use of index
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.NE(fieldExpression, value))
+ cond, err := c.conditionForResolvedKey(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorNotEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.And(conditions...), nil
diff --git a/pkg/telemetryschema/logstelemetryschema/condition_builder_test.go b/pkg/telemetryschema/logstelemetryschema/condition_builder_test.go
index 692f1eb7a8..c2eeefc47f 100644
--- a/pkg/telemetryschema/logstelemetryschema/condition_builder_test.go
+++ b/pkg/telemetryschema/logstelemetryschema/condition_builder_test.go
@@ -905,3 +905,52 @@ func TestConditionForJSONBodySearch(t *testing.T) {
})
}
}
+
+// IN on the body column routes each value back through the `=` path; the SQL it produces
+// must stay what the shared IN handling produced before, including for a mixed-type list.
+func TestConditionForBodyIn(t *testing.T) {
+ testCases := []struct {
+ name string
+ values []any
+ expectedSQL string
+ expectedArgs []any
+ }{
+ {
+ name: "strings",
+ values: []any{"alpha", "beta"},
+ expectedSQL: "(body = ? OR body = ?)",
+ expectedArgs: []any{"alpha", "beta"},
+ },
+ {
+ name: "mixed types are stringified before they reach the column",
+ values: []any{"alpha", float64(1), true},
+ expectedSQL: "(body = ? OR body = ? OR body = ?)",
+ expectedArgs: []any{"alpha", "1", "true"},
+ },
+ }
+
+ fl := flaggertest.New(t)
+ fm := NewFieldMapper(fl)
+ conditionBuilder := NewConditionBuilder(fm, fl)
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ key := telemetrytypes.TelemetryFieldKey{
+ Name: "body",
+ FieldContext: telemetrytypes.FieldContextLog,
+ FieldDataType: telemetrytypes.FieldDataTypeString,
+ }
+ sb := sqlbuilder.NewSelectBuilder()
+ sb.Select("1").From("t")
+ cond, _, err := conditionBuilder.ConditionFor(context.Background(), valuer.UUID{}, 0, 0, &key,
+ map[string][]*telemetrytypes.TelemetryFieldKey{key.Name: {&key}}, qbtypes.ConditionBuilderOptions{},
+ qbtypes.FilterOperatorIn, tc.values, sb)
+ require.NoError(t, err)
+ sb.Where(cond...)
+
+ sql, args := sb.BuildWithFlavor(sqlbuilder.ClickHouse)
+ assert.Contains(t, sql, tc.expectedSQL)
+ assert.Equal(t, tc.expectedArgs, args)
+ })
+ }
+}
diff --git a/pkg/telemetryschema/tracestelemetryschema/condition_builder.go b/pkg/telemetryschema/tracestelemetryschema/condition_builder.go
index 3b36c4f3a4..bd4a4176ed 100644
--- a/pkg/telemetryschema/tracestelemetryschema/condition_builder.go
+++ b/pkg/telemetryschema/tracestelemetryschema/condition_builder.go
@@ -135,7 +135,11 @@ func (c *conditionBuilder) conditionFor(
// instead of using IN, we use `=` + `OR` to make use of index
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.E(fieldExpression, value))
+ cond, err := c.conditionFor(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.Or(conditions...), nil
case qbtypes.FilterOperatorNotIn:
@@ -146,7 +150,11 @@ func (c *conditionBuilder) conditionFor(
// instead of using NOT IN, we use `!=` + `AND` to make use of index
conditions := []string{}
for _, value := range values {
- conditions = append(conditions, sb.NE(fieldExpression, value))
+ cond, err := c.conditionFor(ctx, orgID, startNs, endNs, key, qbtypes.FilterOperatorNotEqual, value, sb)
+ if err != nil {
+ return "", err
+ }
+ conditions = append(conditions, cond)
}
return sb.And(conditions...), nil
diff --git a/tests/integration/tests/querierlogs/06_json_body.py b/tests/integration/tests/querierlogs/06_json_body.py
index ac08f7849b..851fd35f0f 100644
--- a/tests/integration/tests/querierlogs/06_json_body.py
+++ b/tests/integration/tests/querierlogs/06_json_body.py
@@ -3,11 +3,13 @@ from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
+import pytest
import requests
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
from fixtures.logs import Logs
+from fixtures.querier import build_order_by, build_raw_query, get_rows, make_query_request
def test_logs_json_body_simple_searches(
@@ -911,3 +913,61 @@ def test_logs_json_body_listing(
assert len(results) == 1
count = results[0]["data"][0][0]
assert count == 4 # 4 logs have status="success"
+
+
+ "expression,expected_services",
+ [
+ pytest.param("body.service IN ['auth', 'payment']", {"auth", "payment"}, id="in_scalar_path"),
+ pytest.param("body.status IN [200, 500]", {"auth", "payment"}, id="in_number_path"),
+ pytest.param("body.service NOT IN ['auth']", {"payment", "search"}, id="not_in_scalar_path"),
+ # An `[]` path is extracted as an array. Comparing that array to each scalar in the
+ # list is something ClickHouse rejects outright (code 130), so this shape used to
+ # fail the whole query; per-value extraction reads the first element instead.
+ pytest.param("body.user_names[*] IN ['alpha', 'gamma']", {"auth", "payment"}, id="in_array_path"),
+ ],
+)
+def test_logs_json_body_in_operator(
+ signoz: types.SigNoz,
+ create_user_admin: None, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ insert_logs: Callable[[list[Logs]], None],
+ expression: str,
+ expected_services: set[str],
+) -> None:
+ """IN over a body JSON path fans out to one comparison per value."""
+ now = datetime.now(tz=UTC).replace(second=0, microsecond=0)
+ specs = [("auth", 200, ["alpha", "beta"]), ("payment", 500, ["gamma"]), ("search", 404, ["beta", "alpha"])]
+ insert_logs(
+ [
+ Logs(
+ timestamp=now - timedelta(seconds=i + 1),
+ resources={"service.name": "api"},
+ body=json.dumps({"service": service, "status": status, "user_names": user_names}),
+ )
+ for i, (service, status, user_names) in enumerate(specs)
+ ]
+ )
+
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ response = make_query_request(
+ signoz,
+ token,
+ start_ms=int((now - timedelta(minutes=5)).timestamp() * 1000),
+ end_ms=int(now.timestamp() * 1000),
+ request_type="raw",
+ queries=[
+ build_raw_query(
+ "A",
+ "logs",
+ filter_expression=expression,
+ order=[build_order_by("timestamp", "desc")],
+ limit=100,
+ )
+ ],
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["status"] == "success"
+ # flag off: the body comes back as the raw JSON string
+ assert {json.loads(row["data"]["body"])["service"] for row in get_rows(response)} == expected_services