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
feat(promote): support indexes on trace attributes and remove prefix requirement in paths (#13021)
Nikhil Soni6b1379472805
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex c728c2447c..e64a2412eb 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -13691,7 +13691,7 @@ paths:post:deprecated: falsedescription: This endpoint promotes paths of JSON columns to their promoted- columns. Each path names its promotion domain with its signal and context,+ columns. Each path names its promotion target with its signal and context,e.g. traces/attribute.operationId: PromotePathsrequestBody:@@ -13706,7 +13706,7 @@ paths:- fieldDataType: stringgranularity: 1type: ngrambf_v1(4, 1024, 2, 0)- path: body.user.name+ path: user.namepromote: truesignal: logstraces_attribute:diff --git a/frontend/src/api/generated/services/promote/index.ts b/frontend/src/api/generated/services/promote/index.tsindex b934e94b69..c9711d2e52 100644--- a/frontend/src/api/generated/services/promote/index.ts+++ b/frontend/src/api/generated/services/promote/index.ts@@ -146,7 +146,7 @@ export const invalidateListPromotedPaths = async (};/**- * This endpoint promotes paths of JSON columns to their promoted columns. Each path names its promotion domain with its signal and context, e.g. traces/attribute.+ * This endpoint promotes paths of JSON columns to their promoted columns. Each path names its promotion target with its signal and context, e.g. traces/attribute.* @summary Promote paths*/export const promotePaths = (diff --git a/pkg/apiserver/signozapiserver/promote.go b/pkg/apiserver/signozapiserver/promote.goindex d94732d89f..9e6b1a9099 100644--- a/pkg/apiserver/signozapiserver/promote.go+++ b/pkg/apiserver/signozapiserver/promote.go@@ -14,7 +14,7 @@ func (provider *provider) addPromoteRoutes(router *mux.Router) error {ID: "PromotePaths",Tags: []string{"promote"},Summary: "Promote paths",- Description: "This endpoint promotes paths of JSON columns to their promoted columns. Each path names its promotion domain with its signal and context, e.g. traces/attribute.",+ Description: "This endpoint promotes paths of JSON columns to their promoted columns. Each path names its promotion target with its signal and context, e.g. traces/attribute.",Request: new([]*promotetypes.PromotePath),RequestContentType: "application/json",RequestExamples: []handler.OpenAPIExample{@@ -25,7 +25,7 @@ func (provider *provider) addPromoteRoutes(router *mux.Router) error {{"signal": "logs","context": "body",- "path": "body.user.name",+ "path": "user.name","promote": true,"indexes": []map[string]any{{"fieldDataType": "string", "type": "ngrambf_v1(4, 1024, 2, 0)", "granularity": 1},diff --git a/pkg/modules/promote/implpromote/handler.go b/pkg/modules/promote/implpromote/handler.goindex ecba7903de..e51cfcc8bb 100644--- a/pkg/modules/promote/implpromote/handler.go+++ b/pkg/modules/promote/implpromote/handler.go@@ -32,6 +32,10 @@ func (h *handler) PromotePaths(w http.ResponseWriter, r *http.Request) {render.Error(w, err)return}+ if err := promotetypes.ValidatePromotePaths(req); err != nil {+ render.Error(w, err)+ return+ }err = h.module.PromotePaths(r.Context(), req...)if err != nil {diff --git a/pkg/modules/promote/implpromote/module.go b/pkg/modules/promote/implpromote/module.goindex 437babf7ad..f8263f7852 100644--- a/pkg/modules/promote/implpromote/module.go+++ b/pkg/modules/promote/implpromote/module.go@@ -58,16 +58,12 @@ func (m *module) listPromotedPaths(ctx context.Context, target promotetypes.Targresponse = append(response, promotetypes.PromotePath{Signal: target.Entry.Signal.StringValue(),Context: target.Entry.FieldContext.StringValue(),- Path: target.RequiredPathPrefix + path,+ Path: path,Promote: true,})}- if !target.IndexesSupported {- return response, nil- }-- indexes, err := m.metadataStore.ListLogsJSONIndexes(ctx)+ indexes, err := m.metadataStore.ListJSONIndexes(ctx, target.JSONIndexLookup())if err != nil {return nil, err}@@ -85,7 +81,7 @@ func (m *module) listPromotedPaths(ctx context.Context, target promotetypes.Targ}for i := range response {- fullPath := target.PromotedColumnPrefix() + strings.TrimPrefix(response[i].Path, target.RequiredPathPrefix)+ fullPath := target.PromotedColumnPrefix() + response[i].Pathif indexes, ok := aggr[fullPath]; ok {response[i].Indexes = indexesdelete(aggr, fullPath)@@ -95,7 +91,6 @@ func (m *module) listPromotedPaths(ctx context.Context, target promotetypes.Targfor fullPath, indexes := range aggr {path := strings.TrimPrefix(fullPath, target.BaseColumnPrefix())path = strings.TrimPrefix(path, target.PromotedColumnPrefix())- path = target.RequiredPathPrefix + pathresponse = append(response, promotetypes.PromotePath{Signal: target.Entry.Signal.StringValue(),Context: target.Entry.FieldContext.StringValue(),@@ -107,10 +102,6 @@ func (m *module) listPromotedPaths(ctx context.Context, target promotetypes.Targ}func (m *module) PromotePaths(ctx context.Context, paths ...*promotetypes.PromotePath) error {- if len(paths) == 0 {- return errors.NewInvalidInputf(errors.CodeInvalidInput, "paths cannot be empty")- }-byTarget := map[promotetypes.Target][]*promotetypes.PromotePath{}targets := []promotetypes.Target{}for _, path := range paths {@@ -118,9 +109,6 @@ func (m *module) PromotePaths(ctx context.Context, paths ...*promotetypes.Promotif err != nil {return err}- if err := path.ValidateAndSetDefaults(target); err != nil {- return err- }if _, ok := byTarget[target]; !ok {targets = append(targets, target)}@@ -194,7 +182,7 @@ func (m *module) promotePaths(ctx context.Context, target promotetypes.Target, p}indexes = append(indexes, schemamigrator.Index{Name: schemamigrator.JSONSubColumnIndexName(parentColumn, it.Path, index.JSONDataType.StringValue(), typeIndex),- Expression: schemamigrator.JSONSubColumnIndexExpr(parentColumn, it.Path, index.JSONDataType.StringValue()),+ Expression: target.IndexExpression(parentColumn, it.Path, index.JSONDataType.StringValue()),Type: index.Type,Granularity: index.Granularity,})diff --git a/pkg/modules/promote/implpromote/module_test.go b/pkg/modules/promote/implpromote/module_test.goindex f74ebf91eb..07c17b09e3 100644--- a/pkg/modules/promote/implpromote/module_test.go+++ b/pkg/modules/promote/implpromote/module_test.go@@ -36,10 +36,10 @@ func TestPromotePaths(t *testing.T) {wantPromoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalTraces: {"http.method": true, "span.operation": true}},},{- name: "MixedDomains_RecordedPerTarget",+ name: "MixedContexts_RecordedPerTarget",paths: []*promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "http.method", Promote: true},- {Signal: "logs", Context: "body", Path: "body.user.name", Promote: true},+ {Signal: "logs", Context: "body", Path: "user.name", Promote: true},},wantPromoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalTraces: {"http.method": true},@@ -51,41 +51,19 @@ func TestPromotePaths(t *testing.T) {paths: []*promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "http.method"}},wantPromoted: map[telemetrytypes.Signal]map[string]bool{},},- {- name: "InvalidIndexTypeInLaterDomain_NothingRecorded",- paths: []*promotetypes.PromotePath{- {Signal: "traces", Context: "attribute", Path: "http.method", Promote: true},- {Signal: "logs", Context: "body", Path: "body.user.name", Promote: true, Indexes: []promotetypes.WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "unsupported", Granularity: 1}}},- },- wantErr: true,- },{name: "InvalidSignal_Rejected",paths: []*promotetypes.PromotePath{{Signal: "events", Context: "attribute", Path: "http.method", Promote: true}},wantErr: true,},{- name: "UnsupportedDomain_Rejected",+ name: "UnsupportedTarget_Rejected",paths: []*promotetypes.PromotePath{{Signal: "metrics", Context: "attribute", Path: "http.method", Promote: true}},wantErr: true,},{- name: "ColumnPrefixedPath_Rejected",- paths: []*promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "attributes.http.method", Promote: true}},- wantErr: true,- },- {- name: "EmptyPath_Rejected",- paths: []*promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "", Promote: true}},- wantErr: true,- },- {- name: "EmptyRequest_Rejected",- wantErr: true,- },- {- name: "PromotesBodyPath_PrefixStripped",- paths: []*promotetypes.PromotePath{{Signal: "logs", Context: "body", Path: "body.user.name", Promote: true}},+ name: "PromotesBareBodyPath_AsIs",+ paths: []*promotetypes.PromotePath{{Signal: "logs", Context: "body", Path: "user.name", Promote: true}},wantPromoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalLogs: {"user.name": true}},},}@@ -123,43 +101,92 @@ func TestPromotePathsCreatesIndexes(t *testing.T) {wantDDLColumn string}{{- name: "NewPromotion_IndexesPromotedColumn",+ name: "LogsNewPromotion_IndexesPromotedColumn",path: &promotetypes.PromotePath{Signal: "logs",Context: "body",- Path: "body.user.name",+ Path: "user.name",Promote: true,Indexes: []promotetypes.WrappedIndex{- {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1, JSONDataType: telemetrytypes.String},},},wantDDLColumn: "dynamicElement(body_promoted.user.name",},{- name: "AlreadyPromoted_IndexesPromotedColumn",+ name: "LogsAlreadyPromoted_IndexesPromotedColumn",promoted: map[string]bool{"user.name": true},path: &promotetypes.PromotePath{Signal: "logs",Context: "body",- Path: "body.user.name",+ Path: "user.name",Indexes: []promotetypes.WrappedIndex{- {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1, JSONDataType: telemetrytypes.String},},},wantDDLColumn: "dynamicElement(body_promoted.user.name",},{- name: "UnpromotedPath_IndexesBaseColumn",+ name: "LogsUnpromotedPath_IndexesBaseColumn",path: &promotetypes.PromotePath{Signal: "logs",Context: "body",- Path: "body.user.name",+ Path: "user.name",Indexes: []promotetypes.WrappedIndex{- {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1, JSONDataType: telemetrytypes.String},},},wantDDLColumn: "dynamicElement(body_v2.user.name",},+ {+ name: "TracesNewPromotion_IndexesPromotedColumn",+ path: &promotetypes.PromotePath{+ Signal: "traces",+ Context: "attribute",+ Path: "http.method",+ Promote: true,+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1, JSONDataType: telemetrytypes.String},+ },+ },+ wantDDLColumn: "`attributes_promoted.http.method_String_ngrambf_v1` attributes_promoted.`http.method`::String",+ },+ {+ name: "TracesUnpromotedPath_IndexesBaseColumn",+ path: &promotetypes.PromotePath{+ Signal: "traces",+ Context: "attribute",+ Path: "http.method",+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1, JSONDataType: telemetrytypes.String},+ },+ },+ wantDDLColumn: "`attributes.http.method_String_ngrambf_v1` attributes.`http.method`::String",+ },+ {+ name: "BloomFilterIndex_FullTypeInDDL",+ path: &promotetypes.PromotePath{+ Signal: "logs",+ Context: "body",+ Path: "user.name",+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "bloom_filter(0.01)", Granularity: 1, JSONDataType: telemetrytypes.String},+ },+ },+ wantDDLColumn: "`body_v2.user.name_String_bloom_filter` lower(assumeNotNull(dynamicElement(body_v2.user.name, 'String'))) TYPE bloom_filter(0.01)",+ },+ {+ name: "SetIndex_FullTypeInDDL",+ path: &promotetypes.PromotePath{+ Signal: "logs",+ Context: "body",+ Path: "user.name",+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "set(100)", Granularity: 1, JSONDataType: telemetrytypes.String},+ },+ },+ wantDDLColumn: "`body_v2.user.name_String_set` lower(assumeNotNull(dynamicElement(body_v2.user.name, 'String'))) TYPE set(100)",+ },}for _, testCase := range testCases {@@ -189,18 +216,18 @@ func TestListPromotedPaths(t *testing.T) {wantPaths []promotetypes.PromotePath}{{- name: "PromotedPaths_ListedPerDomain",+ name: "PromotedPaths_ListedPerTarget",promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalLogs: {"user.name": true},telemetrytypes.SignalTraces: {"http.method": true},},wantPaths: []promotetypes.PromotePath{- {Signal: "logs", Context: "body", Path: "body.user.name", Promote: true},+ {Signal: "logs", Context: "body", Path: "user.name", Promote: true},{Signal: "traces", Context: "attribute", Path: "http.method", Promote: true},},},{- name: "SignalFilter_SkipsOtherDomains",+ name: "SignalFilter_SkipsOtherContexts",filters: promotetypes.ListPromotedPathsFilters{Signal: "traces"},promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalLogs: {"user.name": true},@@ -209,22 +236,22 @@ func TestListPromotedPaths(t *testing.T) {wantPaths: []promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "http.method", Promote: true}},},{- name: "ContextFilter_SkipsOtherDomains",+ name: "ContextFilter_SkipsOtherContexts",filters: promotetypes.ListPromotedPathsFilters{Context: "body"},promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalLogs: {"user.name": true},telemetrytypes.SignalTraces: {"http.method": true},},- wantPaths: []promotetypes.PromotePath{{Signal: "logs", Context: "body", Path: "body.user.name", Promote: true}},+ wantPaths: []promotetypes.PromotePath{{Signal: "logs", Context: "body", Path: "user.name", Promote: true}},},{- name: "ContextAliasFilter_MatchesDomain",+ name: "ContextAliasFilter_MatchesTarget",filters: promotetypes.ListPromotedPathsFilters{Signal: "traces", Context: "tag"},promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalTraces: {"http.method": true}},wantPaths: []promotetypes.PromotePath{{Signal: "traces", Context: "attribute", Path: "http.method", Promote: true}},},{- name: "IndexedPaths_MergedForSupportingDomains",+ name: "LogsIndexes_MergedWithLogsPaths",promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalLogs: {"user.name": true}},indexes: []telemetrytypes.TelemetryFieldKeySkipIndex{{@@ -248,7 +275,7 @@ func TestListPromotedPaths(t *testing.T) {{Signal: "logs",Context: "body",- Path: "body.user.name",+ Path: "user.name",Promote: true,Indexes: []promotetypes.WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},@@ -257,7 +284,7 @@ func TestListPromotedPaths(t *testing.T) {{Signal: "logs",Context: "body",- Path: "body.request.duration",+ Path: "request.duration",Indexes: []promotetypes.WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeFloat64, Type: "minmax", Granularity: 1},},@@ -282,7 +309,7 @@ func TestListPromotedPaths(t *testing.T) {{Signal: "logs",Context: "body",- Path: "body.request.duration",+ Path: "request.duration",Indexes: []promotetypes.WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeFloat64, Type: "minmax", Granularity: 1},},@@ -307,7 +334,7 @@ func TestListPromotedPaths(t *testing.T) {{Signal: "logs",Context: "body",- Path: "body.user.name",+ Path: "user.name",Promote: true,Indexes: []promotetypes.WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},@@ -315,6 +342,47 @@ func TestListPromotedPaths(t *testing.T) {},},},+ {+ name: "TracesIndexes_MergedWithTracesPaths",+ promoted: map[telemetrytypes.Signal]map[string]bool{telemetrytypes.SignalTraces: {"http.method": true}},+ indexes: []telemetrytypes.TelemetryFieldKeySkipIndex{+ {+ Name: "http.method",+ FieldContext: telemetrytypes.FieldContextAttribute,+ FieldDataType: telemetrytypes.FieldDataTypeString,+ BaseColumn: "attributes_promoted.",+ IndexType: "ngrambf_v1(4, 1024, 2, 0)",+ Granularity: 1,+ },+ {+ Name: "http.status_code",+ FieldContext: telemetrytypes.FieldContextAttribute,+ FieldDataType: telemetrytypes.FieldDataTypeFloat64,+ BaseColumn: "attributes.",+ IndexType: "minmax",+ Granularity: 1,+ },+ },+ wantPaths: []promotetypes.PromotePath{+ {+ Signal: "traces",+ Context: "attribute",+ Path: "http.method",+ Promote: true,+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},+ },+ },+ {+ Signal: "traces",+ Context: "attribute",+ Path: "http.status_code",+ Indexes: []promotetypes.WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeFloat64, Type: "minmax", Granularity: 1},+ },+ },+ },+ },}for _, testCase := range testCases {@@ -328,14 +396,14 @@ func TestListPromotedPaths(t *testing.T) {require.NoError(t, err)require.Len(t, paths, len(testCase.wantPaths))- byDomainPath := map[string]promotetypes.PromotePath{}+ byContextPath := map[string]promotetypes.PromotePath{}for _, path := range paths {- byDomainPath[path.Signal+"/"+path.Context+"/"+path.Path] = path+ byContextPath[path.Signal+"/"+path.Context+"/"+path.Path] = path}for _, want := range testCase.wantPaths {key := want.Signal + "/" + want.Context + "/" + want.Path- require.Contains(t, byDomainPath, key)- assert.Equal(t, want, byDomainPath[key])+ require.Contains(t, byContextPath, key)+ assert.Equal(t, want, byContextPath[key])}})}diff --git a/pkg/telemetrymetadata/body_json_metadata.go b/pkg/telemetrymetadata/body_json_metadata.goindex 3e82beda16..2b4d8c0f7f 100644--- a/pkg/telemetrymetadata/body_json_metadata.go+++ b/pkg/telemetrymetadata/body_json_metadata.go@@ -5,12 +5,12 @@ import ("fmt""log/slog""reflect"+ "regexp""strings""time""github.com/ClickHouse/clickhouse-go/v2/lib/chcol"schemamigrator "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"- "github.com/SigNoz/signoz-otel-collector/constants""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/logstelemetryschema"@@ -36,6 +36,24 @@ var (var logsBodyPromotedEntry = promotetypes.NewLogsBodyTarget().Entry+var logsBodyIndexLookup = promotetypes.NewLogsBodyTarget().JSONIndexLookup()++// ClickHouse stores a `col.path::Type` skip index expression as CAST(col.path, 'Type').+var simpleJSONSubColumnIndexExprRe = regexp.MustCompile(`^CAST\((?P<expr>[^()]+), '(?P<type>.+)'\)$`)++// unfoldJSONSubColumnIndexExpr accepts both the folded (lower/assumeNotNull)+// and the bare type-cast expression forms.+func unfoldJSONSubColumnIndexExpr(expr string) (string, string, error) {+ if columnExpr, columnType, err := schemamigrator.UnfoldJSONSubColumnIndexExpr(expr); err == nil {+ return columnExpr, columnType, nil+ }+ matches := simpleJSONSubColumnIndexExprRe.FindStringSubmatch(expr)+ if matches == nil {+ return "", "", errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid expression: %s", expr)+ }+ return matches[1], matches[2], nil+}+// enrichJSONKeys enriches body-context keys with promoted path info, indexes,// and JSON access plans. parentTypeCache contains parent array types (ArrayJSON/ArrayDynamic)// pre-fetched in the main UNION query.@@ -123,7 +141,7 @@ func (t *telemetryMetaStore) getJSONPathIndexes(ctx context.Context, paths ...st}// list indexes for the paths- indexes, err := t.ListLogsJSONIndexes(ctx, filteredPaths...)+ indexes, err := t.ListJSONIndexes(ctx, logsBodyIndexLookup, filteredPaths...)if err != nil {return nil, errors.WrapInternalf(err, CodeFailLoadLogsJSONIndexes, "failed to list JSON path indexes")}@@ -137,16 +155,16 @@ func (t *telemetryMetaStore) getJSONPathIndexes(ctx context.Context, paths ...streturn fieldPathToIndexes, nil}-func buildListLogsJSONIndexesQuery(cluster string, filters ...string) (string, []any) {+func buildListJSONIndexesQuery(cluster string, lookup telemetrytypes.JSONIndexLookup, filters ...string) (string, []any) {sb := sqlbuilder.Select("name", "type_full", "expr", "granularity",).From(fmt.Sprintf("clusterAllReplicas('%s', %s)", cluster, SkipIndexTableName))- sb.Where(sb.Equal("database", logstelemetryschema.DBName))- sb.Where(sb.Equal("table", logstelemetryschema.LogsV2LocalTableName))+ sb.Where(sb.Equal("database", lookup.DBName))+ sb.Where(sb.Equal("table", lookup.LocalTableName))sb.Where(sb.Or(- sb.ILike("expr", fmt.Sprintf("%%%s%%", querybuilder.FormatValueForContains(constants.BodyV2ColumnPrefix))),- sb.ILike("expr", fmt.Sprintf("%%%s%%", querybuilder.FormatValueForContains(constants.BodyPromotedColumnPrefix))),+ sb.ILike("expr", fmt.Sprintf("%%%s%%", querybuilder.FormatValueForContains(lookup.BaseColumnPrefix))),+ sb.ILike("expr", fmt.Sprintf("%%%s%%", querybuilder.FormatValueForContains(lookup.PromotedColumnPrefix))),))filterExprs := []string{}@@ -159,9 +177,9 @@ func buildListLogsJSONIndexesQuery(cluster string, filters ...string) (string, [return sb.BuildWithFlavor(sqlbuilder.ClickHouse)}-func (t *telemetryMetaStore) ListLogsJSONIndexes(ctx context.Context, filters ...string) ([]telemetrytypes.TelemetryFieldKeySkipIndex, error) {- ctx = withTelemetryContext(ctx, telemetrytypes.SignalLogs, "ListLogsJSONIndexes")- query, args := buildListLogsJSONIndexesQuery(t.telemetrystore.Cluster(), filters...)+func (t *telemetryMetaStore) ListJSONIndexes(ctx context.Context, lookup telemetrytypes.JSONIndexLookup, filters ...string) ([]telemetrytypes.TelemetryFieldKeySkipIndex, error) {+ ctx = withTelemetryContext(ctx, lookup.Signal, "ListJSONIndexes")+ query, args := buildListJSONIndexesQuery(t.telemetrystore.Cluster(), lookup, filters...)rows, err := t.telemetrystore.ClickhouseDB().Query(ctx, query, args...)if err != nil {return nil, errors.WrapInternalf(err, CodeFailLoadLogsJSONIndexes, "failed to load string indexed columns")@@ -178,7 +196,7 @@ func (t *telemetryMetaStore) ListLogsJSONIndexes(ctx context.Context, filters ..return nil, errors.WrapInternalf(err, CodeFailLoadLogsJSONIndexes, "failed to scan string indexed column")}- columnExpr, columnType, err := schemamigrator.UnfoldJSONSubColumnIndexExpr(expr)+ columnExpr, columnType, err := unfoldJSONSubColumnIndexExpr(expr)if err != nil {return nil, errors.WrapInternalf(err, CodeFailLoadLogsJSONIndexes, "failed to unfold JSON sub column index expression: %s", expr)}@@ -192,18 +210,18 @@ func (t *telemetryMetaStore) ListLogsJSONIndexes(ctx context.Context, filters ..baseColumn := ""fieldName := ""switch {- case strings.HasPrefix(columnExpr, logstelemetryschema.BodyV2ColumnPrefix):- baseColumn = logstelemetryschema.BodyV2ColumnPrefix- fieldName = strings.TrimPrefix(columnExpr, logstelemetryschema.BodyV2ColumnPrefix)- case strings.HasPrefix(columnExpr, logstelemetryschema.BodyPromotedColumnPrefix):- baseColumn = logstelemetryschema.BodyPromotedColumnPrefix- fieldName = strings.TrimPrefix(columnExpr, logstelemetryschema.BodyPromotedColumnPrefix)+ case strings.HasPrefix(columnExpr, lookup.BaseColumnPrefix):+ baseColumn = lookup.BaseColumnPrefix+ fieldName = strings.TrimPrefix(columnExpr, lookup.BaseColumnPrefix)+ case strings.HasPrefix(columnExpr, lookup.PromotedColumnPrefix):+ baseColumn = lookup.PromotedColumnPrefix+ fieldName = strings.TrimPrefix(columnExpr, lookup.PromotedColumnPrefix)}fieldName = strings.ReplaceAll(fieldName, "`", "")indexes = append(indexes, telemetrytypes.TelemetryFieldKeySkipIndex{Name: fieldName,- FieldContext: telemetrytypes.FieldContextBody,+ FieldContext: lookup.FieldContext,FieldDataType: fdt,BaseColumn: baseColumn,IndexName: name,diff --git a/pkg/telemetrymetadata/body_json_metadata_test.go b/pkg/telemetrymetadata/body_json_metadata_test.goindex 5ee7e307bb..ed6d9a4e2d 100644--- a/pkg/telemetrymetadata/body_json_metadata_test.go+++ b/pkg/telemetrymetadata/body_json_metadata_test.go@@ -2,11 +2,13 @@ package telemetrymetadataimport ("fmt"+ "strings""testing""github.com/SigNoz/signoz-otel-collector/constants""github.com/SigNoz/signoz/pkg/querybuilder""github.com/SigNoz/signoz/pkg/telemetryschema/logstelemetryschema"+ "github.com/SigNoz/signoz/pkg/types/promotetypes""github.com/stretchr/testify/require")@@ -50,10 +52,106 @@ func TestBuildListLogsJSONIndexesQuery(t *testing.T) {for _, tc := range testCases {t.Run(tc.name, func(t *testing.T) {- query, args := buildListLogsJSONIndexesQuery(tc.cluster, tc.filters...)+ query, args := buildListJSONIndexesQuery(tc.cluster, logsBodyIndexLookup, tc.filters...)require.Equal(t, tc.expectedSQL, query)require.Equal(t, tc.expectedArgs, args)})}}++func TestUnfoldJSONSubColumnIndexExpr(t *testing.T) {+ testCases := []struct {+ name string+ expr string+ wantColumn string+ wantType string+ wantErr bool+ }{+ {+ name: "LogsFoldedLower",+ expr: "lower(assumeNotNull(dynamicElement(body_v2.user.name, 'String')))",+ wantColumn: "body_v2.user.name",+ wantType: "String",+ },+ {+ name: "LogsAssumeNotNullOnly",+ expr: "assumeNotNull(dynamicElement(body_v2.request.duration, 'Float64'))",+ wantColumn: "body_v2.request.duration",+ wantType: "Float64",+ },+ {+ name: "TracesCastDottedKey",+ expr: "CAST(attributes.`http.method`, 'String')",+ wantColumn: "attributes.`http.method`",+ wantType: "String",+ },+ {+ name: "TracesCastPlainKey",+ expr: "CAST(attributes_promoted.status, 'Int64')",+ wantColumn: "attributes_promoted.status",+ wantType: "Int64",+ },+ {+ name: "UnrecognizedForm",+ expr: "toString(attributes.status)",+ wantErr: true,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ columnExpr, columnType, err := unfoldJSONSubColumnIndexExpr(tc.expr)+ if tc.wantErr {+ require.Error(t, err)+ return+ }+ require.NoError(t, err)+ require.Equal(t, tc.wantColumn, columnExpr)+ require.Equal(t, tc.wantType, columnType)+ })+ }+}++// ClickHouse stores a generated col.`path`::Type trace index expression as+// CAST(col.`path`, 'Type'), dropping quoting an identifier does not need; the+// listing must parse that stored form back into the original path.+func TestUnfoldJSONSubColumnIndexExprTracesRoundTrip(t *testing.T) {+ testCases := []struct {+ name string+ column string+ path string+ jsonDataType string+ wantExpr string+ storedExpr string+ }{+ {+ name: "DottedKey_BackticksPreservedInStorage",+ column: "attributes",+ path: "http.method",+ jsonDataType: "String",+ wantExpr: "attributes.`http.method`::String",+ storedExpr: "CAST(attributes.`http.method`, 'String')",+ },+ {+ name: "PlainKey_UnquotedInStorage",+ column: "attributes_promoted",+ path: "status",+ jsonDataType: "Int64",+ wantExpr: "attributes_promoted.`status`::Int64",+ storedExpr: "CAST(attributes_promoted.status, 'Int64')",+ },+ }++ target := promotetypes.NewTracesAttributesTarget()+ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ require.Equal(t, tc.wantExpr, target.IndexExpression(tc.column, tc.path, tc.jsonDataType))++ columnExpr, columnType, err := unfoldJSONSubColumnIndexExpr(tc.storedExpr)+ require.NoError(t, err)+ require.Equal(t, tc.column+"."+tc.path, strings.ReplaceAll(columnExpr, "`", ""))+ require.Equal(t, tc.jsonDataType, columnType)+ })+ }+}diff --git a/pkg/types/promotetypes/target.go b/pkg/types/promotetypes/target.goindex c38b06cd7b..5359731265 100644--- a/pkg/types/promotetypes/target.go+++ b/pkg/types/promotetypes/target.go@@ -1,20 +1,23 @@package promotetypesimport (+ "fmt"+ "strings"++ schemamigrator "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"+ "github.com/SigNoz/signoz/pkg/clickhousesql""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/telemetryschema/logstelemetryschema""github.com/SigNoz/signoz/pkg/telemetryschema/tracestelemetryschema""github.com/SigNoz/signoz/pkg/types/telemetrytypes")-// Target identifies a promotion domain.+// Target identifies a promotion context.type Target struct {- Entry telemetrytypes.EvolutionEntry // evolution row template; FieldName and ReleaseTime are set per write- DBName string // index DDL database, used only when IndexesSupported- LocalTableName string // index DDL local table, used only when IndexesSupported- BaseColumn string // column holding every path; indexes for unpromoted paths are created on it- RequiredPathPrefix string // prefix API paths must carry, stripped before storing; empty for bare names- IndexesSupported bool+ Entry telemetrytypes.EvolutionEntry // evolution row template; FieldName and ReleaseTime are set per write+ DBName string // index DDL database+ LocalTableName string // index DDL local table+ BaseColumn string // column holding every path; indexes for unpromoted paths are created on it}func (t Target) PromotedColumn() string { return t.Entry.ColumnName }@@ -23,18 +26,38 @@ func (t Target) BaseColumnPrefix() string { return t.BaseColumn + "." }func (t Target) PromotedColumnPrefix() string { return t.PromotedColumn() + "." }-func NewTarget(entry telemetrytypes.EvolutionEntry, dbName, localTableName, baseColumn, requiredPathPrefix string, indexesSupported bool) Target {+// IndexExpression folds logs strings to lower case over assumeNotNull for+// case-insensitive LIKE searches; traces indexes are a bare type cast.+func (t Target) IndexExpression(column, path, jsonDataType string) string {+ switch t.Entry.Signal {+ case telemetrytypes.SignalLogs:+ return schemamigrator.JSONSubColumnIndexExpr(column, path, jsonDataType)+ default:+ return simpleJSONSubColumnIndexExpr(column, path, jsonDataType)+ }+}++func (t Target) JSONIndexLookup() telemetrytypes.JSONIndexLookup {+ return telemetrytypes.JSONIndexLookup{+ Signal: t.Entry.Signal,+ FieldContext: t.Entry.FieldContext,+ DBName: t.DBName,+ LocalTableName: t.LocalTableName,+ BaseColumnPrefix: t.BaseColumnPrefix(),+ PromotedColumnPrefix: t.PromotedColumnPrefix(),+ }+}++func NewTarget(entry telemetrytypes.EvolutionEntry, dbName, localTableName, baseColumn string) Target {return Target{- Entry: entry,- DBName: dbName,- LocalTableName: localTableName,- BaseColumn: baseColumn,- RequiredPathPrefix: requiredPathPrefix,- IndexesSupported: indexesSupported,+ Entry: entry,+ DBName: dbName,+ LocalTableName: localTableName,+ BaseColumn: baseColumn,}}-// NewLogsBodyTarget returns the logs body domain (body_v2 -> body_promoted).+// NewLogsBodyTarget returns the logs body context (body_v2 -> body_promoted).func NewLogsBodyTarget() Target {return NewTarget(telemetrytypes.EvolutionEntry{@@ -46,12 +69,10 @@ func NewLogsBodyTarget() Target {logstelemetryschema.DBName,logstelemetryschema.LogsV2LocalTableName,logstelemetryschema.LogsV2BodyV2Column,- telemetrytypes.BodyJSONStringSearchPrefix,- true,)}-// NewTracesAttributesTarget returns the spans attributes domain (attributes+// NewTracesAttributesTarget returns the spans attributes context (attributes// -> attributes_promoted).func NewTracesAttributesTarget() Target {return NewTarget(@@ -64,8 +85,6 @@ func NewTracesAttributesTarget() Target {tracestelemetryschema.DBName,tracestelemetryschema.SpanIndexV3LocalTableName,tracestelemetryschema.SpanAttributesColumn,- "",- false,)}@@ -101,3 +120,27 @@ func TargetFor(signal telemetrytypes.Signal, context telemetrytypes.FieldContext}return Target{}, false}++// simpleJSONSubColumnIndexExpr renders column.`path`::Type with the path+// quoted as one identifier, the form trace queries read the sub-column with;+// the cast unwraps the Nullable the sub-column access returns, which bloom+// filter indexes reject.+func simpleJSONSubColumnIndexExpr(column, path, jsonDataType string) string {+ return fmt.Sprintf("%s.%s::%s", column, clickhousesql.Identifier(path), jsonDataType)+}++// reservedPathPrefix returns the target prefix path carries, if any: the base+// or promoted column prefix, or the logs body search alias, which is stripped+// from queries before metadata lookup and can never match.+func (t Target) reservedPathPrefix(path string) (string, bool) {+ prefixes := []string{t.BaseColumnPrefix(), t.PromotedColumnPrefix()}+ if t.Entry.Signal == telemetrytypes.SignalLogs {+ prefixes = append(prefixes, telemetrytypes.BodyJSONStringSearchPrefix)+ }+ for _, prefix := range prefixes {+ if strings.HasPrefix(path, prefix) {+ return prefix, true+ }+ }+ return "", false+}diff --git a/pkg/types/promotetypes/target_test.go b/pkg/types/promotetypes/target_test.gonew file mode 100644index 0000000000..3fa7631d4e--- /dev/null+++ b/pkg/types/promotetypes/target_test.go@@ -0,0 +1,57 @@+package promotetypes++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestIndexExpression(t *testing.T) {+ testCases := []struct {+ name string+ target Target+ column string+ path string+ jsonDataType string+ want string+ }{+ {+ name: "LogsString_LoweredOverAssumeNotNull",+ target: NewLogsBodyTarget(),+ column: "body_promoted",+ path: "user.name",+ jsonDataType: "String",+ want: "lower(assumeNotNull(dynamicElement(body_promoted.user.name, 'String')))",+ },+ {+ name: "LogsNumber_AssumeNotNullOnly",+ target: NewLogsBodyTarget(),+ column: "body_v2",+ path: "request.duration",+ jsonDataType: "Float64",+ want: "assumeNotNull(dynamicElement(body_v2.request.duration, 'Float64'))",+ },+ {+ name: "TracesString_TypeCastOnly",+ target: NewTracesAttributesTarget(),+ column: "attributes_promoted",+ path: "http.method",+ jsonDataType: "String",+ want: "attributes_promoted.`http.method`::String",+ },+ {+ name: "TracesPathNeedingBackticks_Backticked",+ target: NewTracesAttributesTarget(),+ column: "attributes",+ path: "user-name",+ jsonDataType: "String",+ want: "attributes.`user-name`::String",+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Equal(t, testCase.want, testCase.target.IndexExpression(testCase.column, testCase.path, testCase.jsonDataType))+ })+ }+}diff --git a/pkg/types/promotetypes/types.go b/pkg/types/promotetypes/types.goindex ad79e0f4d3..75b44ced9f 100644--- a/pkg/types/promotetypes/types.go+++ b/pkg/types/promotetypes/types.go@@ -1,6 +1,8 @@package promotetypesimport (+ "regexp"+ "strconv""strings"schemamigrator "github.com/SigNoz/signoz-otel-collector/cmd/signozschemamigrator/schema_migrator"@@ -9,6 +11,20 @@ import ("github.com/SigNoz/signoz/pkg/types/telemetrytypes")+// maxPromotePathsPerRequest caps a promote batch so one request cannot flood+// the cluster with index DDL.+const maxPromotePathsPerRequest = 100++const (+ maxIndexNGramLength = 64+ maxIndexBloomFilterBytes = 1 << 20+ maxIndexHashFunctions = 64+)++// indexTypeRe anchors the whole index type string, so only a whitelisted type+// with bounded numeric parameters can reach the index DDL.+var indexTypeRe = regexp.MustCompile(`^(?:minmax|set\(\s*(\d{1,7})\s*\)|bloom_filter(?:\(\s*(\d+(?:\.\d+)?|\.\d+)\s*\))?|tokenbf_v1\(\s*(\d{1,7})\s*,\s*(\d{1,2})\s*,\s*(\d{1,10})\s*\)|ngrambf_v1\(\s*(\d{1,2})\s*,\s*(\d{1,7})\s*,\s*(\d{1,2})\s*,\s*(\d{1,10})\s*\))$`)+type WrappedIndex struct {JSONDataType telemetrytypes.JSONDataType `json:"-"`FieldDataType telemetrytypes.FieldDataType `json:"fieldDataType"`@@ -37,7 +53,7 @@ type ListPromotedPathsFilters struct {}// Validate checks the signal and context words are known; the pair need not-// name a supported domain.+// name a supported target.func (f *ListPromotedPathsFilters) Validate() error {if f.Signal != "" {if _, ok := telemetrytypes.SignalFromText(f.Signal); !ok {@@ -89,15 +105,8 @@ func (i *PromotePath) ValidateAndSetDefaults(target Target) error {return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "array paths can not be promoted or indexed")}- if strings.HasPrefix(i.Path, target.BaseColumnPrefix()) || strings.HasPrefix(i.Path, target.PromotedColumnPrefix()) {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "`%s`, `%s` don't add these prefixes to the path", target.BaseColumnPrefix(), target.PromotedColumnPrefix())- }-- if target.RequiredPathPrefix != "" {- if !strings.HasPrefix(i.Path, target.RequiredPathPrefix) {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "path must start with `%s`", target.RequiredPathPrefix)- }- i.Path = strings.TrimPrefix(i.Path, target.RequiredPathPrefix)+ if prefix, ok := target.reservedPathPrefix(i.Path); ok {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "path must be a bare attribute name, without the `%s` prefix", prefix)}isCardinal := keycheck.IsCardinal(i.Path)@@ -105,15 +114,11 @@ func (i *PromotePath) ValidateAndSetDefaults(target Target) error {return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cardinal paths can not be promoted or indexed")}- if len(i.Indexes) > 0 && !target.IndexesSupported {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "indexes are not supported for %s %s", target.Entry.Signal.StringValue(), target.Entry.FieldContext.StringValue())- }-for idx, index := range i.Indexes {if index.Type == "" {return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "index type is required")}- if _, err := index.SkipIndexType(); err != nil {+ if err := validateIndexType(index.Type); err != nil {return err}if index.Granularity <= 0 {@@ -142,7 +147,78 @@ func (index WrappedIndex) SkipIndexType() (schemamigrator.IndexType, error) {return schemamigrator.IndexTypeTokenBF, nilcase strings.HasPrefix(index.Type, string(schemamigrator.IndexTypeMinMax)):return schemamigrator.IndexTypeMinMax, nil+ case strings.HasPrefix(index.Type, "bloom_filter"):+ return "bloom_filter", nil+ case strings.HasPrefix(index.Type, "set"):+ return "set", nildefault:return "", errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid index type: %s", index.Type)}}++func ValidatePromotePaths(paths []*PromotePath) error {+ if len(paths) == 0 {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "paths cannot be empty")+ }+ if len(paths) > maxPromotePathsPerRequest {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot promote more than %d paths in one request", maxPromotePathsPerRequest)+ }+ for _, path := range paths {+ if path == nil {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "path cannot be null")+ }+ target, err := path.Target()+ if err != nil {+ return err+ }+ if err := path.ValidateAndSetDefaults(target); err != nil {+ return err+ }+ }+ return nil+}++func validateIndexType(indexType string) error {+ matches := indexTypeRe.FindStringSubmatch(indexType)+ if matches == nil {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid index type: %s", indexType)+ }++ switch {+ case indexType == "minmax" || strings.HasPrefix(indexType, "set"):+ return nil+ case strings.HasPrefix(indexType, "bloom_filter"):+ if matches[2] == "" {+ return nil+ }+ falsePositive, _ := strconv.ParseFloat(matches[2], 64)+ if falsePositive <= 0 || falsePositive >= 1 {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid false positive rate in index type: %s", indexType)+ }+ return nil+ }++ params := matches[3:6]+ if strings.HasPrefix(indexType, "ngrambf_v1") {+ params = matches[6:10]+ }+ values := make([]uint64, len(params))+ for idx, param := range params {+ values[idx], _ = strconv.ParseUint(param, 10, 64)+ }++ bloomBytes, hashes := 0, 1+ if len(values) == 4 {+ if values[0] < 1 || values[0] > maxIndexNGramLength {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid n-gram length in index type: %s", indexType)+ }+ bloomBytes, hashes = 1, 2+ }+ if values[bloomBytes] < 1 || values[bloomBytes] > maxIndexBloomFilterBytes {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid bloom filter size in index type: %s", indexType)+ }+ if values[hashes] < 1 || values[hashes] > maxIndexHashFunctions {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid hash function count in index type: %s", indexType)+ }+ return nil+}diff --git a/pkg/types/promotetypes/types_test.go b/pkg/types/promotetypes/types_test.goindex ca5c815bbd..febbe86190 100644--- a/pkg/types/promotetypes/types_test.go+++ b/pkg/types/promotetypes/types_test.go@@ -37,7 +37,7 @@ func TestPromotePathTarget(t *testing.T) {wantErr: true,},{- name: "UnsupportedDomain_Rejected",+ name: "UnsupportedTarget_Rejected",path: &PromotePath{Signal: "metrics", Context: "attribute", Path: "http.method"},wantErr: true,},@@ -67,13 +67,13 @@ func TestValidateAndSetDefaultsLogsBody(t *testing.T) {wantJSONDataType telemetrytypes.JSONDataType}{{- name: "ValidPath_BodyPrefixStripped",- path: &PromotePath{Path: "body.user.name", Promote: true},+ name: "BarePath_KeptAsIs",+ path: &PromotePath{Path: "user.name", Promote: true},wantPath: "user.name",},{- name: "PathWithoutBodyPrefix_Rejected",- path: &PromotePath{Path: "user.name", Promote: true},+ name: "BodyPrefixedPath_Rejected",+ path: &PromotePath{Path: "body.user.name", Promote: true},wantErr: true,},{@@ -114,7 +114,7 @@ func TestValidateAndSetDefaultsLogsBody(t *testing.T) {{name: "ValidIndex_JSONDataTypeDefaulted",path: &PromotePath{- Path: "body.user.name",+ Path: "user.name",Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},},@@ -122,10 +122,83 @@ func TestValidateAndSetDefaultsLogsBody(t *testing.T) {wantPath: "user.name",wantJSONDataType: telemetrytypes.String,},+ {+ name: "ValidTokenBFIndex_JSONDataTypeDefaulted",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "tokenbf_v1(1024, 2, 0)", Granularity: 1},+ },+ },+ wantPath: "user.name",+ wantJSONDataType: telemetrytypes.String,+ },+ {+ name: "IndexTypeWithAlterAction_Rejected",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4,1024,2,0)\tGRANULARITY\t1,\tDROP\tINDEX\tidx\t--\t", Granularity: 1}},+ },+ wantErr: true,+ },+ {+ name: "ValidBloomFilterIndex_JSONDataTypeDefaulted",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "bloom_filter(0.01)", Granularity: 1},+ },+ },+ wantPath: "user.name",+ wantJSONDataType: telemetrytypes.String,+ },+ {+ name: "ValidSetIndex_JSONDataTypeDefaulted",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "set(100)", Granularity: 1},+ },+ },+ wantPath: "user.name",+ wantJSONDataType: telemetrytypes.String,+ },+ {+ name: "IndexTypeFalsePositiveOutOfRange_Rejected",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "bloom_filter(1)", Granularity: 1}},+ },+ wantErr: true,+ },+ {+ name: "UnsupportedIndexType_Rejected",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "inverted(2)", Granularity: 1}},+ },+ wantErr: true,+ },+ {+ name: "IndexTypeWrongArity_Rejected",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024)", Granularity: 1}},+ },+ wantErr: true,+ },+ {+ name: "IndexTypeOversizedBloomFilter_Rejected",+ path: &PromotePath{+ Path: "user.name",+ Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 9999999, 2, 0)", Granularity: 1}},+ },+ wantErr: true,+ },{name: "UnsupportedColumnTypeIndex_Rejected",path: &PromotePath{- Path: "body.user.active",+ Path: "user.active",Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeBool, Type: "minmax", Granularity: 1}},},wantErr: true,@@ -133,7 +206,7 @@ func TestValidateAndSetDefaultsLogsBody(t *testing.T) {{name: "IndexWithoutType_Rejected",path: &PromotePath{- Path: "body.user.name",+ Path: "user.name",Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Granularity: 1}},},wantErr: true,@@ -149,7 +222,7 @@ func TestValidateAndSetDefaultsLogsBody(t *testing.T) {{name: "IndexWithoutGranularity_Rejected",path: &PromotePath{- Path: "body.user.name",+ Path: "user.name",Indexes: []WrappedIndex{{FieldDataType: telemetrytypes.FieldDataTypeString, Type: "minmax"}},},wantErr: true,@@ -177,16 +250,28 @@ func TestValidateAndSetDefaultsTracesAttributes(t *testing.T) {target := NewTracesAttributesTarget()testCases := []struct {- name string- path *PromotePath- wantErr bool- wantPath string+ name string+ path *PromotePath+ wantErr bool+ wantPath string+ wantJSONDataType telemetrytypes.JSONDataType}{{name: "BareAttributeName_KeptAsIs",path: &PromotePath{Path: "http.method", Promote: true},wantPath: "http.method",},+ {+ name: "ValidIndex_JSONDataTypeDefaulted",+ path: &PromotePath{+ Path: "http.method",+ Indexes: []WrappedIndex{+ {FieldDataType: telemetrytypes.FieldDataTypeString, Type: "ngrambf_v1(4, 1024, 2, 0)", Granularity: 1},+ },+ },+ wantPath: "http.method",+ wantJSONDataType: telemetrytypes.String,+ },{name: "AttributesPrefixedPath_Rejected",path: &PromotePath{Path: "attributes.http.method", Promote: true},@@ -223,6 +308,10 @@ func TestValidateAndSetDefaultsTracesAttributes(t *testing.T) {}require.NoError(t, err)assert.Equal(t, testCase.wantPath, testCase.path.Path)+ if testCase.wantJSONDataType != (telemetrytypes.JSONDataType{}) {+ require.Len(t, testCase.path.Indexes, 1)+ assert.Equal(t, testCase.wantJSONDataType, testCase.path.Indexes[0].JSONDataType)+ }})}}@@ -352,3 +441,38 @@ func TestListPromotedPathsFiltersMatch(t *testing.T) {})}}++func TestValidatePromotePaths(t *testing.T) {+ validPaths := func(n int) []*PromotePath {+ paths := make([]*PromotePath, n)+ for idx := range paths {+ paths[idx] = &PromotePath{Signal: "logs", Context: "body", Path: "user.name"}+ }+ return paths+ }++ testCases := []struct {+ name string+ paths []*PromotePath+ wantErr bool+ }{+ {name: "Empty_Rejected", paths: nil, wantErr: true},+ {name: "NullPath_Rejected", paths: []*PromotePath{nil}, wantErr: true},+ {name: "OverCap_Rejected", paths: validPaths(maxPromotePathsPerRequest + 1), wantErr: true},+ {name: "PrefixedPath_Rejected", paths: []*PromotePath{{Signal: "logs", Context: "body", Path: "body.user.name"}}, wantErr: true},+ {name: "UnsupportedSignal_Rejected", paths: []*PromotePath{{Signal: "metrics", Context: "body", Path: "user.name"}}, wantErr: true},+ {name: "AtCap_Valid", paths: validPaths(maxPromotePathsPerRequest)},+ {name: "SinglePath_Valid", paths: validPaths(1)},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ err := ValidatePromotePaths(testCase.paths)+ if testCase.wantErr {+ assert.Error(t, err)+ return+ }+ require.NoError(t, err)+ })+ }+}diff --git a/pkg/types/telemetrytypes/field.go b/pkg/types/telemetrytypes/field.goindex b32966d182..cb71afecc8 100644--- a/pkg/types/telemetrytypes/field.go+++ b/pkg/types/telemetrytypes/field.go@@ -398,6 +398,19 @@ func NewTelemetryFieldKey(name string, fieldContext FieldContext, fieldDataType}}+// JSONIndexLookup locates one domain's JSON sub-column indexes in+// system.data_skipping_indices: the table to read, the base and promoted+// column prefixes to match index expressions against, and the signal and+// context to stamp on the results.+type JSONIndexLookup struct {+ Signal Signal+ FieldContext FieldContext+ DBName string+ LocalTableName string+ BaseColumnPrefix string+ PromotedColumnPrefix string+}+type TelemetryFieldKeySkipIndex struct {Name string `json:"name"` // Name is TelemetryFieldKey.Name not IndexName from ClickHouseFieldContext FieldContext `json:"fieldContext,omitzero"`diff --git a/pkg/types/telemetrytypes/store.go b/pkg/types/telemetrytypes/store.goindex b74752b279..53ff4e107a 100644--- a/pkg/types/telemetrytypes/store.go+++ b/pkg/types/telemetrytypes/store.go@@ -34,8 +34,8 @@ type MetadataStore interface {FetchTemporalityAndTypeMulti(ctx context.Context, orgID valuer.UUID, queryTimeRangeStartTs, queryTimeRangeEndTs uint64, metricNames ...string) (map[string]metrictypes.Temporality, map[string]metrictypes.Type, map[string]bool, error)- // ListLogsJSONIndexes lists the JSON indexes for the logs table.- ListLogsJSONIndexes(ctx context.Context, filters ...string) ([]TelemetryFieldKeySkipIndex, error)+ // ListJSONIndexes lists the per-path JSON skip indexes of the given source.+ ListJSONIndexes(ctx context.Context, lookup JSONIndexLookup, filters ...string) ([]TelemetryFieldKeySkipIndex, error)// GetPromotedPaths lists the promoted paths recorded in the column// evolution table for the entry's signal, column and field context.diff --git a/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go b/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.goindex 69ebe72eec..5bd1e0de95 100644--- a/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go+++ b/pkg/types/telemetrytypes/telemetrytypestest/metadata_store.go@@ -376,9 +376,15 @@ func (m *MockMetadataStore) GetPromotedPaths(_ context.Context, entry telemetrytreturn m.PromotedPathsMap[entry.Signal], nil}-// ListLogsJSONIndexes lists the JSON indexes for the logs table.-func (m *MockMetadataStore) ListLogsJSONIndexes(ctx context.Context, filters ...string) ([]telemetrytypes.TelemetryFieldKeySkipIndex, error) {- return m.LogsJSONIndexes, nil+// ListJSONIndexes narrows the stored indexes to the lookup's field context like the real query.+func (m *MockMetadataStore) ListJSONIndexes(ctx context.Context, lookup telemetrytypes.JSONIndexLookup, filters ...string) ([]telemetrytypes.TelemetryFieldKeySkipIndex, error) {+ indexes := []telemetrytypes.TelemetryFieldKeySkipIndex{}+ for _, index := range m.LogsJSONIndexes {+ if index.FieldContext.StringValue() == lookup.FieldContext.StringValue() {+ indexes = append(indexes, index)+ }+ }+ return indexes, nil}func (m *MockMetadataStore) updateColumnEvolutionMetadataForKeys(_ context.Context, keysToUpdate []*telemetrytypes.TelemetryFieldKey) map[string][]*telemetrytypes.EvolutionEntry {