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(querier): decode JSON columns in table and graph queries (#12555)
Tushar Vats74c946fe7988
diff --git a/pkg/querier/consume.go b/pkg/querier/consume.goindex 34ee097ca1..99935b9cf8 100644--- a/pkg/querier/consume.go+++ b/pkg/querier/consume.go@@ -1,6 +1,7 @@package querierimport (+ "encoding/json""fmt""math""reflect"@@ -11,12 +12,12 @@ import ("strings""time"+ "github.com/ClickHouse/clickhouse-go/v2/lib/chcol""github.com/ClickHouse/clickhouse-go/v2/lib/driver"- "github.com/SigNoz/signoz/pkg/errors"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/spantypes"+ "github.com/SigNoz/signoz/pkg/types/telemetrystoretypes""github.com/SigNoz/signoz/pkg/types/telemetrytypes"- "github.com/bytedance/sonic")var (@@ -30,8 +31,6 @@ var (// written clickhouse query. The column alias indcate which value is// to be considered as final result (or target).legacyReservedColumnTargetAliases = []string{"__result", "__value", "result", "res", "value"}-- CodeFailUnmarshalJSONColumn = errors.MustNewCode("fail_unmarshal_json_column"))// stripKeyAlias removes the __SELECT_KEY_<n>_ / __GROUP_BY_KEY_<n>_ prefix from a result@@ -40,6 +39,32 @@ func stripKeyAlias(name string) string {return keyAliasRe.ReplaceAllString(name, "")}+// unwrapVariant returns the concrete value inside the chcol.Variant envelope the driver scans a+// Dynamic column — a JSON path such as body_v2.level — into.+func unwrapVariant(val any) any {+ if v, ok := val.(chcol.Variant); ok {+ return v.Any()+ }+ return val+}++// labelValue renders a group-by value the payload cannot carry as a scalar — a JSON column, or a+// Dynamic one — as a stable string, so that rows differing only in that value land in different+// series. JSON goes through encoding/json for its sorted map keys: ClickHouse groups documents by+// structure, so two rows it considers equal have to produce the same label.+func labelValue(val any) string {+ val = unwrapVariant(val)+ if val == nil {+ return ""+ }+ if v, ok := val.(telemetrystoretypes.JSONValue); ok {+ if raw, err := json.Marshal(v); err == nil {+ return string(raw)+ }+ }+ return fmt.Sprint(val)+}+// consume reads every row and shapes it into the payload expected for the// given request type.//@@ -205,6 +230,14 @@ func readAsTimeSeries(rows driver.Rows, queryWindow *qbtypes.TimeRange, step qbtValue: *val,})+ case *telemetrystoretypes.JSONValue, *chcol.Variant:+ val := labelValue(derefValue(ptr))+ lblVals = append(lblVals, val)+ lblObjs = append(lblObjs, &qbtypes.Label{+ Key: telemetrytypes.TelemetryFieldKey{Name: name},+ Value: val,+ })+default:continue}@@ -345,7 +378,7 @@ func readAsScalar(rows driver.Rows, queryName string) (*qbtypes.ScalarData, erro// 2. deref each slot into the output rowrow := make([]any, len(scan))for i, cell := range scan {- row[i] = derefValue(cell)+ row[i] = unwrapVariant(derefValue(cell))}data = append(data, row)}@@ -382,31 +415,13 @@ func readAsRaw(rows driver.Rows, queryName string) (*qbtypes.RawData, error) {colTypes := rows.ColumnTypes()colCnt := len(colNames)- // Helper that decides scan target per column based on DB type- makeScanTarget := func(i int) any {- dbt := strings.ToUpper(colTypes[i].DatabaseTypeName())- if strings.HasPrefix(dbt, "JSON") {- // Since the driver fails to decode JSON/Dynamic into native Go values, we read it as raw bytes- // TODO: check in future if fixed in the driver- var v []byte- return &v- }- return reflect.New(colTypes[i].ScanType()).Interface()- }-- // Build a template slice of correctly-typed pointers once- scanTpl := make([]any, colCnt)- for i := range colTypes {- scanTpl[i] = makeScanTarget(i)- }-var outRows []*qbtypes.RawRowfor rows.Next() {// fresh copy of the scan slice (otherwise the driver reuses pointers)scan := make([]any, colCnt)- for i := range scanTpl {- scan[i] = makeScanTarget(i)+ for i := range colTypes {+ scan[i] = reflect.New(colTypes[i].ScanType()).Interface()}if err := rows.Scan(scan...); err != nil {@@ -421,21 +436,7 @@ func readAsRaw(rows driver.Rows, queryName string) (*qbtypes.RawData, error) {name := stripKeyAlias(colNames[i])// de-reference the typed pointer to any- val := reflect.ValueOf(cellPtr).Elem().Interface()- // Post-process JSON columns: unmarshal bytes into map[string]any- if strings.HasPrefix(strings.ToUpper(colTypes[i].DatabaseTypeName()), "JSON") {- switch x := val.(type) {- case []byte:- var m map[string]any- err := sonic.Unmarshal(x, &m)- if err != nil {- return nil, errors.WrapInternalf(err, CodeFailUnmarshalJSONColumn, "failed to unmarshal JSON column %s", name)- }- val = m- default:- // already a structured type (map[string]any, []any, etc.)- }- }+ val := unwrapVariant(reflect.ValueOf(cellPtr).Elem().Interface())// special-case: timestamp columnif name == "timestamp" || name == "timestamp_datetime" {diff --git a/pkg/querier/consume_test.go b/pkg/querier/consume_test.goindex 9fb5ab6132..17438a2493 100644--- a/pkg/querier/consume_test.go+++ b/pkg/querier/consume_test.go@@ -3,8 +3,16 @@ package querierimport ("reflect""testing"+ "time"+ "github.com/ClickHouse/clickhouse-go/v2/lib/chcol"+ cmock "github.com/SigNoz/clickhouse-go-mock"+ "github.com/SigNoz/signoz/pkg/telemetrystore"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5""github.com/SigNoz/signoz/pkg/types/spantypes"+ "github.com/SigNoz/signoz/pkg/types/telemetrystoretypes"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require")func TestMergeSpanAttributeColumns_ParsesEventsAndLinks(t *testing.T) {@@ -75,6 +83,103 @@ func TestMergeSpanAttributeColumns_ParsesEventsAndLinks(t *testing.T) {}}+// A ClickHouse query can put a JSON column in the result of any request type — e.g.+// `select * from signoz_logs.logs_v2` on a body_v2 stack, where `*` covers body_v2.+func TestConsume_JSONColumn(t *testing.T) {+ ts := time.Date(2026, 8, 14, 10, 0, 0, 0, time.UTC)+ body := `{"level":"error","attrs":{"code":500}}`+ wantBody := telemetrystoretypes.JSONValue{+ "level": "error",+ "attrs": map[string]any{"code": float64(500)},+ }++ // the scalar reader reuses its scan slots across rows, so each row must still carry its own body+ t.Run("scalar", func(t *testing.T) {+ rows := telemetrystore.WrapRows(cmock.NewRows([]cmock.ColumnType{+ {Name: "body_v2", Type: "JSON"},+ {Name: "__result_0", Type: "UInt64"},+ }, [][]any{{body, uint64(3)}, {`{"level":"warn"}`, uint64(1)}}))++ payload, err := consume(rows, qbtypes.RequestTypeScalar, nil, qbtypes.Step{}, "A")+ require.NoError(t, err)++ data := payload.(*qbtypes.ScalarData)+ require.Len(t, data.Data, 2)+ assert.Equal(t, wantBody, data.Data[0][0])+ assert.Equal(t, uint64(3), data.Data[0][1])+ assert.Equal(t, telemetrystoretypes.JSONValue{"level": "warn"}, data.Data[1][0])+ assert.Equal(t, uint64(1), data.Data[1][1])+ })++ t.Run("time series", func(t *testing.T) {+ rows := telemetrystore.WrapRows(cmock.NewRows([]cmock.ColumnType{+ {Name: "ts", Type: "DateTime"},+ {Name: "body_v2", Type: "JSON"},+ {Name: "__result_0", Type: "UInt64"},+ }, [][]any{{ts, body, uint64(3)}}))++ payload, err := consume(rows, qbtypes.RequestTypeTimeSeries, nil, qbtypes.Step{}, "A")+ require.NoError(t, err)++ data := payload.(*qbtypes.TimeSeriesData)+ require.Len(t, data.Aggregations, 1)+ require.Len(t, data.Aggregations[0].Series, 1)+ require.Len(t, data.Aggregations[0].Series[0].Values, 1)+ assert.Equal(t, float64(3), data.Aggregations[0].Series[0].Values[0].Value)+ })++ // grouping by a JSON column is legal in ClickHouse, so each document has to label its own+ // series rather than being dropped, which would merge every group into one+ t.Run("time series grouped by the JSON column", func(t *testing.T) {+ rows := telemetrystore.WrapRows(cmock.NewRows([]cmock.ColumnType{+ {Name: "ts", Type: "DateTime"},+ {Name: "body_v2", Type: "JSON"},+ {Name: "__result_0", Type: "UInt64"},+ }, [][]any{+ {ts, `{"level":"error"}`, uint64(7)},+ {ts, `{"level":"warn"}`, uint64(2)},+ }))++ payload, err := consume(rows, qbtypes.RequestTypeTimeSeries, nil, qbtypes.Step{}, "A")+ require.NoError(t, err)++ data := payload.(*qbtypes.TimeSeriesData)+ require.Len(t, data.Aggregations, 1)+ require.Len(t, data.Aggregations[0].Series, 2)++ got := map[string]float64{}+ for _, series := range data.Aggregations[0].Series {+ require.Len(t, series.Labels, 1)+ require.Len(t, series.Values, 1)+ got[series.Labels[0].Value.(string)] = series.Values[0].Value+ }+ assert.Equal(t, map[string]float64{`{"level":"error"}`: 7, `{"level":"warn"}`: 2}, got)+ })++ t.Run("raw", func(t *testing.T) {+ rows := telemetrystore.WrapRows(cmock.NewRows([]cmock.ColumnType{+ {Name: "timestamp", Type: "DateTime"},+ {Name: "body_v2", Type: "JSON"},+ }, [][]any{{ts, body}}))++ payload, err := consume(rows, qbtypes.RequestTypeRaw, nil, qbtypes.Step{}, "A")+ require.NoError(t, err)++ data := payload.(*qbtypes.RawData)+ require.Len(t, data.Rows, 1)+ assert.Equal(t, ts, data.Rows[0].Timestamp.UTC())+ assert.Equal(t, wantBody, data.Rows[0].Data["body_v2"])+ })+}++// A JSON path (e.g. `body_v2.level`) comes back as a Dynamic column, which the driver scans+// into a chcol.Variant envelope rather than the value itself.+func TestUnwrapVariant(t *testing.T) {+ assert.Equal(t, "error", unwrapVariant(chcol.NewDynamicWithType("error", "String")))+ assert.Nil(t, unwrapVariant(chcol.Dynamic{}))+ assert.Equal(t, uint64(3), unwrapVariant(uint64(3)))+}+func TestMergeSpanAttributeColumns_EmptyEventsAndLinks(t *testing.T) {data := map[string]any{"events": []string{},diff --git a/pkg/querier/postprocess.go b/pkg/querier/postprocess.goindex 954ef89d0f..dd5c1ee711 100644--- a/pkg/querier/postprocess.go+++ b/pkg/querier/postprocess.go@@ -13,9 +13,10 @@ import ("github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/flagger"- "github.com/SigNoz/signoz/pkg/types/featuretypes""github.com/SigNoz/signoz/pkg/querybuilder"+ "github.com/SigNoz/signoz/pkg/types/featuretypes"qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrystoretypes""github.com/SigNoz/signoz/pkg/types/telemetrytypes""github.com/SigNoz/signoz/pkg/valuer")@@ -72,9 +73,13 @@ func (q *querier) postProcessResults(ctx context.Context, orgID valuer.UUID, rescase qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:if result, ok := typedResults[spec.Name]; ok {result = postProcessBuilderQuery(q, result, spec, req)- result = q.postProcessLogBody(ctx, orgID, result, req)+ result = q.postProcessLogBody(ctx, orgID, result)typedResults[spec.Name] = result}+ case qbtypes.ClickHouseQuery:+ if result, ok := typedResults[spec.Name]; ok {+ typedResults[spec.Name] = q.postProcessLogBody(ctx, orgID, result)+ }case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:if result, ok := typedResults[spec.Name]; ok {result = postProcessMetricQuery(q, result, spec, req)@@ -1051,32 +1056,44 @@ func (q *querier) calculateFormulaStep(expression string, req *qbtypes.QueryRangreturn result}-// postProcessLogBody removes the "message" key from the body map when it is empty.-// Only runs for raw list queries with the use_json_body feature enabled.-func (q *querier) postProcessLogBody(ctx context.Context, orgID valuer.UUID, result *qbtypes.Result, req *qbtypes.QueryRangeRequest) *qbtypes.Result {- if req.RequestType != qbtypes.RequestTypeRaw {- return result- }+// postProcessLogBody removes the empty "message" the typed body path materializes into every+// document, wherever a decoded body lands in the payload — raw rows and scalar cells, under the+// column's own name or the builder's `body` alias. Only runs with the use_json_body feature+// enabled. A time-series label keeps the document verbatim: it is the group key.+func (q *querier) postProcessLogBody(ctx context.Context, orgID valuer.UUID, result *qbtypes.Result) *qbtypes.Result {if !q.fl.BooleanOrEmpty(ctx, flagger.FeatureUseJSONBody, featuretypes.NewFlaggerEvaluationContext(orgID)) {return result}- rawData, ok := result.Value.(*qbtypes.RawData)- if !ok {- return result- }- for _, row := range rawData.Rows {- bodyMap, ok := row.Data["body"].(map[string]any)- if !ok {- continue+ switch data := result.Value.(type) {+ case *qbtypes.RawData:+ for _, row := range data.Rows {+ for _, name := range []string{"body", "body_v2"} {+ stripEmptyBodyMessage(row.Data[name])+ }}- if msg, exists := bodyMap["message"]; exists {- switch v := msg.(type) {- case string:- if v == "" {- delete(bodyMap, "message")- }+ case *qbtypes.ScalarData:+ for idx, column := range data.Columns {+ if column.Name != "body" && column.Name != "body_v2" {+ continue+ }+ for _, row := range data.Data {+ stripEmptyBodyMessage(row[idx])}}}return result}++// stripEmptyBodyMessage drops `message: ""` from a decoded body document: the message path is+// typed String in the JSON column, so ClickHouse materializes it even for documents that never+// carried one. Anything that is not a decoded document — the legacy string body, a NULL cell —+// is legal under these names and left alone.+func stripEmptyBodyMessage(val any) {+ bodyMap, ok := val.(telemetrystoretypes.JSONValue)+ if !ok {+ return+ }+ if msg, ok := bodyMap["message"].(string); ok && msg == "" {+ delete(bodyMap, "message")+ }+}diff --git a/pkg/querier/querier_test.go b/pkg/querier/querier_test.goindex 17e40364d4..85913b87b7 100644--- a/pkg/querier/querier_test.go+++ b/pkg/querier/querier_test.go@@ -189,6 +189,7 @@ func TestRunExecutesQueriesConcurrently(t *testing.T) {q := &querier{logger: instrumentationtest.New().Logger(),+ fl: flaggertest.New(t),maxConcurrentQueries: numQueries,}@@ -236,6 +237,7 @@ func TestRunRespectsMaxConcurrentQueries(t *testing.T) {q := &querier{logger: instrumentationtest.New().Logger(),+ fl: flaggertest.New(t),maxConcurrentQueries: limit,}@@ -273,6 +275,7 @@ func TestRunRespectsMaxConcurrentQueries(t *testing.T) {func TestRunQueryErrorCancelsSiblings(t *testing.T) {q := &querier{logger: instrumentationtest.New().Logger(),+ fl: flaggertest.New(t),maxConcurrentQueries: 4,}diff --git a/pkg/telemetrystore/clickhousetelemetrystore/provider.go b/pkg/telemetrystore/clickhousetelemetrystore/provider.goindex 9eb2e1f0d9..edf34179f0 100644--- a/pkg/telemetrystore/clickhousetelemetrystore/provider.go+++ b/pkg/telemetrystore/clickhousetelemetrystore/provider.go@@ -184,7 +184,7 @@ func (p *provider) Query(ctx context.Context, query string, args ...interface{})}return &rowsWithHooks{- Rows: rows,+ Rows: telemetrystore.WrapRows(rows),ctx: ctx,event: event,onClose: func() { telemetrystore.WrapAfterQuery(p.hooks, ctx, event) },diff --git a/pkg/telemetrystore/rows.go b/pkg/telemetrystore/rows.gonew file mode 100644index 0000000000..194557a908--- /dev/null+++ b/pkg/telemetrystore/rows.go@@ -0,0 +1,39 @@+package telemetrystore++import (+ "reflect"+ "strings"++ "github.com/ClickHouse/clickhouse-go/v2/lib/driver"+ "github.com/SigNoz/signoz/pkg/types/telemetrystoretypes"+)++// WrapRows reports JSONValue as the scan type of every JSON column. Nested JSON — Array(JSON),+// Map(String, JSON) — is not covered.+func WrapRows(rows driver.Rows) driver.Rows {+ return &rowsWithJSONScanType{Rows: rows}+}++type rowsWithJSONScanType struct {+ driver.Rows+}++func (r *rowsWithJSONScanType) ColumnTypes() []driver.ColumnType {+ colTypes := r.Rows.ColumnTypes()+ wrapped := make([]driver.ColumnType, len(colTypes))+ for i, colType := range colTypes {+ wrapped[i] = colType+ if strings.HasPrefix(strings.ToUpper(colType.DatabaseTypeName()), "JSON") {+ wrapped[i] = jsonColumnType{ColumnType: colType}+ }+ }+ return wrapped+}++type jsonColumnType struct {+ driver.ColumnType+}++func (jsonColumnType) ScanType() reflect.Type {+ return reflect.TypeFor[telemetrystoretypes.JSONValue]()+}diff --git a/pkg/telemetrystore/telemetrystoretest/conn.go b/pkg/telemetrystore/telemetrystoretest/conn.gonew file mode 100644index 0000000000..601aef5282--- /dev/null+++ b/pkg/telemetrystore/telemetrystoretest/conn.go@@ -0,0 +1,23 @@+package telemetrystoretest++import (+ "context"++ "github.com/ClickHouse/clickhouse-go/v2"+ "github.com/ClickHouse/clickhouse-go/v2/lib/driver"+ "github.com/SigNoz/signoz/pkg/telemetrystore"+)++// conn wraps rows the way the clickhouse provider does, so mocked JSON columns report the scan+// type they do in production.+type conn struct {+ clickhouse.Conn+}++func (c conn) Query(ctx context.Context, query string, args ...any) (driver.Rows, error) {+ rows, err := c.Conn.Query(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ return telemetrystore.WrapRows(rows), nil+}diff --git a/pkg/telemetrystore/telemetrystoretest/provider.go b/pkg/telemetrystore/telemetrystoretest/provider.goindex db73cee285..6aeb52bb91 100644--- a/pkg/telemetrystore/telemetrystoretest/provider.go+++ b/pkg/telemetrystore/telemetrystoretest/provider.go@@ -32,7 +32,7 @@ func New(_ telemetrystore.Config, matcher sqlmock.QueryMatcher) *Provider {// ClickhouseDB returns the mock Clickhouse connection.func (p *Provider) ClickhouseDB() clickhouse.Conn {- return p.clickhouseDB.(clickhouse.Conn)+ return conn{Conn: p.clickhouseDB.(clickhouse.Conn)}}// Cluster returns the cluster name.diff --git a/pkg/types/telemetrystoretypes/json.go b/pkg/types/telemetrystoretypes/json.gonew file mode 100644index 0000000000..ea44f5cd7a--- /dev/null+++ b/pkg/types/telemetrystoretypes/json.go@@ -0,0 +1,37 @@+package telemetrystoretypes++import (+ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/bytedance/sonic"+)++var ErrCodeUnmarshalJSONColumn = errors.MustNewCode("fail_unmarshal_json_column")++// JSONValue is the scan target for a ClickHouse JSON column: the connection sets+// output_format_native_write_json_as_string, so the column arrives as a raw document rather than+// the chcol.JSON the driver reports as its scan type.+type JSONValue map[string]any++// Scan decodes into a fresh map every time: a scan target is reused across rows, and unmarshalling+// into the map already there would both keep its keys and hand every row the same map.+func (v *JSONValue) Scan(src any) error {+ var raw []byte+ switch value := src.(type) {+ case nil:+ *v = nil+ return nil+ case string:+ raw = []byte(value)+ case []byte:+ raw = value+ default:+ return errors.NewInternalf(ErrCodeUnmarshalJSONColumn, "cannot decode %T as a JSON column", src)+ }++ decoded := JSONValue{}+ if err := sonic.Unmarshal(raw, &decoded); err != nil {+ return errors.WrapInternalf(err, ErrCodeUnmarshalJSONColumn, "failed to unmarshal JSON column")+ }+ *v = decoded+ return nil+}diff --git a/tests/integration/tests/querier_json_body/06_json_column_scan.py b/tests/integration/tests/querier_json_body/06_json_column_scan.pynew file mode 100644index 0000000000..96ccc108fb--- /dev/null+++ b/tests/integration/tests/querier_json_body/06_json_column_scan.py@@ -0,0 +1,159 @@+import json+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from http import HTTPStatus++from fixtures import querier, types+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD+from fixtures.logs import Logs++# A raw ClickHouse query is the one place a JSON column can land in a scalar or+# time-series result: the builder only selects body_v2 in raw list queries.++DOC_ERROR = {"level": "error", "attrs": {"code": 500}}+DOC_WARN = {"level": "warn"}++SERVICE = "json-column-scan"+WHERE = f"resources_string['service.name'] = '{SERVICE}'"+++def test_clickhouse_scalar_with_json_column(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+) -> None:+ """A scalar result carrying the body_v2 JSON column decodes it into an object."""+ now = datetime.now(tz=UTC)+ insert_logs(+ [+ Logs(+ timestamp=now - timedelta(seconds=seconds),+ resources={"service.name": SERVICE},+ body_v2=json.dumps(doc, separators=(",", ":")),+ body_promoted="",+ severity_text="INFO",+ )+ for seconds, doc in [(3, DOC_ERROR), (2, DOC_ERROR), (1, DOC_WARN)]+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ start_ms = int((now - timedelta(minutes=10)).timestamp() * 1000)+ end_ms = int(now.timestamp() * 1000)++ # `select *` picks up body_v2 without naming it+ response = querier.make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [+ {+ "type": "clickhouse_sql",+ "spec": {+ "name": "A",+ "query": f"SELECT * FROM signoz_logs.distributed_logs_v2 WHERE {WHERE} ORDER BY timestamp LIMIT 1",+ "disabled": False,+ },+ }+ ],+ request_type=querier.RequestType.SCALAR,+ )++ assert response.status_code == HTTPStatus.OK, response.text+ assert response.json()["status"] == "success"++ columns = [column["name"] for column in querier.get_scalar_columns(response.json())]+ rows = querier.get_scalar_table_data(response.json())+ assert len(rows) == 1+ assert rows[0][columns.index("body_v2")] == DOC_ERROR++ # a JSON column is a legal GROUP BY key, so it can sit next to an aggregation+ response = querier.make_query_request(+ signoz,+ token,+ start_ms,+ end_ms,+ [+ {+ "type": "clickhouse_sql",+ "spec": {+ "name": "A",+ "query": f"SELECT body_v2, count() AS __result_0 FROM signoz_logs.distributed_logs_v2 WHERE {WHERE} GROUP BY body_v2",+ "disabled": False,+ },+ }+ ],+ request_type=querier.RequestType.SCALAR,+ )++ assert response.status_code == HTTPStatus.OK, response.text+ assert response.json()["status"] == "success"++ rows = querier.get_scalar_table_data(response.json())+ counts = {json.dumps(row[0], sort_keys=True): row[1] for row in rows}+ assert counts == {+ json.dumps(DOC_ERROR, sort_keys=True): 2,+ json.dumps(DOC_WARN, sort_keys=True): 1,+ }+++def test_clickhouse_time_series_grouped_by_json_column(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ insert_logs: Callable[[list[Logs]], None],+) -> None:+ """Grouping a graph by the JSON column labels each series with its document."""+ now = datetime.now(tz=UTC)+ insert_logs(+ [+ Logs(+ timestamp=now - timedelta(seconds=seconds),+ resources={"service.name": SERVICE},+ body_v2=json.dumps(doc, separators=(",", ":")),+ body_promoted="",+ severity_text="INFO",+ )+ for seconds, doc in [(3, DOC_ERROR), (2, DOC_ERROR), (1, DOC_WARN)]+ ]+ )+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = querier.make_query_request(+ signoz,+ token,+ int((now - timedelta(minutes=10)).timestamp() * 1000),+ int(now.timestamp() * 1000),+ [+ {+ "type": "clickhouse_sql",+ "spec": {+ "name": "A",+ "query": (f"SELECT toStartOfInterval(fromUnixTimestamp64Nano(timestamp), INTERVAL 60 SECOND) AS ts, body_v2, count() AS __result_0 FROM signoz_logs.distributed_logs_v2 WHERE {WHERE} GROUP BY ts, body_v2"),+ "disabled": False,+ },+ }+ ],+ request_type=querier.RequestType.TIME_SERIES,+ )++ assert response.status_code == HTTPStatus.OK, response.text+ assert response.json()["status"] == "success"++ series = querier.get_all_series(response.json(), "A")+ assert len(series) == 2++ # One series per document, labelled with the document rendered with sorted keys. The label is+ # the verbatim group key, so it keeps the `message: ""` the typed body path materializes into+ # every document; points may split across minute buckets, so compare the per-series sum.+ counts = {}+ for single_series in series:+ labels = single_series["labels"]+ assert len(labels) == 1+ assert labels[0]["key"]["name"] == "body_v2"+ counts[labels[0]["value"]] = sum(point["value"] for point in single_series["values"])+ assert counts == {+ json.dumps(DOC_ERROR | {"message": ""}, sort_keys=True, separators=(",", ":")): 2,+ json.dumps(DOC_WARN | {"message": ""}, sort_keys=True, separators=(",", ":")): 1,+ }