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
chore(deps): bump clickhouse-sql-parser to v0.5.2 (#12303)
Pandey44828b41851a
diff --git a/go.mod b/go.modindex 05317e8baf..28e35ccae3 100644--- a/go.mod+++ b/go.mod@@ -4,7 +4,7 @@ go 1.25.7require (dario.cat/mergo v1.0.2- github.com/AfterShip/clickhouse-sql-parser v0.4.16+ github.com/AfterShip/clickhouse-sql-parser v0.5.2github.com/ClickHouse/clickhouse-go/v2 v2.44.0github.com/DATA-DOG/go-sqlmock v1.5.2github.com/SigNoz/clickhouse-go-mock v0.14.0diff --git a/go.sum b/go.sumindex a3604cc7b6..27e365204c 100644--- a/go.sum+++ b/go.sum@@ -66,8 +66,8 @@ dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=-github.com/AfterShip/clickhouse-sql-parser v0.4.16 h1:gpl+wXclYUKT0p4+gBq22XeRYWwEoZ9f35vogqMvkLQ=-github.com/AfterShip/clickhouse-sql-parser v0.4.16/go.mod h1:W0Z82wJWkJxz2RVun/RMwxue3g7ut47Xxl+SFqdJGus=+github.com/AfterShip/clickhouse-sql-parser v0.5.2 h1:KCxdmvuVawVF4yl0ZS33q7olgmLZwvZG5BjWHp6o414=+github.com/AfterShip/clickhouse-sql-parser v0.5.2/go.mod h1:Qi3qvPTfZb/aFwI5V4WFOahgjsLJa4MzVijIAfwOhDw=github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU=github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28=github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA=diff --git a/pkg/querybuilder/agg_rewrite.go b/pkg/querybuilder/agg_rewrite.goindex c4c26f183c..3dff48b9e9 100644--- a/pkg/querybuilder/agg_rewrite.go+++ b/pkg/querybuilder/agg_rewrite.go@@ -96,9 +96,9 @@ func (r *aggExprRewriter) Rewrite(}if visitor.isRate {- return fmt.Sprintf("%s/%d", sel.SelectItems[0].String(), rateInterval), visitor.chArgs, nil+ return fmt.Sprintf("%s/%d", chparser.Format(sel.SelectItems[0]), rateInterval), visitor.chArgs, nil}- return sel.SelectItems[0].String(), visitor.chArgs, nil+ return chparser.Format(sel.SelectItems[0]), visitor.chArgs, nil}// RewriteMulti rewrites a slice of expressions.@@ -207,7 +207,7 @@ func (v *exprVisitor) VisitFunctionExpr(fn *chparser.FunctionExpr) error {// Handle *If functions with predicate + valuesif aggFunc.FuncCombinator {// Map the predicate (last argument)- origPred := args[len(args)-1].String()+ origPred := chparser.Format(args[len(args)-1])whereClause, err := PrepareWhereClause(origPred,FilterExprVisitorOpts{@@ -242,7 +242,7 @@ func (v *exprVisitor) VisitFunctionExpr(fn *chparser.FunctionExpr) error {// Map each value column argumentfor i := 0; i < len(args)-1; i++ {- origVal := args[i].String()+ origVal := chparser.Format(args[i])fieldKey := telemetrytypes.GetFieldKeyFromKeyText(origVal)expr, err := v.fieldMapper.ColumnExpressionFor(v.ctx, v.orgID, v.startNs, v.endNs, &fieldKey, dataType, v.fieldKeys)if err != nil {@@ -259,7 +259,7 @@ func (v *exprVisitor) VisitFunctionExpr(fn *chparser.FunctionExpr) error {} else {// Non-If functions: map every argument as a column/valuefor i, arg := range args {- orig := arg.String()+ orig := chparser.Format(arg)fieldKey := telemetrytypes.GetFieldKeyFromKeyText(orig)expr, err := v.fieldMapper.ColumnExpressionFor(v.ctx, v.orgID, v.startNs, v.endNs, &fieldKey, dataType, v.fieldKeys)if err != nil {diff --git a/pkg/queryparser/queryfilterextractor/clickhouse.go b/pkg/queryparser/queryfilterextractor/clickhouse.goindex cb63860ece..443abeb735 100644--- a/pkg/queryparser/queryfilterextractor/clickhouse.go+++ b/pkg/queryparser/queryfilterextractor/clickhouse.go@@ -316,17 +316,17 @@ func (e *ClickHouseFilterExtractor) extractColumnStrByExpr(expr clickhouse.Expr)// FunctionExpr is a function call like "toDate(timestamp)"case *clickhouse.FunctionExpr:// For function expressions, return the complete function call string- return ex.String()+ return clickhouse.Format(ex)// ColumnExpr is a column expression like "m.region", "toDate(timestamp)"case *clickhouse.ColumnExpr:// ColumnExpr wraps another expression - extract the underlying expressionif ex.Expr != nil {return e.extractColumnStrByExpr(ex.Expr)}- return ex.String()+ return clickhouse.Format(ex)default:// For other expression types, return the string representation- return expr.String()+ return clickhouse.Format(expr)}}@@ -524,7 +524,7 @@ func (e *ClickHouseFilterExtractor) extractFullExpression(expr clickhouse.Expr)if expr == nil {return ""}- return expr.String()+ return clickhouse.Format(expr)}// isSimpleColumnReference checks if an expression is just a simple column reference@@ -657,7 +657,7 @@ func (e *ClickHouseFilterExtractor) extractCTEName(cte *clickhouse.CTEStmt) stricase *clickhouse.Ident:return name.Namedefault:- return cte.Expr.String()+ return clickhouse.Format(cte.Expr)}}diff --git a/pkg/telemetrymetadata/stmt_parse.go b/pkg/telemetrymetadata/stmt_parse.goindex 8cd92300aa..ddd61a4649 100644--- a/pkg/telemetrymetadata/stmt_parse.go+++ b/pkg/telemetrymetadata/stmt_parse.go@@ -27,7 +27,7 @@ func (v *TelemetryFieldVisitor) VisitColumnDef(expr *parser.ColumnDef) error {}// Parse column name to extract context and data type- columnName := expr.Name.String()+ columnName := parser.Format(expr.Name)// Remove backticks if presentcolumnName = strings.TrimPrefix(columnName, "`")@@ -75,7 +75,7 @@ func (v *TelemetryFieldVisitor) VisitColumnDef(expr *parser.ColumnDef) error {// Extract field name from the DEFAULT expression// The DEFAULT expression should be something like: resources_string['k8s.cluster.name']// We need to extract the key inside the square brackets- defaultExprStr := expr.DefaultExpr.String()+ defaultExprStr := parser.Format(expr.DefaultExpr)// Look for the pattern: map['key']startIdx := strings.Index(defaultExprStr, "['")diff --git a/pkg/variables/clickhouse/processor.go b/pkg/variables/clickhouse/processor.goindex e76a2d0c30..b5113c1409 100644--- a/pkg/variables/clickhouse/processor.go+++ b/pkg/variables/clickhouse/processor.go@@ -69,7 +69,7 @@ func (qp *QueryProcessor) ProcessQuery(query string, transformer FilterTransform// Reconstruct the queryvar resultBuilder strings.Builderfor _, stmt := range stmts {- resultBuilder.WriteString(stmt.String())+ resultBuilder.WriteString(parser.Format(stmt))resultBuilder.WriteString(";")}diff --git a/tests/integration/tests/querierlogs/11_aggregation_functions.py b/tests/integration/tests/querierlogs/11_aggregation_functions.pyindex 783ad17547..09888ab0a6 100644--- a/tests/integration/tests/querierlogs/11_aggregation_functions.py+++ b/tests/integration/tests/querierlogs/11_aggregation_functions.py@@ -20,12 +20,15 @@ from fixtures.querier import (# Numeric aggregation-function coverage for logs — the logs counterpart of# queriertraces/02_aggregation.py::test_traces_aggregate_functions. Logs querier# tests elsewhere only ever use count()/count_distinct(); here a grouped scalar-# query computes sum / avg / min / max / p50 / p90 / p95 / p99 / countIf /-# count_distinct over a numeric log attribute and asserts every value.+# query computes sum / avg / min / max / p50 / p90 / p95 / p99 / countIf / rate /+# rate_sum / count_distinct over a numeric log attribute and asserts every value.## Log number attributes are stored as Float64, so aggregates come back as floats;# percentiles are matched with pytest.approx (ClickHouse quantile() and# numpy.percentile both linear-interpolate, but avoid ULP-level exact equality).+#+# The rate family divides by a window the caller does not otherwise see, so the+# lookback is passed explicitly instead of taken from the request helper default.def test_logs_aggregate_functions(@@ -41,11 +44,14 @@ def test_logs_aggregate_functions(Tests:A grouped scalar query computes count / sum / avg / min / max / p50 / p90 /- p95 / p99 over latency_ms, countIf over a numeric threshold, and- count_distinct over a string attribute — all matching values derived from the- inserted logs, ordered by count() desc.+ p95 / p99 over latency_ms, countIf over a numeric threshold, rate and+ rate_sum over the query window, and count_distinct over a string attribute —+ all matching values derived from the inserted logs, ordered by count() desc."""now = datetime.now(tz=UTC).replace(second=0, microsecond=0)+ # A scalar rate divides by the whole query window, so both sides agree on it.+ lookback_minutes = 5+ rate_interval_seconds = lookback_minutes * 60# (service, latency_ms, endpoint)specs = [("svc-a", 10, "/x"),@@ -80,12 +86,14 @@ def test_logs_aggregate_functions(build_aggregation("p95(latency_ms)", "p95_l"),build_aggregation("p99(latency_ms)", "p99_l"),build_aggregation("countIf(latency_ms >= 25)", "slow"),+ build_aggregation("rate()", "rate_all"),+ build_aggregation("rate_sum(latency_ms)", "rate_sum_l"),build_aggregation("count_distinct(endpoint)", "endpoints"),],group_by=[build_group_by_field("service.name", "string", "resource")],order=[build_order_by("count()", "desc")],)- response = make_scalar_query_request(signoz, token, now, [query])+ response = make_scalar_query_request(signoz, token, now, [query], lookback_minutes=lookback_minutes)assert response.status_code == HTTPStatus.OK, response.textdata = get_scalar_table_data(response.json())@@ -109,6 +117,12 @@ def test_logs_aggregate_functions(float(np.percentile(latencies, 95)), # p95(latency_ms)float(np.percentile(latencies, 99)), # p99(latency_ms)sum(1 for latency in latencies if latency >= 25), # countIf(latency_ms >= 25)+ # Response floats are rounded to 3 decimals at or above 1 and to 3+ # significant figures below it (roundToNonZeroDecimals). Every other+ # value here is exact; the rates are the only ones that repeat, and+ # they stay below 1 for this fixture, so mirror the latter form.+ float(f"{len(latencies) / rate_interval_seconds:.3g}"), # rate()+ float(f"{sum(latencies) / rate_interval_seconds:.3g}"), # rate_sum(latency_ms)len(set(endpoints)), # count_distinct(endpoint)]assert by_service[service] == pytest.approx(expected), f"{service}: {by_service[service]} != {expected}"diff --git a/tests/integration/tests/queriertraces/02_aggregation.py b/tests/integration/tests/queriertraces/02_aggregation.pyindex 9d3d9d6ece..37bd5da4f3 100644--- a/tests/integration/tests/queriertraces/02_aggregation.py+++ b/tests/integration/tests/queriertraces/02_aggregation.py@@ -150,12 +150,17 @@ def test_traces_aggregate_functions(Tests:A grouped scalar query computes count / sum / avg / min / max / p50 / p90 overduration_nano, countIf over the intrinsic status_code and the calculated- response_status_code, and avg over a numeric attribute — all matching values- derived from the inserted spans. Under the corrupt variant the same-named- colliding attributes must not change any of these.+ response_status_code, rate and rate_sum over the query window, and avg over a+ numeric attribute — all matching values derived from the inserted spans. Under+ the corrupt variant the same-named colliding attributes must not change any of+ these."""extra_attrs, extra_resources = trace_noise(noise)now = datetime.now(tz=UTC).replace(second=0, microsecond=0)+ # A scalar rate divides by the whole query window, so both sides agree on it.+ # Traces derives this separately from logs (telemetrytraces/statement_builder.go).+ lookback_minutes = 5+ rate_interval_seconds = lookback_minutes * 60def mk(service: str, dur_s: float, status: TracesStatusCode, rsc: str, latency: float) -> Traces:return Traces(@@ -189,6 +194,8 @@ def test_traces_aggregate_functions(build_aggregation("p50(duration_nano)", "p50_d"),build_aggregation("p90(duration_nano)", "p90_d"),build_aggregation("countIf(status_code = 2)", "errs"),+ build_aggregation("rate()", "rate_all"),+ build_aggregation("rate_sum(duration_nano)", "rate_sum_d"),build_aggregation("avg(latency_ms)", "avg_lat"),]query = build_traces_scalar_query(@@ -196,7 +203,7 @@ def test_traces_aggregate_functions(group_by=[build_group_by_field("service.name", "string", "resource")],order=[build_order_by("count()", "desc")],)- response = make_scalar_query_request(signoz, token, now, [query])+ response = make_scalar_query_request(signoz, token, now, [query], lookback_minutes=lookback_minutes)assert response.status_code == HTTPStatus.OK, response.textdata = get_scalar_table_data(response.json())@@ -214,6 +221,11 @@ def test_traces_aggregate_functions(float(np.percentile(durations, 50)), # p50(duration_nano)float(np.percentile(durations, 90)), # p90(duration_nano)sum(1 for s in group if int(s.status_code) == 2), # countIf(status_code = 2)+ # Response floats are rounded to 3 significant figures below 1 and to 3+ # decimals at or above it (roundToNonZeroDecimals). The two rates land on+ # either side of that boundary, so each mirrors its own form.+ float(f"{len(group) / rate_interval_seconds:.3g}"), # rate()+ round(sum(durations) / rate_interval_seconds, 3), # rate_sum(duration_nano)sum(latencies) / len(latencies), # avg(latency_ms))