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: opamp integration signozspanmapper (#11335)
Nityananda Gohain67324edb7efc
diff --git a/pkg/modules/spanmapper/implspanmapper/module.go b/pkg/modules/spanmapper/implspanmapper/module.goindex 62495bc5d4..0ab4536991 100644--- a/pkg/modules/spanmapper/implspanmapper/module.go+++ b/pkg/modules/spanmapper/implspanmapper/module.go@@ -2,8 +2,11 @@ package implspanmapperimport ("context"+ "encoding/json""github.com/SigNoz/signoz/pkg/modules/spanmapper"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf"+ "github.com/SigNoz/signoz/pkg/types/opamptypes""github.com/SigNoz/signoz/pkg/types/spantypes""github.com/SigNoz/signoz/pkg/valuer")@@ -34,11 +37,22 @@ func (module *module) UpdateGroup(ctx context.Context, orgID, id valuer.UUID, nareturn err}group.Update(name, condition, enabled, updatedBy)- return module.store.UpdateGroup(ctx, group)++ err = module.store.UpdateGroup(ctx, group)+ if err != nil {+ return err+ }+ agentConf.NotifyConfigUpdate(ctx)+ return nil}func (module *module) DeleteGroup(ctx context.Context, orgID, id valuer.UUID) error {- return module.store.DeleteGroup(ctx, orgID, id)+ err := module.store.DeleteGroup(ctx, orgID, id)+ if err != nil {+ return err+ }+ agentConf.NotifyConfigUpdate(ctx)+ return nil}func (module *module) ListMappers(ctx context.Context, orgID, groupID valuer.UUID) ([]*spantypes.SpanMapper, error) {@@ -54,7 +68,12 @@ func (module *module) CreateMapper(ctx context.Context, orgID, groupID valuer.UUif _, err := module.store.GetGroup(ctx, orgID, groupID); err != nil {return err}- return module.store.CreateMapper(ctx, mapper)+ err := module.store.CreateMapper(ctx, mapper)+ if err != nil {+ return err+ }+ agentConf.NotifyConfigUpdate(ctx)+ return nil}func (module *module) UpdateMapper(ctx context.Context, orgID, groupID, id valuer.UUID, fieldContext spantypes.FieldContext, config *spantypes.SpanMapperConfig, enabled *bool, updatedBy string) error {@@ -66,9 +85,72 @@ func (module *module) UpdateMapper(ctx context.Context, orgID, groupID, id valuereturn err}mapper.Update(fieldContext, config, enabled, updatedBy)- return module.store.UpdateMapper(ctx, mapper)+ err = module.store.UpdateMapper(ctx, mapper)+ if err != nil {+ return err+ }+ agentConf.NotifyConfigUpdate(ctx)+ return nil}func (module *module) DeleteMapper(ctx context.Context, orgID, groupID, id valuer.UUID) error {- return module.store.DeleteMapper(ctx, orgID, groupID, id)+ err := module.store.DeleteMapper(ctx, orgID, groupID, id)+ if err != nil {+ return err+ }+ agentConf.NotifyConfigUpdate(ctx)+ return nil+}++func (module *module) AgentFeatureType() agentConf.AgentFeatureType {+ return spantypes.SpanAttrMappingFeatureType+}++func (module *module) RecommendAgentConfig(orgID valuer.UUID, currentConfYaml []byte, configVersion *opamptypes.AgentConfigVersion) ([]byte, string, error) {+ ctx := context.Background()++ enabled, err := module.listEnabledGroupsWithMappers(ctx, orgID)+ if err != nil {+ return nil, "", err+ }++ updatedConf, err := spantypes.GenerateCollectorConfigWithSpanMapperProcessor(currentConfYaml, enabled)+ if err != nil {+ return nil, "", err+ }++ serialized, err := json.Marshal(enabled)+ if err != nil {+ return nil, "", err+ }++ return updatedConf, string(serialized), nil+}++// listEnabledGroupsWithMappers returns groups with their mappers.+func (module *module) listEnabledGroupsWithMappers(ctx context.Context, orgID valuer.UUID) ([]*spantypes.SpanMapperGroupWithMappers, error) {+ enabled := true+ groups, err := module.store.ListGroups(ctx, orgID, &spantypes.ListSpanMapperGroupsQuery{Enabled: &enabled})+ if err != nil {+ return nil, err+ }++ out := make([]*spantypes.SpanMapperGroupWithMappers, 0, len(groups))+ for _, g := range groups {+ mappers, err := module.store.ListMappers(ctx, orgID, g.ID)+ if err != nil {+ return nil, err+ }+ enabledMappers := make([]*spantypes.SpanMapper, 0, len(mappers))+ for _, m := range mappers {+ if m.Enabled {+ enabledMappers = append(enabledMappers, m)+ }+ }+ if len(enabledMappers) == 0 {+ continue+ }+ out = append(out, &spantypes.SpanMapperGroupWithMappers{Group: g, Mappers: enabledMappers})+ }+ return out, nil}diff --git a/pkg/modules/spanmapper/spanmapper.go b/pkg/modules/spanmapper/spanmapper.goindex f8722528e1..a2f4b6caae 100644--- a/pkg/modules/spanmapper/spanmapper.go+++ b/pkg/modules/spanmapper/spanmapper.go@@ -4,12 +4,16 @@ import ("context""net/http"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf""github.com/SigNoz/signoz/pkg/types/spantypes""github.com/SigNoz/signoz/pkg/valuer")// Module defines the business logic for span attribute mapping groups and mappers.type Module interface {+ // Since this module interacts with OpAMP, it must implement the AgentFeature interface.+ agentConf.AgentFeature+// Group operationsListGroups(ctx context.Context, orgID valuer.UUID, q *spantypes.ListSpanMapperGroupsQuery) ([]*spantypes.SpanMapperGroup, error)GetGroup(ctx context.Context, orgID, id valuer.UUID) (*spantypes.SpanMapperGroup, error)diff --git a/pkg/types/spantypes/mappergroup.go b/pkg/types/spantypes/mappergroup.goindex 4e285dd63b..cb8afbb01a 100644--- a/pkg/types/spantypes/mappergroup.go+++ b/pkg/types/spantypes/mappergroup.go@@ -13,7 +13,9 @@ var (ErrCodeMappingGroupAlreadyExists = errors.MustNewCode("span_attribute_mapping_group_already_exists"))-// A group runs when any of the listed attribute/resource key patterns match.+// SpanMapperGroupCondition gates whether a group's rules run for a given span.+// A group runs when any attribute or resource key on the span CONTAINS one of+// the listed substrings (plain substring match — no glob syntax).type SpanMapperGroupCondition struct {Attributes []string `json:"attributes" required:"true" nullable:"true"`Resource []string `json:"resource" required:"true" nullable:"true"`diff --git a/pkg/types/spantypes/spanmapperprocessor.go b/pkg/types/spantypes/spanmapperprocessor.gonew file mode 100644index 0000000000..8d8a7ba05b--- /dev/null+++ b/pkg/types/spantypes/spanmapperprocessor.go@@ -0,0 +1,140 @@+package spantypes++import (+ "sort"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/query-service/agentConf"+ "gopkg.in/yaml.v3"+)++const (+ SpanAttrMappingFeatureType agentConf.AgentFeatureType = "span_attr_mapping"++ ProcessorName = "signozspanmapper"+)++var (+ ErrCodeInvalidCollectorConfig = errors.MustNewCode("invalid_collector_config")+ ErrCodeBuildMappingProcessorConfig = errors.MustNewCode("build_mapping_processor_config")+)++type SpanMapperGroupWithMappers struct {+ Group *SpanMapperGroup `json:"group"`+ Mappers []*SpanMapper `json:"mappers"`+}++// spanMapperProcessorConfig is the collector config for signozspanmapper.+type spanMapperProcessorConfig struct {+ Groups []spanMapperProcessorGroup `yaml:"groups" json:"groups"`+}++type spanMapperProcessorGroup struct {+ ID string `yaml:"id" json:"id"`+ ExistsAny spanMapperProcessorExistsAny `yaml:"exists_any" json:"exists_any"`+ Attributes []spanMapperProcessorAttribute `yaml:"attributes" json:"attributes"`+}++type spanMapperProcessorExistsAny struct {+ Attributes []string `yaml:"attributes,omitempty" json:"attributes,omitempty"`+ Resource []string `yaml:"resource,omitempty" json:"resource,omitempty"`+}++type spanMapperProcessorAttribute struct {+ Target string `yaml:"target" json:"target"`+ Context string `yaml:"context,omitempty" json:"context,omitempty"`+ Sources []spanMapperProcessorSource `yaml:"sources" json:"sources"`+}++type spanMapperProcessorSource struct {+ Key string `yaml:"key" json:"key"`+ Action string `yaml:"action,omitempty" json:"action,omitempty"`+}++func GenerateCollectorConfigWithSpanMapperProcessor(currentConfYaml []byte, groups []*SpanMapperGroupWithMappers) ([]byte, error) {+ var collectorConf map[string]any+ if err := yaml.Unmarshal(currentConfYaml, &collectorConf); err != nil {+ return nil, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodeInvalidCollectorConfig, "failed to unmarshal collector config")+ }+ // rare but don't do anything in this case, also means it's just comments.+ if collectorConf == nil {+ collectorConf = map[string]any{}+ }++ processors := map[string]any{}+ if existing, ok := collectorConf["processors"]; ok && existing != nil {+ p, ok := existing.(map[string]any)+ if !ok {+ return nil, errors.Newf(errors.TypeInvalidInput, ErrCodeInvalidCollectorConfig, "collector config 'processors' must be a mapping, got %T", existing)+ }+ processors = p+ }++ procConfig := buildProcessorConfig(groups)++ processors[ProcessorName] = procConfig+ collectorConf["processors"] = processors++ out, err := yaml.Marshal(collectorConf)+ if err != nil {+ return nil, errors.Wrapf(err, errors.TypeInternal, ErrCodeBuildMappingProcessorConfig, "failed to marshal collector config")+ }+ return out, nil+}++func buildProcessorConfig(groups []*SpanMapperGroupWithMappers) *spanMapperProcessorConfig {+ out := make([]spanMapperProcessorGroup, 0, len(groups))++ for _, gm := range groups {+ rules := make([]spanMapperProcessorAttribute, 0, len(gm.Mappers))+ for _, m := range gm.Mappers {+ rules = append(rules, buildAttributeRule(m))+ }++ out = append(out, spanMapperProcessorGroup{+ ID: gm.Group.Name,+ ExistsAny: spanMapperProcessorExistsAny{+ Attributes: gm.Group.Condition.Attributes,+ Resource: gm.Group.Condition.Resource,+ },+ Attributes: rules,+ })+ }++ return &spanMapperProcessorConfig{Groups: out}+}++// buildAttributeRule maps a single SpanMapper to a collector attribute rule.+// Sources are sorted by Priority DESC (highest-priority first); read-from-+// resource sources are encoded via the "resource." prefix on the key. Each+// source carries its own action — "copy" is omitted to keep the emitted YAML+// compact, and only "move" is set explicitly.+func buildAttributeRule(m *SpanMapper) spanMapperProcessorAttribute {+ sources := make([]SpanMapperSource, len(m.Config.Sources))+ copy(sources, m.Config.Sources)+ sort.SliceStable(sources, func(i, j int) bool { return sources[i].Priority > sources[j].Priority })++ out := make([]spanMapperProcessorSource, 0, len(sources))+ for _, s := range sources {+ key := s.Key+ if s.Context == FieldContextResource {+ key = FieldContextResource.StringValue() + "." + s.Key+ }+ var action string+ if s.Operation == SpanMapperOperationMove {+ action = SpanMapperOperationMove.StringValue()+ }+ out = append(out, spanMapperProcessorSource{Key: key, Action: action})+ }++ ctx := FieldContextSpanAttribute+ if m.FieldContext == FieldContextResource {+ ctx = FieldContextResource+ }++ return spanMapperProcessorAttribute{+ Target: m.Name,+ Context: ctx.StringValue(),+ Sources: out,+ }+}diff --git a/pkg/types/spantypes/spanmapperprocessor_test.go b/pkg/types/spantypes/spanmapperprocessor_test.gonew file mode 100644index 0000000000..2a0f0f22fe--- /dev/null+++ b/pkg/types/spantypes/spanmapperprocessor_test.go@@ -0,0 +1,198 @@+package spantypes++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "gopkg.in/yaml.v3"+)++func TestGenerateCollectorConfigWithSpanMapperProcessor(t *testing.T) {+ t.Parallel()++ baseline := loadFixture(t, "collector_baseline.yaml")++ tests := []struct {+ name string+ groups []*SpanMapperGroupWithMappers+ want string+ }{+ {+ name: "no_groups",+ want: "collector_no_groups.yaml",+ },+ {+ name: "with_groups",+ groups: []*SpanMapperGroupWithMappers{+ {+ Group: newGroup("llm", []string{"model"}, []string{"service.name"}),+ Mappers: []*SpanMapper{+ newMapper("gen_ai.request.model", FieldContextResource,+ attrSrc("gen_ai.llm.model", SpanMapperOperationCopy, 3),+ attrSrc("llm.model", SpanMapperOperationCopy, 2),+ resSrc("service.name", SpanMapperOperationCopy, 1),+ ),+ newMapper("gen_ai.request.tokens", FieldContextSpanAttribute,+ attrSrc("gen_ai.request_tokens", SpanMapperOperationCopy, 2),+ attrSrc("llm.tokens", SpanMapperOperationCopy, 1),+ ),+ newMapper("gen_ai.request.input", FieldContextSpanAttribute,+ attrSrc("gen_ai.input", SpanMapperOperationMove, 2),+ attrSrc("llm.input", SpanMapperOperationMove, 1),+ ),+ },+ },+ {+ Group: newGroup("agent", []string{"agent."}, nil),+ Mappers: []*SpanMapper{+ newMapper("gen_ai.agent.name", FieldContextSpanAttribute,+ attrSrc("agent.name", SpanMapperOperationCopy, 2),+ attrSrc("llm.agent.name", SpanMapperOperationCopy, 1),+ ),+ newMapper("gen_ai.agent.id", FieldContextSpanAttribute,+ attrSrc("gen_ai.agent.id", SpanMapperOperationCopy, 2),+ attrSrc("llm.agent.id", SpanMapperOperationCopy, 1),+ ),+ },+ },+ {+ Group: newGroup("tool", []string{"agent."}, nil),+ Mappers: []*SpanMapper{+ newMapper("gen_ai.tool.name", FieldContextSpanAttribute,+ attrSrc("ai.tool.name", SpanMapperOperationCopy, 2),+ attrSrc("llm.tool.name", SpanMapperOperationCopy, 1),+ ),+ },+ },+ },+ want: "collector_with_groups.yaml",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got, err := GenerateCollectorConfigWithSpanMapperProcessor(baseline, tc.groups)+ require.NoError(t, err)+ assertYAMLEqual(t, loadFixture(t, tc.want), got)+ })+ }+}++func TestGenerateCollectorConfigWithSpanMapperProcessor_Errors(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ in []byte+ }{+ {"processors_not_a_map", []byte("processors: not-a-map\n")},+ {"malformed_yaml", []byte(": :")},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ _, err := GenerateCollectorConfigWithSpanMapperProcessor(tc.in, nil)+ require.Error(t, err)+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput), "want TypeInvalidInput, got %v", err)+ assert.True(t, errors.Asc(err, ErrCodeInvalidCollectorConfig), "want ErrCodeInvalidCollectorConfig, got %v", err)+ })+ }+}++func TestBuildAttributeRule(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ mapper *SpanMapper+ want spanMapperProcessorAttribute+ }{+ {+ name: "priority_sort_and_resource_prefix",+ mapper: newMapper("gen_ai.request.model", FieldContextResource,+ attrSrc("llm.model", SpanMapperOperationCopy, 20),+ resSrc("service.name", SpanMapperOperationCopy, 10),+ attrSrc("gen_ai.llm.model", SpanMapperOperationCopy, 30),+ ),+ want: spanMapperProcessorAttribute{+ Target: "gen_ai.request.model",+ Context: FieldContextResource.StringValue(),+ Sources: []spanMapperProcessorSource{+ {Key: "gen_ai.llm.model"},+ {Key: "llm.model"},+ {Key: "resource.service.name"},+ },+ },+ },+ {+ name: "per_source_actions",+ mapper: newMapper("gen_ai.request.input", FieldContextSpanAttribute,+ attrSrc("gen_ai.input", SpanMapperOperationMove, 20),+ attrSrc("llm.input", SpanMapperOperationCopy, 10),+ ),+ want: spanMapperProcessorAttribute{+ Target: "gen_ai.request.input",+ Context: FieldContextSpanAttribute.StringValue(),+ Sources: []spanMapperProcessorSource{+ {Key: "gen_ai.input", Action: SpanMapperOperationMove.StringValue()},+ {Key: "llm.input"},+ },+ },+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ assert.Equal(t, tc.want, buildAttributeRule(tc.mapper))+ })+ }+}++func loadFixture(t *testing.T, name string) []byte {+ t.Helper()+ b, err := os.ReadFile(filepath.Join("testdata", name))+ require.NoError(t, err)+ return b+}++// assertYAMLEqual compares two YAML documents structurally so key order and+// slice formatting do not matter.+func assertYAMLEqual(t *testing.T, want, got []byte) {+ t.Helper()+ var w, g any+ require.NoError(t, yaml.Unmarshal(want, &w))+ require.NoError(t, yaml.Unmarshal(got, &g))+ assert.Equal(t, w, g)+}++func newGroup(name string, attrs, res []string) *SpanMapperGroup {+ return &SpanMapperGroup{+ Name: name,+ Condition: SpanMapperGroupCondition{Attributes: attrs, Resource: res},+ Enabled: true,+ }+}++func newMapper(name string, target FieldContext, sources ...SpanMapperSource) *SpanMapper {+ return &SpanMapper{+ Name: name,+ FieldContext: target,+ Config: SpanMapperConfig{Sources: sources},+ Enabled: true,+ }+}++func attrSrc(key string, op SpanMapperOperation, priority int) SpanMapperSource {+ return SpanMapperSource{Key: key, Context: FieldContextSpanAttribute, Operation: op, Priority: priority}+}++func resSrc(key string, op SpanMapperOperation, priority int) SpanMapperSource {+ return SpanMapperSource{Key: key, Context: FieldContextResource, Operation: op, Priority: priority}+}diff --git a/pkg/types/spantypes/testdata/collector_baseline.yaml b/pkg/types/spantypes/testdata/collector_baseline.yamlnew file mode 100644index 0000000000..23450c984f--- /dev/null+++ b/pkg/types/spantypes/testdata/collector_baseline.yaml@@ -0,0 +1,17 @@+receivers:+ otlp:+ protocols:+ grpc:+processors:+ signozspanmapper:+ groups: []+ batch: {}+exporters:+ otlp:+ endpoint: localhost:4317+service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [signozspanmapper, batch]+ exporters: [otlp]diff --git a/pkg/types/spantypes/testdata/collector_no_groups.yaml b/pkg/types/spantypes/testdata/collector_no_groups.yamlnew file mode 100644index 0000000000..23450c984f--- /dev/null+++ b/pkg/types/spantypes/testdata/collector_no_groups.yaml@@ -0,0 +1,17 @@+receivers:+ otlp:+ protocols:+ grpc:+processors:+ signozspanmapper:+ groups: []+ batch: {}+exporters:+ otlp:+ endpoint: localhost:4317+service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [signozspanmapper, batch]+ exporters: [otlp]diff --git a/pkg/types/spantypes/testdata/collector_with_groups.yaml b/pkg/types/spantypes/testdata/collector_with_groups.yamlnew file mode 100644index 0000000000..8b9bd1d832--- /dev/null+++ b/pkg/types/spantypes/testdata/collector_with_groups.yaml@@ -0,0 +1,67 @@+receivers:+ otlp:+ protocols:+ grpc:+processors:+ signozspanmapper:+ groups:+ - id: llm+ exists_any:+ attributes:+ - model+ resource:+ - service.name+ attributes:+ - target: gen_ai.request.model+ context: resource+ sources:+ - key: gen_ai.llm.model+ - key: llm.model+ - key: resource.service.name+ - target: gen_ai.request.tokens+ context: attribute+ sources:+ - key: gen_ai.request_tokens+ - key: llm.tokens+ - target: gen_ai.request.input+ context: attribute+ sources:+ - key: gen_ai.input+ action: move+ - key: llm.input+ action: move+ - id: agent+ exists_any:+ attributes:+ - agent.+ attributes:+ - target: gen_ai.agent.name+ context: attribute+ sources:+ - key: agent.name+ - key: llm.agent.name+ - target: gen_ai.agent.id+ context: attribute+ sources:+ - key: gen_ai.agent.id+ - key: llm.agent.id+ - id: tool+ exists_any:+ attributes:+ - agent.+ attributes:+ - target: gen_ai.tool.name+ context: attribute+ sources:+ - key: ai.tool.name+ - key: llm.tool.name+ batch: {}+exporters:+ otlp:+ endpoint: localhost:4317+service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [signozspanmapper, batch]+ exporters: [otlp]