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(logs): stop hasToken and hasAny/hasAll 500s on separator and big-int needles (#12261)
Tushar Vats973429a22f94
diff --git a/pkg/telemetrylogs/condition_builder.go b/pkg/telemetrylogs/condition_builder.goindex 045629057e..40c97cecfd 100644--- a/pkg/telemetrylogs/condition_builder.go+++ b/pkg/telemetrylogs/condition_builder.go@@ -89,7 +89,8 @@ func (c *conditionBuilder) conditionForArrayFunction(for i, v := range list {vals[i] = legacyCoerceNeedle(v, elemType)}- arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), arrayExpr, sb.Var(vals))+ // Pin the needle array type to the haystack; scalar fallback below coerces value-level.+ arrayCond := fmt.Sprintf("%s(%s, %s)", operator.FunctionName(), arrayExpr, castNeedleArray(elemType, sb.Var(vals)))if !hasScalar {return arrayCond, nil}@@ -113,6 +114,27 @@ func (c *conditionBuilder) conditionForArrayFunction(return fmt.Sprintf("(%s OR ifNull(%s, false))", arrayCond, sb.And(sb.E(scalarExpr, typedNeedle), scalarGuard)), nil}+// castNeedleArray pins an Int64 needle array to Array(Int64) so it matches the Array(Nullable(Int64))+// haystack; without it a needle >= 2^32 binds as Array(UInt64) and hasAny/hasAll error (code 386).+func castNeedleArray(elemType telemetrytypes.FieldDataType, arg string) string {+ if elemType == telemetrytypes.FieldDataTypeInt64 {+ return fmt.Sprintf("CAST(%s AS Array(Int64))", arg)+ }+ return arg+}++// firstTokenSeparator returns the first char of s that hasToken treats as a token separator+// (anything other than an ASCII letter or digit), and whether one was found.+func firstTokenSeparator(s string) (string, bool) {+ for _, r := range s {+ isAlphaNum := (r >= '0' && r <= '9') || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')+ if !isAlphaNum {+ return string(r), true+ }+ }+ return "", false+}+// conditionForHasToken builds a hasToken full-text search over the body column, resolving the// column from the key name + use_json_body flag.func (c *conditionBuilder) conditionForHasToken(@@ -129,11 +151,19 @@ func (c *conditionBuilder) conditionForHasToken(}// hasToken matches string tokens only.- if _, ok := needle.(string); !ok {+ needleStr, ok := needle.(string)+ if !ok {return "", errors.NewInvalidInputf(errors.CodeInvalidInput,"function `hasToken` expects value parameter to be a string").WithUrl(hasTokenFunctionDocURL)}+ // A multi-token needle makes CH hasToken error (code 36); reject up front as a 400. Both modes flow here.+ if sep, found := firstTokenSeparator(needleStr); found {+ return "", errors.NewInvalidInputf(errors.CodeInvalidInput,+ "function `hasToken` matches a single whole token, but %q contains the separator %q; use a substring filter (e.g. `body CONTAINS '%s'`) to search across separators",+ needleStr, sep, needleStr).WithUrl(hasTokenFunctionDocURL)+ }+bodyJSONEnabled := c.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID))if !bodyJSONEnabled {diff --git a/pkg/telemetrylogs/filter_expr_logs_body_json_test.go b/pkg/telemetrylogs/filter_expr_logs_body_json_test.goindex bf2fd09da1..fed7735c99 100644--- a/pkg/telemetrylogs/filter_expr_logs_body_json_test.go+++ b/pkg/telemetrylogs/filter_expr_logs_body_json_test.go@@ -104,6 +104,23 @@ func TestFilterExprLogsBodyJSON(t *testing.T) {expectedArgs: []any{int64(200), int64(200)},expectedErrorContains: "",},+ {+ // Big-int needle CAST to Array(Int64) to match the haystack (else 386).+ category: "json",+ query: `hasAny(body.ids, ['9007199254740993', '9007199254740994'])`,+ shouldPass: true,+ expectedQuery: `WHERE (hasAny(JSONExtract(JSON_QUERY(body, '$."ids"[*]'), 'Array(Nullable(Int64))'), CAST(? AS Array(Int64))) OR ifNull((JSONExtract(JSON_VALUE(body, '$."ids"'), 'Nullable(Int64)') IN (?, ?) AND JSONType(body, 'ids') NOT IN ('Array', 'Object', 'Null')), false))`,+ expectedArgs: []any{[]any{int64(9007199254740993), int64(9007199254740994)}, int64(9007199254740993), int64(9007199254740994)},+ expectedErrorContains: "",+ },+ {+ category: "json",+ query: `hasAll(body.ids, ['9007199254740993', '9007199254740994'])`,+ shouldPass: true,+ expectedQuery: `WHERE (hasAll(JSONExtract(JSON_QUERY(body, '$."ids"[*]'), 'Array(Nullable(Int64))'), CAST(? AS Array(Int64))) OR ifNull(((JSONExtract(JSON_VALUE(body, '$."ids"'), 'Nullable(Int64)') = ? AND JSONExtract(JSON_VALUE(body, '$."ids"'), 'Nullable(Int64)') = ?) AND JSONType(body, 'ids') NOT IN ('Array', 'Object', 'Null')), false))`,+ expectedArgs: []any{[]any{int64(9007199254740993), int64(9007199254740994)}, int64(9007199254740993), int64(9007199254740994)},+ expectedErrorContains: "",+ },{category: "json",query: "body.message = hello",diff --git a/pkg/telemetrylogs/filter_expr_logs_test.go b/pkg/telemetrylogs/filter_expr_logs_test.goindex 3ea1a2612e..0f783c084d 100644--- a/pkg/telemetrylogs/filter_expr_logs_test.go+++ b/pkg/telemetrylogs/filter_expr_logs_test.go@@ -1561,6 +1561,19 @@ func TestFilterExprLogs(t *testing.T) {expectedArgs: []any{"download"},expectedErrorContains: "function `hasToken` expects value parameter to be a string",},+ // A multi-token needle (separator/whitespace) is a clean 400, not a CH execution error.+ {+ category: "hasTokenUnderscoreNeedle",+ query: "hasToken(body, \"user_id\")",+ shouldPass: false,+ expectedErrorContains: "function `hasToken` matches a single whole token",+ },+ {+ category: "hasTokenWhitespaceNeedle",+ query: "hasToken(body, \"production node\")",+ shouldPass: false,+ expectedErrorContains: "function `hasToken` matches a single whole token",+ },// extra / mis-shaped value arguments are rejected, not silently dropped.{category: "hasExtraArgs",diff --git a/tests/integration/tests/querier_json_body/03_body_array_functions.py b/tests/integration/tests/querier_json_body/03_body_array_functions.pyindex ad5ff4e630..72fc50723b 100644--- a/tests/integration/tests/querier_json_body/03_body_array_functions.py+++ b/tests/integration/tests/querier_json_body/03_body_array_functions.py@@ -1178,12 +1178,11 @@ def test_logs_json_body_hastoken_separator_needle_errors(export_json_types: Callable[[list[Logs]], None],needle: str,) -> None:- """KNOWN BUG (currently 500) — same defect as the flag-off path. In JSON mode hasToken searches- body.message via ClickHouse hasToken(LOWER(body.message), LOWER(?)), which rejects a needle- containing whitespace or separator characters (`.`/`_`/`-`/space) with error code 36. The needle- is passed straight through, so the query fails at execution and the raw error surfaces as a 500- instead of a 400 / graceful fallback. Flip to 400 (or a fallback match) once the needle is- validated."""+ """Same defect as the flag-off path. In JSON mode hasToken searches body.message via+ ClickHouse hasToken(LOWER(body.message), LOWER(?)), which rejects a needle containing+ whitespace or separator characters (`.`/`_`/`-`/space) with error code 36 at execution. The+ needle is validated up front, so a multi-token needle is a clean 400 (hasToken matches a single+ whole token) rather than a raw execution 500."""now = datetime.now(tz=UTC)logs = [Logs(timestamp=now - timedelta(seconds=1), resources={"service.name": "app-service"}, body_v2=json.dumps({"message": "client 192.168.1.1 user_id error-code production node"}), body_promoted="", severity_text="INFO"),@@ -1199,8 +1198,8 @@ def test_logs_json_body_hastoken_separator_needle_errors(request_type=RequestType.RAW,queries=[build_raw_query("A", "logs", order=[build_order_by("timestamp")], limit=100, filter_expression=f"hasToken(body, '{needle}')")],)- assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, f"{needle}: expected 500, got {response.status_code}: {response.text}"- assert "Needle must not contain whitespace or separator characters" in response.text, response.text+ assert response.status_code == HTTPStatus.BAD_REQUEST, f"{needle}: expected 400, got {response.status_code}: {response.text}"+ assert "matches a single whole token" in response.text, response.textdef test_logs_json_body_unregistered_path_warns(diff --git a/tests/integration/tests/querierlogs/09_json_body_functions.py b/tests/integration/tests/querierlogs/09_json_body_functions.pyindex faea6fe8dd..216e0fb632 100644--- a/tests/integration/tests/querierlogs/09_json_body_functions.py+++ b/tests/integration/tests/querierlogs/09_json_body_functions.py@@ -1197,13 +1197,11 @@ def test_logs_json_body_hastoken_separator_needle_errors(insert_logs: Callable[[list[Logs]], None],needle: str,) -> None:- """KNOWN BUG (currently 500). hasToken maps to ClickHouse hasToken(LOWER(body), LOWER(?)),- which rejects a needle containing whitespace or separator characters (`.`/`_`/`-`/space) with- error code 36 ("Needle must not contain whitespace or separator characters"). The querier- passes the user needle straight through, so the query fails during execution and the raw CH- error surfaces as a 500 rather than a 400 / graceful fallback. Common needles like an IP,- `user_id` or a UUID hit this. Flip this to 400 (or a fallback match) once the needle is- validated."""+ """hasToken maps to ClickHouse hasToken(LOWER(body), LOWER(?)), which rejects a needle+ containing whitespace or separator characters (`.`/`_`/`-`/space) with error code 36 at+ execution. The querier validates the needle up front and returns a clean 400 (hasToken matches+ a single whole token) instead of letting the raw CH error surface as a 500. Common needles like+ an IP, `user_id` or a UUID hit this."""now = datetime.now(tz=UTC)insert_logs([@@ -1219,8 +1217,8 @@ def test_logs_json_body_hastoken_separator_needle_errors(request_type=RequestType.RAW,queries=[build_raw_query("A", "logs", order=[build_order_by("timestamp")], limit=100, filter_expression=f"hasToken(body, '{needle}')")],)- assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, f"{needle}: expected 500, got {response.status_code}: {response.text}"- assert "Needle must not contain whitespace or separator characters" in response.text, response.text+ assert response.status_code == HTTPStatus.BAD_REQUEST, f"{needle}: expected 400, got {response.status_code}: {response.text}"+ assert "matches a single whole token" in response.text, response.text@pytest.mark.parametrize(@@ -1230,20 +1228,18 @@ def test_logs_json_body_hastoken_separator_needle_errors(pytest.param("hasAll", id="hasall"),],)-def test_logs_json_body_hasany_hasall_large_quoted_int_errors(+def test_logs_json_body_hasany_hasall_large_quoted_int_matches(signoz: types.SigNoz,create_user_admin: None, # pylint: disable=unused-argumentget_token: Callable[[str, str], str],insert_logs: Callable[[list[Logs]], None],func: str,) -> None:- """KNOWN BUG (currently 500). A quoted integer needle >= 2^32 in hasAny/hasAll fails with- ClickHouse code 386 ("no supertype for types UInt64, Int64") -> 500. The body array is- extracted as Array(Nullable(Int64)), but the needle array is bound as Array(UInt64) for values- that don't fit UInt32, and CH has no Int64/UInt64 supertype at the array-vs-array type level.- Single has() is unaffected because scalar-vs-array coercion is value-level (asserted below as a- contrast). When fixed (bind the needle array as Int64) this should return 200 with an exact- match like has()."""+ """A quoted integer needle >= 2^32 in hasAny/hasAll used to 500: the body array is extracted as+ Array(Nullable(Int64)) but the needle array bound as a concrete Array(UInt64), and CH has no+ Int64/UInt64 supertype at the array-vs-array level (code 386). The needle array is now CAST to+ Array(Int64) to match the extraction, so it returns 200 with an exact match like has() (asserted+ below as a contrast)."""now = datetime.now(tz=UTC)insert_logs([@@ -1254,7 +1250,7 @@ def test_logs_json_body_hasany_hasall_large_quoted_int_errors(start_ms = int((now - timedelta(seconds=10)).timestamp() * 1000)end_ms = int(now.timestamp() * 1000)- # hasAny/hasAll with a quoted big int (>= 2^32) -> 500 (no supertype).+ # hasAny/hasAll with a quoted big int (>= 2^32) -> 200 with an exact match (needle CAST to Int64).response = make_query_request(signoz,token,@@ -1263,7 +1259,8 @@ def test_logs_json_body_hasany_hasall_large_quoted_int_errors(request_type=RequestType.RAW,queries=[build_raw_query("A", "logs", order=[build_order_by("timestamp")], limit=100, filter_expression=f"{func}(body.id, ['9007199254740993'])")],)- assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR, f"{func}: expected 500, got {response.status_code}: {response.text}"+ assert response.status_code == HTTPStatus.OK, f"{func}: expected 200, got {response.status_code}: {response.text}"+ assert len(get_rows(response)) == 1, f"{func} with a quoted big int should match exactly one log"# Contrast: single has() with the same quoted big int works (exact Int64 match, 1 row).response = make_query_request(