SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
chore: add functional unique index for tags (#12029)
Naman Vermabf35d123980b
diff --git a/pkg/modules/tag/impltag/store.go b/pkg/modules/tag/impltag/store.goindex c635326fd6..fa38552719 100644--- a/pkg/modules/tag/impltag/store.go+++ b/pkg/modules/tag/impltag/store.go@@ -98,7 +98,7 @@ func (s *store) CreateOrGet(ctx context.Context, tags []*tagtypes.Tag) ([]*tagtyBunDBCtx(ctx).NewInsert().Model(&tags).- // On("CONFLICT (org_id, kind, (LOWER(key)), (LOWER(value))) DO UPDATE").+ On("CONFLICT (org_id, kind, (LOWER(key)), (LOWER(value))) DO UPDATE").Set("key = tag.key").Returning("*").Scan(ctx)diff --git a/pkg/modules/tag/impltag/store_test.go b/pkg/modules/tag/impltag/store_test.goindex cb8bb2e8f4..b147a30c2c 100644--- a/pkg/modules/tag/impltag/store_test.go+++ b/pkg/modules/tag/impltag/store_test.go@@ -88,62 +88,60 @@ func TestStore_Create_PopulatesIDsOnFreshInsert(t *testing.T) {assert.Equal(t, preIDB, stored["team\x00blr"].ID)}-// todo (@namanverma): uncomment once unique index is there.-//-// func TestStore_Create_ConflictReturnsExistingRowID(t *testing.T) {-// ctx := context.Background()-// sqlstore := newTestStore(t)-// s := NewStore(sqlstore)--// orgID := valuer.GenerateUUID()--// // Simulate a concurrent insert: someone else has already inserted "tag:Database".-// winner := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")-// _, err := s.CreateOrGet(ctx, []*tagtypes.Tag{winner})-// require.NoError(t, err)-// winnerID := winner.ID--// // Now our request runs with a different pre-generated ID for the same-// // (key, value) — case differs but the functional unique index collapses-// // them. RETURNING should overwrite our stale ID with winner's ID.-// loser := tagtypes.NewTag(orgID, dashboardKind, "TAG", "DATABASE")-// loserPreID := loser.ID-// require.NotEqual(t, winnerID, loserPreID, "pre-generated IDs must differ for this test to be meaningful")--// got, err := s.CreateOrGet(ctx, []*tagtypes.Tag{loser})-// require.NoError(t, err)-// require.Len(t, got, 1)--// assert.Equal(t, winnerID, got[0].ID, "returned slice should carry the existing row's ID, not our stale one")-// assert.Equal(t, winnerID, loser.ID, "input slice element is mutated in place")--// // And the DB still has exactly one row for that (lower(key), lower(value)) — winner's, with winner's casing.-// stored := tagsByLowerKeyValue(t, sqlstore.BunDB())-// require.Len(t, stored, 1)-// assert.Equal(t, winnerID, stored["tag\x00database"].ID)-// assert.Equal(t, "tag", stored["tag\x00database"].Key, "winner's casing preserved in key")-// assert.Equal(t, "Database", stored["tag\x00database"].Value, "winner's casing preserved in value")-// }--// func TestStore_Create_MixedFreshAndConflict(t *testing.T) {-// ctx := context.Background()-// sqlstore := newTestStore(t)-// s := NewStore(sqlstore)--// orgID := valuer.GenerateUUID()-// pre := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")-// _, err := s.CreateOrGet(ctx, []*tagtypes.Tag{pre})-// require.NoError(t, err)-// preExistingID := pre.ID--// conflict := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")-// fresh := tagtypes.NewTag(orgID, dashboardKind, "team", "BLR")-// freshPreID := fresh.ID--// got, err := s.CreateOrGet(ctx, []*tagtypes.Tag{conflict, fresh})-// require.NoError(t, err)-// require.Len(t, got, 2)--// assert.Equal(t, preExistingID, got[0].ID, "conflicting row's ID overwritten with the existing row's")-// assert.Equal(t, freshPreID, got[1].ID, "fresh row's pre-generated ID is preserved")-// }+func TestStore_Create_ConflictReturnsExistingRowID(t *testing.T) {+ ctx := context.Background()+ sqlstore := newTestStore(t)+ s := NewStore(sqlstore)++ orgID := valuer.GenerateUUID()++ // Simulate a concurrent insert: someone else has already inserted "tag:Database".+ winner := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")+ _, err := s.CreateOrGet(ctx, []*tagtypes.Tag{winner})+ require.NoError(t, err)+ winnerID := winner.ID++ // Now our request runs with a different pre-generated ID for the same+ // (key, value) — case differs but the functional unique index collapses+ // them. RETURNING should overwrite our stale ID with winner's ID.+ loser := tagtypes.NewTag(orgID, dashboardKind, "TAG", "DATABASE")+ loserPreID := loser.ID+ require.NotEqual(t, winnerID, loserPreID, "pre-generated IDs must differ for this test to be meaningful")++ got, err := s.CreateOrGet(ctx, []*tagtypes.Tag{loser})+ require.NoError(t, err)+ require.Len(t, got, 1)++ assert.Equal(t, winnerID, got[0].ID, "returned slice should carry the existing row's ID, not our stale one")+ assert.Equal(t, winnerID, loser.ID, "input slice element is mutated in place")++ // And the DB still has exactly one row for that (lower(key), lower(value)) — winner's, with winner's casing.+ stored := tagsByLowerKeyValue(t, sqlstore.BunDB())+ require.Len(t, stored, 1)+ assert.Equal(t, winnerID, stored["tag\x00database"].ID)+ assert.Equal(t, "tag", stored["tag\x00database"].Key, "winner's casing preserved in key")+ assert.Equal(t, "Database", stored["tag\x00database"].Value, "winner's casing preserved in value")+}++func TestStore_Create_MixedFreshAndConflict(t *testing.T) {+ ctx := context.Background()+ sqlstore := newTestStore(t)+ s := NewStore(sqlstore)++ orgID := valuer.GenerateUUID()+ pre := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")+ _, err := s.CreateOrGet(ctx, []*tagtypes.Tag{pre})+ require.NoError(t, err)+ preExistingID := pre.ID++ conflict := tagtypes.NewTag(orgID, dashboardKind, "tag", "Database")+ fresh := tagtypes.NewTag(orgID, dashboardKind, "team", "BLR")+ freshPreID := fresh.ID++ got, err := s.CreateOrGet(ctx, []*tagtypes.Tag{conflict, fresh})+ require.NoError(t, err)+ require.Len(t, got, 2)++ assert.Equal(t, preExistingID, got[0].ID, "conflicting row's ID overwritten with the existing row's")+ assert.Equal(t, freshPreID, got[1].ID, "fresh row's pre-generated ID is preserved")+}diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex d8644778ef..509053096e 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -219,6 +219,7 @@ func NewSQLMigrationProviderFactories(sqlmigration.NewAddMetricReductionRulesFactory(sqlstore, sqlschema),sqlmigration.NewRemoveOrganizationTuplesFactory(sqlstore),sqlmigration.NewAddRoleTransactionGroupsFactory(sqlstore, sqlschema),+ sqlmigration.NewAddTagUniqueIndexFactory(sqlstore, sqlschema),)}diff --git a/pkg/sqlmigration/100_add_tag_unique_index.go b/pkg/sqlmigration/100_add_tag_unique_index.gonew file mode 100644index 0000000000..22cfe35216--- /dev/null+++ b/pkg/sqlmigration/100_add_tag_unique_index.go@@ -0,0 +1,59 @@+package sqlmigration++import (+ "context"++ "github.com/SigNoz/signoz/pkg/factory"+ "github.com/SigNoz/signoz/pkg/sqlschema"+ "github.com/SigNoz/signoz/pkg/sqlstore"+ "github.com/uptrace/bun"+ "github.com/uptrace/bun/migrate"+)++type addTagUniqueIndex struct {+ sqlstore sqlstore.SQLStore+ sqlschema sqlschema.SQLSchema+}++func NewAddTagUniqueIndexFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {+ return factory.NewProviderFactory(factory.MustNewName("add_tag_unique_index"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {+ return &addTagUniqueIndex{+ sqlstore: sqlstore,+ sqlschema: sqlschema,+ }, nil+ })+}++func (migration *addTagUniqueIndex) Register(migrations *migrate.Migrations) error {+ return migrations.Register(migration.Up, migration.Down)+}++func (migration *addTagUniqueIndex) Up(ctx context.Context, db *bun.DB) error {+ tx, err := db.BeginTx(ctx, nil)+ if err != nil {+ return err+ }++ defer func() {+ _ = tx.Rollback()+ }()++ sqls := migration.sqlschema.Operator().CreateIndex(+ &sqlschema.UniqueIndexWithExpressions{+ TableName: "tag",+ Expressions: []string{"org_id", "kind", "LOWER(key)", "LOWER(value)"},+ },+ )++ for _, sql := range sqls {+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (migration *addTagUniqueIndex) Down(_ context.Context, _ *bun.DB) error {+ return nil+}