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: proper definition of user dashboard preferences (#11643)
Naman Verma7eb00951334d
diff --git a/ee/modules/dashboard/impldashboard/module.go b/ee/modules/dashboard/impldashboard/module.goindex d7fc533faf..11fbe965e8 100644--- a/ee/modules/dashboard/impldashboard/module.go+++ b/ee/modules/dashboard/impldashboard/module.go@@ -254,12 +254,12 @@ func (module *module) PinV2(ctx context.Context, orgID valuer.UUID, userID valuereturn module.pkgDashboardModule.PinV2(ctx, orgID, userID, id)}-func (module *module) UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error {- return module.pkgDashboardModule.UnpinV2(ctx, userID, id)+func (module *module) UnpinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {+ return module.pkgDashboardModule.UnpinV2(ctx, orgID, userID, id)}-func (module *module) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {- return module.pkgDashboardModule.DeletePreferencesForUser(ctx, userID)+func (module *module) DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error {+ return module.pkgDashboardModule.DeletePreferencesForUser(ctx, orgID, userID)}func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.Dashboard, error) {diff --git a/pkg/modules/dashboard/dashboard.go b/pkg/modules/dashboard/dashboard.goindex 33898cddc0..520decdda3 100644--- a/pkg/modules/dashboard/dashboard.go+++ b/pkg/modules/dashboard/dashboard.go@@ -73,11 +73,11 @@ type Module interface {PinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error- UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error+ UnpinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) errorDeleteV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error- DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error+ DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error}type Handler interface {diff --git a/pkg/modules/dashboard/impldashboard/listfilter.go b/pkg/modules/dashboard/impldashboard/listfilter.goindex c473b6ffb8..baa1c3ad00 100644--- a/pkg/modules/dashboard/impldashboard/listfilter.go+++ b/pkg/modules/dashboard/impldashboard/listfilter.go@@ -13,9 +13,16 @@ type Compiled struct {Args []any}+func (c Compiled) IsEmpty() bool {+ return c.SQL == ""+}++// Compile always returns a non-nil *Compiled. An empty query (or one that+// produces no SQL) yields a Compiled with an empty SQL — callers gate on+// SQL != "" rather than a nil check.func Compile(query string, formatter sqlstore.SQLFormatter) (*Compiled, error) {if len(query) == 0 {- return nil, nil //nolint:nilnil+ return &Compiled{}, nil}queryVisitor := newVisitor(formatter)@@ -29,9 +36,6 @@ func Compile(query string, formatter sqlstore.SQLFormatter) (*Compiled, error) {return nil, errors.NewInvalidInputf(dashboardtypes.ErrCodeDashboardListFilterInvalid,"invalid filter query: %s", strings.Join(queryVisitor.errors, "; "))}- if sql == "" {- return nil, nil //nolint:nilnil- }return &Compiled{SQL: sql,diff --git a/pkg/modules/dashboard/impldashboard/listfilter_test.go b/pkg/modules/dashboard/impldashboard/listfilter_test.goindex b2577c2fcb..277767919c 100644--- a/pkg/modules/dashboard/impldashboard/listfilter_test.go+++ b/pkg/modules/dashboard/impldashboard/listfilter_test.go@@ -17,7 +17,7 @@ import (type compileCase struct {subtestName stringdslQueryToCompile string- nilExpected bool+ emptyQueryExpected boolexpectedSQL stringexpectedArgs []anyexpectedErrShouldContain string@@ -41,8 +41,8 @@ func runCompileCases(t *testing.T, cases []compileCase) {}require.NoError(t, err)- if c.nilExpected {- assert.Nil(t, out)+ if c.emptyQueryExpected {+ assert.True(t, out.IsEmpty())return}require.NotNil(t, out)@@ -71,7 +71,7 @@ func runCompileCases(t *testing.T, cases []compileCase) {func TestCompile_Empty(t *testing.T) {runCompileCases(t, []compileCase{- {subtestName: "empty query yields nil", dslQueryToCompile: "", nilExpected: true},+ {subtestName: "empty query yields nil", dslQueryToCompile: "", emptyQueryExpected: true},})}diff --git a/pkg/modules/dashboard/impldashboard/store.go b/pkg/modules/dashboard/impldashboard/store.goindex 18b5d47d29..b9a8a45514 100644--- a/pkg/modules/dashboard/impldashboard/store.go+++ b/pkg/modules/dashboard/impldashboard/store.go@@ -103,7 +103,7 @@ func (store *store) ListForUser(Where("dashboard.org_id = ?", orgID).Where("dashboard.source != ?", dashboardtypes.SourceSystem)- if compiled != nil {+ if !compiled.IsEmpty() {q = q.Where(compiled.SQL, compiled.Args...)}@@ -166,7 +166,7 @@ func (store *store) ListV2(Where("dashboard.org_id = ?", orgID).Where("dashboard.source != ?", dashboardtypes.SourceSystem)- if compiled != nil {+ if !compiled.IsEmpty() {q = q.Where(compiled.SQL, compiled.Args...)}@@ -383,15 +383,16 @@ func (store *store) RunInTx(ctx context.Context, cb func(ctx context.Context) er// rows = 0 is the only signal of a real limit hit.func (store *store) PinForUser(ctx context.Context, preference *dashboardtypes.UserDashboardPreference) error {res, err := store.sqlstore.BunDBCtx(ctx).NewRaw(`- INSERT INTO user_dashboard_preference (user_id, dashboard_id, is_pinned)- SELECT ?, ?, true+ INSERT INTO user_dashboard_preference (id, user_id, dashboard_id, is_pinned, created_at, updated_at)+ SELECT ?, ?, ?, true, ?, ?WHERE (SELECT COUNT(*) FROM user_dashboard_preference WHERE user_id = ? AND is_pinned = true) < ?OR EXISTS (SELECT 1 FROM user_dashboard_preference WHERE user_id = ? AND dashboard_id = ? AND is_pinned = true)- ON CONFLICT (user_id, dashboard_id) DO UPDATE SET is_pinned = true+ ON CONFLICT (user_id, dashboard_id) DO UPDATE SET is_pinned = true, updated_at = ?`,- preference.UserID, preference.DashboardID,+ preference.ID, preference.UserID, preference.DashboardID, preference.CreatedAt, preference.UpdatedAt,preference.UserID, dashboardtypes.MaxPinnedDashboardsPerUser,preference.UserID, preference.DashboardID,+ preference.UpdatedAt,).Exec(ctx)if err != nil {return errors.WrapInternalf(err, errors.CodeInternal, "couldn't pin dashboard for user")@@ -410,12 +411,21 @@ func (store *store) PinForUser(ctx context.Context, preference *dashboardtypes.U// UnpinForUser deletes the user's preference row. This is fine while is_pinned// is the only preference stored; once the row carries other preferences this// must become an UPDATE that clears is_pinned instead of dropping the row.-func (store *store) UnpinForUser(ctx context.Context, userID valuer.UUID, dashboardID valuer.UUID) error {+func (store *store) UnpinForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, dashboardID valuer.UUID) error {+ // No org_id on the preference table, so scope by org via a subquery on the+ // parent (DELETE-with-JOIN isn't portable across Postgres/SQLite).+ dashboardIDsInOrgSubQuery := store.sqlstore.BunDBCtx(ctx).+ NewSelect().+ TableExpr("dashboard").+ Column("id").+ Where("org_id = ?", orgID)+_, err := store.sqlstore.BunDBCtx(ctx).NewDelete().Model((*dashboardtypes.UserDashboardPreference)(nil)).Where("user_id = ?", userID).Where("dashboard_id = ?", dashboardID).+ Where("dashboard_id IN (?)", dashboardIDsInOrgSubQuery).Exec(ctx)if err != nil {return errors.WrapInternalf(err, errors.CodeInternal, "couldn't unpin dashboard for user")@@ -423,11 +433,19 @@ func (store *store) UnpinForUser(ctx context.Context, userID valuer.UUID, dashboreturn nil}-func (store *store) DeletePreferencesForDashboard(ctx context.Context, dashboardID valuer.UUID) error {+func (store *store) DeletePreferencesForDashboard(ctx context.Context, orgID valuer.UUID, dashboardID valuer.UUID) error {+ // No org_id on the preference table, so scope by org via a subquery on the+ // parent (DELETE-with-JOIN isn't portable across Postgres/SQLite).+ dashboardIDsInOrgSubQuery := store.sqlstore.BunDBCtx(ctx).+ NewSelect().+ TableExpr("dashboard").+ Column("id").+ Where("org_id = ?", orgID)_, err := store.sqlstore.BunDBCtx(ctx).NewDelete().Model((*dashboardtypes.UserDashboardPreference)(nil)).Where("dashboard_id = ?", dashboardID).+ Where("dashboard_id IN (?)", dashboardIDsInOrgSubQuery).Exec(ctx)if err != nil {return errors.WrapInternalf(err, errors.CodeInternal, "couldn't delete dashboard preferences")@@ -435,11 +453,19 @@ func (store *store) DeletePreferencesForDashboard(ctx context.Context, dashboardreturn nil}-func (store *store) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {+func (store *store) DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error {+ // No org_id on the preference table, so scope by org via a subquery on the+ // parent (DELETE-with-JOIN isn't portable across Postgres/SQLite).+ userIDsInOrgSubQuery := store.sqlstore.BunDBCtx(ctx).+ NewSelect().+ TableExpr("users").+ Column("id").+ Where("org_id = ?", orgID)_, err := store.sqlstore.BunDBCtx(ctx).NewDelete().Model((*dashboardtypes.UserDashboardPreference)(nil)).Where("user_id = ?", userID).+ Where("user_id IN (?)", userIDsInOrgSubQuery).Exec(ctx)if err != nil {return errors.WrapInternalf(err, errors.CodeInternal, "couldn't delete dashboard preferences")diff --git a/pkg/modules/dashboard/impldashboard/v2_handler.go b/pkg/modules/dashboard/impldashboard/v2_handler.goindex d88cc76e4d..ed5d2f653f 100644--- a/pkg/modules/dashboard/impldashboard/v2_handler.go+++ b/pkg/modules/dashboard/impldashboard/v2_handler.go@@ -304,7 +304,7 @@ func (handler *handler) pinUnpinV2(rw http.ResponseWriter, r *http.Request, pinif pin {err = handler.module.PinV2(ctx, orgID, userID, dashboardID)} else {- err = handler.module.UnpinV2(ctx, userID, dashboardID)+ err = handler.module.UnpinV2(ctx, orgID, userID, dashboardID)}if err != nil {render.Error(rw, err)diff --git a/pkg/modules/dashboard/impldashboard/v2_module.go b/pkg/modules/dashboard/impldashboard/v2_module.goindex 068d3ad1d0..5d28119b0b 100644--- a/pkg/modules/dashboard/impldashboard/v2_module.go+++ b/pkg/modules/dashboard/impldashboard/v2_module.go@@ -119,7 +119,7 @@ func (module *module) UpdateV2(ctx context.Context, orgID valuer.UUID, id valuerreturn nil, err}// Locked-dashboard / state gate — independent of tags, so run it before the tx.- if err := existing.CanUpdate(); err != nil {+ if err := existing.ErrIfNotUpdatable(); err != nil {return nil, err}@@ -154,7 +154,7 @@ func (module *module) PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.return nil, err}// Locked-dashboard / state gate — independent of tags, so run it before the tx.- if err := existing.CanUpdate(); err != nil {+ if err := existing.ErrIfNotUpdatable(); err != nil {return nil, err}@@ -193,7 +193,7 @@ func (module *module) DeleteV2(ctx context.Context, orgID valuer.UUID, id valuerif err != nil {return err}- if err := existing.CanDelete(); err != nil {+ if err := existing.ErrIfNotDeletable(); err != nil {return err}@@ -202,7 +202,7 @@ func (module *module) DeleteV2(ctx context.Context, orgID valuer.UUID, id valuerif _, err := module.tagModule.SyncTags(ctx, orgID, coretypes.KindDashboard, id, nil); err != nil {return err}- if err := module.store.DeletePreferencesForDashboard(ctx, id); err != nil {+ if err := module.store.DeletePreferencesForDashboard(ctx, orgID, id); err != nil {return err}return module.store.Delete(ctx, orgID, id)@@ -231,10 +231,10 @@ func (module *module) PinV2(ctx context.Context, orgID valuer.UUID, userID valuereturn module.store.PinForUser(ctx, dashboardtypes.NewUserDashboardPreference(userID, id))}-func (module *module) UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error {- return module.store.UnpinForUser(ctx, userID, id)+func (module *module) UnpinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {+ return module.store.UnpinForUser(ctx, orgID, userID, id)}-func (module *module) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {- return module.store.DeletePreferencesForUser(ctx, userID)+func (module *module) DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error {+ return module.store.DeletePreferencesForUser(ctx, orgID, userID)}diff --git a/pkg/modules/user/impluser/setter.go b/pkg/modules/user/impluser/setter.goindex 14704d28ac..8de62c14ae 100644--- a/pkg/modules/user/impluser/setter.go+++ b/pkg/modules/user/impluser/setter.go@@ -13,7 +13,6 @@ import ("github.com/SigNoz/signoz/pkg/emailing""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/factory"- "github.com/SigNoz/signoz/pkg/modules/dashboard""github.com/SigNoz/signoz/pkg/modules/organization"root "github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/tokenizer"@@ -35,11 +34,11 @@ type setter struct {analytics analytics.Analyticsconfig root.Configgetter root.Getter- dashboard dashboard.Module+ onDeleteUser []root.OnDeleteUser}// This module is a WIP, don't take inspiration from this.-func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config root.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter, dashboard dashboard.Module) root.Setter {+func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config root.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter, onDeleteUser []root.OnDeleteUser) root.Setter {settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/modules/user/impluser")return &setter{store: store,@@ -52,7 +51,7 @@ func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emauthz: authz,config: config,getter: getter,- dashboard: dashboard,+ onDeleteUser: onDeleteUser,}}@@ -409,8 +408,10 @@ func (module *setter) DeleteUser(ctx context.Context, orgID valuer.UUID, id strireturn err}- if err := module.dashboard.DeletePreferencesForUser(ctx, user.ID); err != nil {- return err+ for _, onDeleteUser := range module.onDeleteUser {+ if err := onDeleteUser(ctx, orgID, user.ID); err != nil {+ return err+ }}traitsOrProperties := types.NewTraitsFromUser(user)diff --git a/pkg/modules/user/user.go b/pkg/modules/user/user.goindex 4c3402f60a..effc4183ac 100644--- a/pkg/modules/user/user.go+++ b/pkg/modules/user/user.go@@ -129,3 +129,6 @@ type Handler interface {ChangePassword(http.ResponseWriter, *http.Request)ForgotPassword(http.ResponseWriter, *http.Request)}++// OnDeleteUser lets other modules clean up data tied to a deleted user.+type OnDeleteUser func(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) errordiff --git a/pkg/signoz/module.go b/pkg/signoz/module.goindex 6afc4d5141..53f796084e 100644--- a/pkg/signoz/module.go+++ b/pkg/signoz/module.go@@ -122,7 +122,11 @@ func NewModules() Modules {quickfilter := implquickfilter.NewModule(implquickfilter.NewStore(sqlstore))orgSetter := implorganization.NewSetter(implorganization.NewStore(sqlstore), alertmanager, quickfilter)- userSetter := impluser.NewSetter(impluser.NewStore(sqlstore, providerSettings), tokenizer, emailing, providerSettings, orgSetter, authz, analytics, config.User, userRoleStore, userGetter, dashboard)+ // Cleanup callbacks from other modules, invoked when a user is deleted.+ onDeleteUser := []user.OnDeleteUser{+ dashboard.DeletePreferencesForUser,+ }+ userSetter := impluser.NewSetter(impluser.NewStore(sqlstore, providerSettings), tokenizer, emailing, providerSettings, orgSetter, authz, analytics, config.User, userRoleStore, userGetter, onDeleteUser)ruleStore := sqlrulestore.NewRuleStore(sqlstore, queryParser, providerSettings)return Modules{diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.goindex 1aaafffe01..08498bffc7 100644--- a/pkg/signoz/provider.go+++ b/pkg/signoz/provider.go@@ -212,6 +212,7 @@ func NewSQLMigrationProviderFactories(sqlmigration.NewFixChangelogOperationTypeFactory(sqlstore, sqlschema),sqlmigration.NewCloudIntegrationRemoveCascadeDeleteFactory(sqlschema),sqlmigration.NewAddUserDashboardPreferenceFactory(sqlstore, sqlschema),+ sqlmigration.NewRecreateUserDashboardPreferenceFactory(sqlstore, sqlschema),)}diff --git a/pkg/sqlmigration/093_recreate_user_dashboard_preference.go b/pkg/sqlmigration/093_recreate_user_dashboard_preference.gonew file mode 100644index 0000000000..a2da408e93--- /dev/null+++ b/pkg/sqlmigration/093_recreate_user_dashboard_preference.go@@ -0,0 +1,84 @@+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 recreateUserDashboardPreference struct {+ sqlstore sqlstore.SQLStore+ sqlschema sqlschema.SQLSchema+}++func NewRecreateUserDashboardPreferenceFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {+ return factory.NewProviderFactory(factory.MustNewName("recreate_user_dashboard_pref"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {+ return &recreateUserDashboardPreference{+ sqlstore: sqlstore,+ sqlschema: sqlschema,+ }, nil+ })+}++func (migration *recreateUserDashboardPreference) Register(migrations *migrate.Migrations) error {+ return migrations.Register(migration.Up, migration.Down)+}++// Up replaces the composite (user_id, dashboard_id) primary key with a surrogate+// id primary key, demotes the pair to a unique index, and adds created_at /+// updated_at. The table is dropped and recreated since it carries no data yet.+func (migration *recreateUserDashboardPreference) 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().DropTable(&sqlschema.Table{Name: "user_dashboard_preference"})++ sqls = append(sqls, migration.sqlschema.Operator().CreateTable(&sqlschema.Table{+ Name: "user_dashboard_preference",+ Columns: []*sqlschema.Column{+ {Name: "id", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "user_id", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "dashboard_id", DataType: sqlschema.DataTypeText, Nullable: false},+ {Name: "is_pinned", DataType: sqlschema.DataTypeBoolean, Nullable: false, Default: "false"},+ {Name: "created_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},+ {Name: "updated_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},+ },+ PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{ColumnNames: []sqlschema.ColumnName{"id"}},+ ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{+ {+ ReferencingColumnName: sqlschema.ColumnName("user_id"),+ ReferencedTableName: sqlschema.TableName("users"),+ ReferencedColumnName: sqlschema.ColumnName("id"),+ },+ {+ ReferencingColumnName: sqlschema.ColumnName("dashboard_id"),+ ReferencedTableName: sqlschema.TableName("dashboard"),+ ReferencedColumnName: sqlschema.ColumnName("id"),+ },+ },+ })...)++ sqls = append(sqls, migration.sqlschema.Operator().CreateIndex(&sqlschema.UniqueIndex{+ TableName: "user_dashboard_preference",+ ColumnNames: []sqlschema.ColumnName{"user_id", "dashboard_id"},+ })...)++ for _, sql := range sqls {+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (migration *recreateUserDashboardPreference) Down(_ context.Context, _ *bun.DB) error {+ return nil+}diff --git a/pkg/types/dashboardtypes/perses_dashboard.go b/pkg/types/dashboardtypes/perses_dashboard.goindex cd936a2f92..d4a1683816 100644--- a/pkg/types/dashboardtypes/perses_dashboard.go+++ b/pkg/types/dashboardtypes/perses_dashboard.go@@ -61,10 +61,17 @@ type DashboardV2 struct {Spec DashboardSpec `json:"spec" required:"true"`}-func (d *DashboardV2) CanUpdate() error {+func (d *DashboardV2) ErrIfNotMutable() error {if d.Source == SourceIntegration {return errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardImmutable, "integration dashboards cannot be modified")}+ return nil+}++func (d *DashboardV2) ErrIfNotUpdatable() error {+ if err := d.ErrIfNotMutable(); err != nil {+ return err+ }if d.Locked {return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot update a locked dashboard, please unlock the dashboard to update")}@@ -72,7 +79,7 @@ func (d *DashboardV2) CanUpdate() error {}func (d *DashboardV2) Update(updatable UpdatableDashboardV2, updatedBy string, resolvedTags []*tagtypes.Tag) error {- if err := d.CanUpdate(); err != nil {+ if err := d.ErrIfNotUpdatable(); err != nil {return err}if updatable.Name != d.Name {@@ -86,7 +93,7 @@ func (d *DashboardV2) Update(updatable UpdatableDashboardV2, updatedBy string, rreturn nil}-func (d *DashboardV2) CanLockUnlock(isAdmin bool, updatedBy string) error {+func (d *DashboardV2) ErrIfNotLockable(isAdmin bool, updatedBy string) error {if d.Source == SourceIntegration {return errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardImmutable, "integration dashboards cannot be locked or unlocked")}@@ -100,7 +107,7 @@ func (d *DashboardV2) CanLockUnlock(isAdmin bool, updatedBy string) error {}func (d *DashboardV2) LockUnlock(lock bool, isAdmin bool, updatedBy string) error {- if err := d.CanLockUnlock(isAdmin, updatedBy); err != nil {+ if err := d.ErrIfNotLockable(isAdmin, updatedBy); err != nil {return err}d.Locked = lock@@ -109,7 +116,7 @@ func (d *DashboardV2) LockUnlock(lock bool, isAdmin bool, updatedBy string) erroreturn nil}-func (d *DashboardV2) CanDelete() error {+func (d *DashboardV2) ErrIfNotDeletable() error {if d.Locked {return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot delete a locked dashboard, please unlock the dashboard to delete")}diff --git a/pkg/types/dashboardtypes/store.go b/pkg/types/dashboardtypes/store.goindex 95beed7940..0115435792 100644--- a/pkg/types/dashboardtypes/store.go+++ b/pkg/types/dashboardtypes/store.go@@ -46,9 +46,9 @@ type Store interface {// Returns ErrCodePinnedDashboardLimitHit when the user is at MaxPinnedDashboardsPerUser.PinForUser(ctx context.Context, preference *UserDashboardPreference) error- UnpinForUser(ctx context.Context, userID valuer.UUID, dashboardID valuer.UUID) error+ UnpinForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, dashboardID valuer.UUID) error- DeletePreferencesForDashboard(ctx context.Context, dashboardID valuer.UUID) error+ DeletePreferencesForDashboard(ctx context.Context, orgID valuer.UUID, dashboardID valuer.UUID) error- DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error+ DeletePreferencesForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID) error}diff --git a/pkg/types/dashboardtypes/user_dashboard_preference.go b/pkg/types/dashboardtypes/user_dashboard_preference.goindex 867089c2a9..23b68217d3 100644--- a/pkg/types/dashboardtypes/user_dashboard_preference.go+++ b/pkg/types/dashboardtypes/user_dashboard_preference.go@@ -1,7 +1,10 @@package dashboardtypesimport (+ "time"+"github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/valuer""github.com/uptrace/bun")@@ -14,15 +17,20 @@ var ErrCodePinnedDashboardLimitHit = errors.MustNewCode("pinned_dashboard_limit_type UserDashboardPreference struct {bun.BaseModel `bun:"table:user_dashboard_preference,alias:user_dashboard_preference"`- UserID valuer.UUID `bun:"user_id,pk,type:text"`- DashboardID valuer.UUID `bun:"dashboard_id,pk,type:text"`+ types.Identifiable+ types.TimeAuditable+ UserID valuer.UUID `bun:"user_id,type:text"`+ DashboardID valuer.UUID `bun:"dashboard_id,type:text"`IsPinned bool `bun:"is_pinned,notnull,default:false"`}func NewUserDashboardPreference(userID, dashboardID valuer.UUID) *UserDashboardPreference {+ now := time.Now()return &UserDashboardPreference{- UserID: userID,- DashboardID: dashboardID,- IsPinned: true,+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},+ TimeAuditable: types.TimeAuditable{CreatedAt: now, UpdatedAt: now},+ UserID: userID,+ DashboardID: dashboardID,+ IsPinned: true,}}diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.pyindex edf4df8b45..265f529eff 100644--- a/tests/integration/tests/dashboard/03_v2_dashboard.py+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py@@ -1,5 +1,5 @@import uuid-from collections.abc import Callable, Iterator+from collections.abc import Callablefrom http import HTTPStatusimport pytest@@ -8,96 +8,7 @@ import requestsfrom fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORDfrom fixtures.types import Operation, SigNoz-# The v2 dashboard API. Request shape (current):-# {"schemaVersion": "v6", "name": "<dns-1123-label>",-# "spec": {"display": {"name": "<human name>"}},-# "tags": [{"key": "...", "value": "..."}]}-# `name` is a DNS-1123 label identifier and is immutable after create;-# `spec.display.name` is the human-facing title used for name-sort/name-filter.--_BASE = "/api/v2/dashboards"-_TIMEOUT = 5--# This file's tests tag their dashboards with a `suite` marker so list queries-# can be scoped server-side. Each test gets its own unique marker (the-# suite_marker fixture) so tests stay isolated from each other and from leftovers-# in the reused session DB.-_SUITE_PREFIX = "dashboardv2"---def _headers(token: str) -> dict:- return {"Authorization": f"Bearer {token}"}---def _url(signoz: SigNoz, path: str = "") -> str:- return signoz.self.host_configs["8080"].get(f"{_BASE}{path}")---def _create(signoz: SigNoz, token: str, body: dict) -> requests.Response:- return requests.post(_url(signoz), json=body, headers=_headers(token), timeout=_TIMEOUT)---def _get(signoz: SigNoz, token: str, dashboard_id: str) -> requests.Response:- return requests.get(_url(signoz, f"/{dashboard_id}"), headers=_headers(token), timeout=_TIMEOUT)---# The tests exercise the per-user list (carries pin state); the pure list lives-# at GET /api/v2/dashboards.-def _list(signoz: SigNoz, token: str, **params: object) -> requests.Response:- url = signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards")- return requests.get(- url,- params={k: v for k, v in params.items() if v is not None},- headers=_headers(token),- timeout=_TIMEOUT,- )---# The pure, user-independent list — no pin join, no pinned field.-def _list_pure(signoz: SigNoz, token: str, **params: object) -> requests.Response:- return requests.get(- _url(signoz),- params={k: v for k, v in params.items() if v is not None},- headers=_headers(token),- timeout=_TIMEOUT,- )---def _update(signoz: SigNoz, token: str, dashboard_id: str, body: dict) -> requests.Response:- return requests.put(- _url(signoz, f"/{dashboard_id}"),- json=body,- headers=_headers(token),- timeout=_TIMEOUT,- )---def _delete(signoz: SigNoz, token: str, dashboard_id: str) -> requests.Response:- return requests.delete(_url(signoz, f"/{dashboard_id}"), headers=_headers(token), timeout=_TIMEOUT)---def _lock(signoz: SigNoz, token: str, dashboard_id: str, lock: bool) -> requests.Response:- method = requests.put if lock else requests.delete- return method(- _url(signoz, f"/{dashboard_id}/lock"),- headers=_headers(token),- timeout=_TIMEOUT,- )---def _pin(signoz: SigNoz, token: str, dashboard_id: str, pin: bool) -> requests.Response:- method = requests.put if pin else requests.delete- url = signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{dashboard_id}/pins")- return method(url, headers=_headers(token), timeout=_TIMEOUT)---def _minimal_body(name: str, display: str, tags: list[dict] | None = None) -> dict:- return {- "schemaVersion": "v6",- "name": name,- "spec": {"display": {"name": display}},- "tags": tags or [],- }+BASE_URL = "/api/v2/dashboards"# ─── failure cases (create no dashboards) ────────────────────────────────────@@ -110,7 +21,12 @@ def test_create_rejects_wrong_schema_version():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _create(signoz, token, {})+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTbody = response.json()@@ -126,7 +42,12 @@ def test_create_rejects_missing_name():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _create(signoz, token, {"schemaVersion": "v6"})+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={"schemaVersion": "v6"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTbody = response.json()@@ -141,7 +62,17 @@ def test_create_rejects_non_dns_name():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _create(signoz, token, _minimal_body(name="Not A Label", display="Not A Label"))+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "Not A Label",+ "spec": {"display": {"name": "Not A Label"}},+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTassert response.json()["error"]["code"] == "dashboard_invalid_input"@@ -154,9 +85,18 @@ def test_create_rejects_unknown_field():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- body = _minimal_body("rejects-unknown", "Rejects Unknown")- body["unknownfield"] = "boom"- response = _create(signoz, token, body)+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "rejects-unknown",+ "spec": {"display": {"name": "Rejects Unknown"}},+ "tags": [],+ "unknownfield": "boom",+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTassert response.json()["error"]["code"] == "dashboard_invalid_input"@@ -170,8 +110,17 @@ def test_create_rejects_reserved_tag_key():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- body = _minimal_body("rejects-reserved", "Rejects Reserved", [{"key": "source", "value": "x"}])- response = _create(signoz, token, body)+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "rejects-reserved",+ "spec": {"display": {"name": "Rejects Reserved"}},+ "tags": [{"key": "source", "value": "x"}],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTassert response.json()["error"]["code"] == "dashboard_invalid_input"@@ -185,7 +134,17 @@ def test_create_rejects_too_many_tags(token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)tags = [{"key": f"k{i}", "value": "v"} for i in range(11)]- response = _create(signoz, token, _minimal_body("too-many-tags", "Too Many", tags))+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "too-many-tags",+ "spec": {"display": {"name": "Too Many"}},+ "tags": tags,+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTassert response.json()["error"]["code"] == "dashboard_invalid_input"@@ -208,7 +167,12 @@ def test_list_rejects_invalid_params():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _list(signoz, token, **params)+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params=params,+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUESTassert response.json()["error"]["code"] == "dashboard_list_invalid"@@ -221,7 +185,11 @@ def test_get_rejects_malformed_id():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _get(signoz, token, "not-a-uuid")+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/not-a-uuid"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.BAD_REQUEST@@ -233,7 +201,11 @@ def test_get_missing_dashboard_returns_not_found():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _get(signoz, token, str(uuid.uuid4()))+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{uuid.uuid4()}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.NOT_FOUND@@ -245,7 +217,11 @@ def test_delete_missing_dashboard_returns_not_found():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _delete(signoz, token, str(uuid.uuid4()))+ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{uuid.uuid4()}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.NOT_FOUND@@ -257,58 +233,44 @@ def test_pin_missing_dashboard_returns_not_found():token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- response = _pin(signoz, token, str(uuid.uuid4()), pin=True)+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{uuid.uuid4()}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.NOT_FOUND# ─── lifecycle ───────────────────────────────────────────────────────────────# A single end-to-end flow through create → get → list/filter/sort → pin →-# update → lock → delete. Every fixture dashboard carries the shared suite marker-# tag so list queries can be scoped server-side, isolating this test from any-# other dashboards sharing the session DB.---def _display_names(body: dict) -> list[str]:- return [d["spec"]["display"]["name"] for d in body["data"]["dashboards"]]---def _delete_suite(signoz: SigNoz, token: str, suite_filter: str) -> None:- response = _list(signoz, token, query=suite_filter, limit=200)- if response.status_code != HTTPStatus.OK:- return- for dashboard in response.json()["data"]["dashboards"]:- _delete(signoz, token, dashboard["id"])--[email protected](name="suite_marker")-def _suite_marker(- signoz: SigNoz,- get_token: Callable[[str, str], str],-) -> Iterator[tuple[dict, str]]:- """Yields a per-test unique suite (tag, filter) and deletes its dashboards on teardown.- Unique per test so the tests stay isolated from each other and from reused-DB leftovers."""- value = f"{_SUITE_PREFIX}-{uuid.uuid4().hex[:8]}"- suite_tag = {"key": "suite", "value": value}- suite_filter = f"suite = '{value}'"- yield suite_tag, suite_filter- token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)- _delete_suite(signoz, token, suite_filter)+# update → lock → delete.def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-statementssignoz: SigNoz,create_user_admin: Operation, # pylint: disable=unused-argumentget_token: Callable[[str, str], str],- suite_marker: tuple[dict, str],):- suite_tag, suite_filter = suite_marker-- def _scoped(query: str) -> str:- return f"({query}) AND {suite_filter}"-token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ # The dashboard test files share this package's DB and it's reused across+ # runs, so start from a clean slate: delete every dashboard (which also clears+ # pins via the delete cascade). This test then owns the whole dashboard space+ # and asserts on global counts.+ existing = requests.get(+ signoz.self.host_configs["8080"].get(BASE_URL),+ params={"limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).json()["data"]["dashboards"]+ for dashboard in existing:+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard['id']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+dashboard_requests = [("lc-alpha",@@ -353,18 +315,38 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta# ── stage 1: create ──────────────────────────────────────────────────────ids: dict[str, str] = {}for name, display, tags in dashboard_requests:- response = _create(signoz, token, _minimal_body(name, display, [suite_tag, *tags]))+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": name,+ "spec": {"display": {"name": display}},+ "tags": tags,+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.CREATED, response.textids[name] = response.json()["data"]["id"]# TODO: re-enable once the dashboard name unique index lands — creating a# second dashboard with an existing name should conflict (409). Until the# index exists, duplicate names are silently allowed.- # response = _create(signoz, token, _minimal_body("lc-alpha", "Alpha Dupe"))+ # response = requests.post(+ # signoz.self.host_configs["8080"].get(_BASE),+ # json={"schemaVersion": "v6", "name": "lc-alpha",+ # "spec": {"display": {"name": "Alpha Dupe"}}, "tags": []},+ # headers={"Authorization": f"Bearer {token}"},+ # timeout=5,+ # )# assert response.status_code == HTTPStatus.CONFLICT, response.text# ── stage 2: get one and verify the round-tripped shape ──────────────────- response = _get(signoz, token, ids["lc-alpha"])+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-alpha']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.OK, response.textalpha = response.json()["data"]assert alpha["id"] == ids["lc-alpha"]@@ -375,12 +357,17 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-staassert alpha["locked"] is Falseassert {"key": "team", "value": "pulse"} in alpha["tags"]- # ── stage 3: list everything in the suite ────────────────────────────────- response = _list(signoz, token, query=suite_filter, limit=200)+ # ── stage 3: list everything ─────────────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.OK, response.textbody = response.json()assert body["data"]["total"] == 6- assert set(_display_names(body)) == {+ assert {d["spec"]["display"]["name"] for d in body["data"]["dashboards"]} == {"Alpha Overview","Beta Overview","Gamma Storage",@@ -490,13 +477,23 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta),]for query, expected in cases:- response = _list(signoz, token, query=_scoped(query), limit=200)+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"query": query, "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.OK, response.text- assert set(_display_names(response.json())) == expected, query+ assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == expected, query# ── stage 5: name sort honours order ─────────────────────────────────────- response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)- assert _display_names(response.json()) == [+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"sort": "name", "order": "asc", "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert [d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]] == ["Alpha Overview","Beta Overview","Delta Storage",@@ -504,8 +501,13 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta"Gamma Storage","Zeta Overview",]- response = _list(signoz, token, query=suite_filter, sort="name", order="desc", limit=200)- assert _display_names(response.json()) == [+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"sort": "name", "order": "desc", "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert [d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]] == ["Zeta Overview","Gamma Storage","Epsilon Metrics",@@ -515,8 +517,20 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta]# ── stage 6: pinning floats a dashboard to the top of any ordering ───────- assert _pin(signoz, token, ids["lc-gamma"], pin=True).status_code == HTTPStatus.NO_CONTENT- response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids['lc-gamma']}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"sort": "name", "order": "asc", "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )dashboards = response.json()["data"]["dashboards"]assert dashboards[0]["name"] == "lc-gamma"assert dashboards[0]["pinned"] is True@@ -524,8 +538,13 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta# the pure list is user-independent: the same pin neither reorders it (gamma# stays in natural name order, not floated to the top) nor adds a pinned field.- response = _list_pure(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)- assert _display_names(response.json()) == [+ response = requests.get(+ signoz.self.host_configs["8080"].get(BASE_URL),+ params={"sort": "name", "order": "asc", "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert [d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]] == ["Alpha Overview","Beta Overview","Delta Storage",@@ -536,9 +555,21 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-staassert all("pinned" not in d for d in response.json()["data"]["dashboards"])# ── stage 7: unpinning restores the natural ordering ─────────────────────- assert _pin(signoz, token, ids["lc-gamma"], pin=False).status_code == HTTPStatus.NO_CONTENT- response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)- assert _display_names(response.json()) == [+ assert (+ requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids['lc-gamma']}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"sort": "name", "order": "asc", "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert [d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]] == ["Alpha Overview","Beta Overview","Delta Storage",@@ -548,39 +579,95 @@ def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-sta]# ── stage 8: update mutates the spec but keeps the immutable name ────────- update_body = _minimal_body(- "lc-alpha",- "Alpha Overview",- [- suite_tag,+ update_body = {+ "schemaVersion": "v6",+ "name": "lc-alpha",+ "spec": {"display": {"name": "Alpha Overview"}},+ "tags": [{"key": "team", "value": "pulse"},{"key": "env", "value": "prod"},],- )+ }update_body["spec"]["display"]["description"] = "now with a description"- response = _update(signoz, token, ids["lc-alpha"], update_body)+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-alpha']}"),+ json=update_body,+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.OK, response.text- response = _get(signoz, token, ids["lc-alpha"])+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-alpha']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.json()["data"]["spec"]["display"]["description"] == "now with a description"# ── stage 9: a locked dashboard rejects updates until unlocked ───────────- assert _lock(signoz, token, ids["lc-beta"], lock=True).status_code == HTTPStatus.NO_CONTENT- beta_body = _minimal_body(- "lc-beta",- "Beta Overview",- [suite_tag, {"key": "team", "value": "pulse"}, {"key": "env", "value": "dev"}],+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-beta']}/lock"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ beta_body = {+ "schemaVersion": "v6",+ "name": "lc-beta",+ "spec": {"display": {"name": "Beta Overview"}},+ "tags": [{"key": "team", "value": "pulse"}, {"key": "env", "value": "dev"}],+ }+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-beta']}"),+ json=beta_body,+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,)- response = _update(signoz, token, ids["lc-beta"], beta_body)assert response.status_code == HTTPStatus.BAD_REQUEST- assert _lock(signoz, token, ids["lc-beta"], lock=False).status_code == HTTPStatus.NO_CONTENT- assert _update(signoz, token, ids["lc-beta"], beta_body).status_code == HTTPStatus.OK+ assert (+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-beta']}/lock"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-beta']}"),+ json=beta_body,+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.OK+ )# ── stage 10: delete removes the dashboard from get and list ─────────────- assert _delete(signoz, token, ids["lc-gamma"]).status_code == HTTPStatus.NO_CONTENT- assert _get(signoz, token, ids["lc-gamma"]).status_code == HTTPStatus.NOT_FOUND- response = _list(signoz, token, query=suite_filter, limit=200)+ assert (+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-gamma']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ assert (+ requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{ids['lc-gamma']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NOT_FOUND+ )+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.json()["data"]["total"] == 5- assert set(_display_names(response.json())) == {+ assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == {"Alpha Overview","Beta Overview","Delta Storage",@@ -593,34 +680,89 @@ def test_dashboard_v2_pin_limit(signoz: SigNoz,create_user_admin: Operation, # pylint: disable=unused-argumentget_token: Callable[[str, str], str],- suite_marker: tuple[dict, str],):- suite_tag, _ = suite_markermax_pinned = 10token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ # Wipe the dashboard space (see lifecycle) so the per-user pin cap this test+ # asserts against starts empty — deleting dashboards clears their pins.+ existing = requests.get(+ signoz.self.host_configs["8080"].get(BASE_URL),+ params={"limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).json()["data"]["dashboards"]+ for dashboard in existing:+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard['id']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ids: list[str] = []for i in range(max_pinned + 1):- response = _create(signoz, token, _minimal_body(f"pl-{i}", f"Pin Limit {i}", [suite_tag]))+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": f"pl-{i}",+ "spec": {"display": {"name": f"Pin Limit {i}"}},+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.CREATED, response.textids.append(response.json()["data"]["id"])# pinning up to the limit succeedsfor dashboard_id in ids[:max_pinned]:- assert _pin(signoz, token, dashboard_id, pin=True).status_code == HTTPStatus.NO_CONTENT+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{dashboard_id}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )# re-pinning an already-pinned dashboard is an idempotent no-op, even at the limit- assert _pin(signoz, token, ids[0], pin=True).status_code == HTTPStatus.NO_CONTENT+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[0]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )# the 11th distinct pin is rejected with the typed limit error- response = _pin(signoz, token, ids[max_pinned], pin=True)+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[max_pinned]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.CONFLICT, response.textassert response.json()["error"]["code"] == "pinned_dashboard_limit_hit"# unpinning frees a slot, so the previously-rejected dashboard can now be pinned- assert _pin(signoz, token, ids[0], pin=False).status_code == HTTPStatus.NO_CONTENT- assert _pin(signoz, token, ids[max_pinned], pin=True).status_code == HTTPStatus.NO_CONTENT+ assert (+ requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[0]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )+ assert (+ requests.put(+ signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{ids[max_pinned]}/pins"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).status_code+ == HTTPStatus.NO_CONTENT+ )# ─── LIKE escaping ───────────────────────────────────────────────────────────@@ -638,12 +780,24 @@ def test_dashboard_v2_like_escaping(signoz: SigNoz,create_user_admin: Operation, # pylint: disable=unused-argumentget_token: Callable[[str, str], str],- suite_marker: tuple[dict, str],):- suite_tag, suite_filter = suite_marker-token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ # Wipe the dashboard space (see lifecycle) so the filter assertions run+ # against only the dashboards this test creates.+ existing = requests.get(+ signoz.self.host_configs["8080"].get(BASE_URL),+ params={"limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ ).json()["data"]["dashboards"]+ for dashboard in existing:+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard['id']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+dashboard_requests = [("esc-pct", "Cost 50% Report"),("esc-pct-plain", "Cost 5000 Report"),@@ -651,7 +805,17 @@ def test_dashboard_v2_like_escaping(("esc-underscore-wild", "userXid panel"),]for name, display in dashboard_requests:- response = _create(signoz, token, _minimal_body(name, display, [suite_tag]))+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": name,+ "spec": {"display": {"name": display}},+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )assert response.status_code == HTTPStatus.CREATED, response.textcases = [@@ -685,11 +849,11 @@ def test_dashboard_v2_like_escaping(),]for query, expected in cases:- response = _list(- signoz,- token,- query=f"({query}) AND {suite_filter}",- limit=200,+ response = requests.get(+ signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards"),+ params={"query": query, "limit": 200},+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,)assert response.status_code == HTTPStatus.OK, response.text- assert set(_display_names(response.json())) == expected, query+ assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == expected, query