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: remove omitempty/omitzero and explicit empty value handling in dashboard v2 spec (#12197)
Naman Verma14bb4a843713
diff --git a/pkg/types/dashboardtypes/perses_dashboard.go b/pkg/types/dashboardtypes/perses_dashboard.goindex c2b5564fc8..7bba6e4659 100644--- a/pkg/types/dashboardtypes/perses_dashboard.go+++ b/pkg/types/dashboardtypes/perses_dashboard.go@@ -186,8 +186,8 @@ type DashboardV2MetadataBase struct {type PostableDashboardV2 struct {DashboardV2MetadataBase- Name string `json:"name,omitempty"`- GenerateName bool `json:"generateName,omitempty"`+ Name string `json:"name"`+ GenerateName bool `json:"generateName"`Tags []tagtypes.PostableTag `json:"tags" required:"true"`Spec DashboardSpec `json:"spec" required:"true"`}diff --git a/pkg/types/dashboardtypes/perses_dashboard_patch.go b/pkg/types/dashboardtypes/perses_dashboard_patch.goindex a056cc32f4..3d70c02b56 100644--- a/pkg/types/dashboardtypes/perses_dashboard_patch.go+++ b/pkg/types/dashboardtypes/perses_dashboard_patch.go@@ -32,9 +32,9 @@ type JSONPatchOperation struct {Op PatchOp `json:"op" required:"true"`Path string `json:"path" required:"true" description:"JSON Pointer (RFC 6901) into the dashboard's postable shape — e.g. /spec/display/name, /spec/panels/<id>, /spec/panels/<id>/spec/queries/0, /tags/-."`// `value` is required for add/replace/test.- Value any `json:"value,omitempty" description:"Value to add/replace/test against. The expected type depends on the path. Common shapes (see referenced schemas for the exact field set): /spec/panels/<id> takes a DashboardtypesPanel; /spec/panels/<id>/spec/queries/N (or /-) takes a DashboardtypesQuery; /spec/variables/N takes a DashboardtypesVariable; /spec/layouts/N takes a DashboardtypesLayout; /tags/N (or /-) takes a TagtypesPostableTag; /spec/display/name and other leaf string fields take a string. Required for add/replace/test; ignored for remove/move/copy."`+ Value any `json:"value" description:"Value to add/replace/test against. The expected type depends on the path. Common shapes (see referenced schemas for the exact field set): /spec/panels/<id> takes a DashboardtypesPanel; /spec/panels/<id>/spec/queries/N (or /-) takes a DashboardtypesQuery; /spec/variables/N takes a DashboardtypesVariable; /spec/layouts/N takes a DashboardtypesLayout; /tags/N (or /-) takes a TagtypesPostableTag; /spec/display/name and other leaf string fields take a string. Required for add/replace/test; ignored for remove/move/copy."`// `from` is required for move/copy.- From string `json:"from,omitempty" description:"Source JSON Pointer for move/copy ops; ignored for other ops."`+ From string `json:"from" description:"Source JSON Pointer for move/copy ops; ignored for other ops."`}// PatchOp covers the six RFC 6902 JSON Patch verbs.diff --git a/pkg/types/dashboardtypes/perses_dashboard_test.go b/pkg/types/dashboardtypes/perses_dashboard_test.goindex 5599f7e1b0..00d0b884f5 100644--- a/pkg/types/dashboardtypes/perses_dashboard_test.go+++ b/pkg/types/dashboardtypes/perses_dashboard_test.go@@ -241,9 +241,34 @@ func TestInvalidateListVariableCrossFields(t *testing.T) {assert.Contains(t, err.Error(), "allowMultiple")})+ extractVariableSort := func(t *testing.T, d *DashboardSpec) ListVariableSpecSort {+ require.Len(t, d.Variables, 1)+ spec, ok := d.Variables[0].Spec.(*ListVariableSpec)+ require.True(t, ok, "variable spec should be a *ListVariableSpec")+ return spec.Sort+ }+t.Run("valid sort is accepted", func(t *testing.T) {- _, err := unmarshalDashboard(listVar(`"sort": "alphabetical-asc",`))- assert.NoError(t, err)+ d, err := unmarshalDashboard(listVar(`"sort": "alphabetical-asc",`))+ require.NoError(t, err)+ assert.Equal(t, SortAlphabeticalAsc, extractVariableSort(t, d))+ })++ t.Run("explicit empty sort is rejected", func(t *testing.T) {+ _, err := unmarshalDashboard(listVar(`"sort": "",`))+ require.Error(t, err)+ assert.Contains(t, err.Error(), "unknown sort")+ })++ t.Run("omitted sort defaults to none", func(t *testing.T) {+ d, err := unmarshalDashboard(listVar(``))+ require.NoError(t, err)+ assert.Equal(t, "none", extractVariableSort(t, d).ValueOrDefault())++ // Re-marshal (what we'd store / return): the default surfaces explicitly.+ out, err := json.Marshal(d)+ require.NoError(t, err)+ assert.Contains(t, string(out), `"sort":"none"`)})t.Run("unknown sort is rejected", func(t *testing.T) {diff --git a/pkg/types/dashboardtypes/perses_replicas.go b/pkg/types/dashboardtypes/perses_replicas.goindex 2a6c92e085..90bf8f2c01 100644--- a/pkg/types/dashboardtypes/perses_replicas.go+++ b/pkg/types/dashboardtypes/perses_replicas.go@@ -177,7 +177,7 @@ type ListVariableSpec struct {AllowMultiple bool `json:"allowMultiple"`CustomAllValue string `json:"customAllValue"`CapturingRegexp string `json:"capturingRegexp"`- Sort ListVariableSpecSort `json:"sort,omitzero"`+ Sort ListVariableSpecSort `json:"sort"`Plugin VariablePlugin `json:"plugin"`Name string `json:"name" required:"true" minLength:"1"`}@@ -267,18 +267,25 @@ func (s ListVariableSpecSort) IsValid() bool {return slices.ContainsFunc(s.Enum(), func(v any) bool { return v == s })}+func (s ListVariableSpecSort) ValueOrDefault() string {+ if s.IsZero() {+ return SortNone.StringValue()+ }+ return s.StringValue()+}++func (s ListVariableSpecSort) MarshalJSON() ([]byte, error) {+ return json.Marshal(s.ValueOrDefault())+}+// UnmarshalJSON validates against the enum on decode (valuer.String alone-// accepts any string). An empty value is allowed and means "no sort", matching-// Perses.+// accepts any string). An omitted sort defaults to `none` via ValueOrDefault; an+// explicit value present in the JSON — including `""` — is validated as-is.func (s *ListVariableSpecSort) UnmarshalJSON(data []byte) error {var v stringif err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid sort: must be a string, one of `none`, `alphabetical-asc`, `alphabetical-desc`, `numerical-asc`, `numerical-desc`, `alphabetical-ci-asc`, or `alphabetical-ci-desc`")}- if v == "" {- *s = ListVariableSpecSort{}- return nil- }sort := ListVariableSpecSort{valuer.NewString(v)}if !sort.IsValid() {return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown sort %q: must be `none`, `alphabetical-asc`, `alphabetical-desc`, `numerical-asc`, `numerical-desc`, `alphabetical-ci-asc`, or `alphabetical-ci-desc`", v)diff --git a/pkg/types/dashboardtypes/perses_signoz_plugins.go b/pkg/types/dashboardtypes/perses_signoz_plugins.goindex bd456c9884..a12b69097b 100644--- a/pkg/types/dashboardtypes/perses_signoz_plugins.go+++ b/pkg/types/dashboardtypes/perses_signoz_plugins.go@@ -316,10 +316,6 @@ func (t *TimePreference) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid timePreference: must be a string, one of `global_time`, `last_5_min`, `last_15_min`, `last_30_min`, `last_1_hr`, `last_6_hr`, `last_1_day`, `last_3_days`, `last_1_week`, or `last_1_month`")}- if v == "" {- *t = TimePreferenceGlobalTime- return nil- }tp := TimePreference{valuer.NewString(v)}switch tp {case TimePreferenceGlobalTime, TimePreferenceLast5Min, TimePreferenceLast15Min, TimePreferenceLast30Min, TimePreferenceLast1Hr, TimePreferenceLast6Hr, TimePreferenceLast1Day, TimePreferenceLast3Days, TimePreferenceLast1Week, TimePreferenceLast1Month:@@ -357,10 +353,6 @@ func (l *LegendPosition) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid legend position: must be a string, one of `bottom` or `right`")}- if v == "" {- *l = LegendPositionBottom- return nil- }lp := LegendPosition{valuer.NewString(v)}switch lp {case LegendPositionBottom, LegendPositionRight:@@ -398,10 +390,6 @@ func (m *LegendMode) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid legend mode: must be a string, one of `list` or `table`")}- if v == "" {- *m = LegendModeList- return nil- }lm := LegendMode{valuer.NewString(v)}switch lm {case LegendModeList, LegendModeTable:@@ -439,10 +427,6 @@ func (f *ThresholdFormat) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid threshold format: must be a string, one of `text` or `background`")}- if v == "" {- *f = ThresholdFormatText- return nil- }tf := ThresholdFormat{valuer.NewString(v)}switch tf {case ThresholdFormatText, ThresholdFormatBackground:@@ -486,10 +470,6 @@ func (o *ComparisonOperator) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid comparison operator: must be a string, one of `above`, `below`, `above_or_equal`, `below_or_equal`, `equal`, or `not_equal`")}- if v == "" {- *o = ComparisonOperatorAbove- return nil- }co := ComparisonOperator{valuer.NewString(v)}switch co {case ComparisonOperatorAbove, ComparisonOperatorBelow, ComparisonOperatorAboveOrEqual, ComparisonOperatorBelowOrEqual,@@ -530,10 +510,6 @@ func (li *LineInterpolation) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid line interpolation: must be a string, one of `linear`, `spline`, `step_after`, or `step_before`")}- if v == "" {- *li = LineInterpolationSpline- return nil- }val := LineInterpolation{valuer.NewString(v)}switch val {case LineInterpolationLinear, LineInterpolationSpline, LineInterpolationStepAfter, LineInterpolationStepBefore:@@ -571,10 +547,6 @@ func (ls *LineStyle) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid line style: must be a string, one of `solid` or `dashed`")}- if v == "" {- *ls = LineStyleSolid- return nil- }val := LineStyle{valuer.NewString(v)}switch val {case LineStyleSolid, LineStyleDashed:@@ -613,10 +585,6 @@ func (fm *FillMode) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid fill mode: must be a string, one of `solid`, `gradient`, or `none`")}- if v == "" {- *fm = FillModeNone- return nil- }val := FillMode{valuer.NewString(v)}switch val {case FillModeSolid, FillModeGradient, FillModeNone:@@ -705,10 +673,6 @@ func (p *PrecisionOption) UnmarshalJSON(data []byte) error {if err := json.Unmarshal(data, &v); err != nil {return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid precision option: must be `0`, `1`, `2`, `3`, `4`, or `full`")}- if v == "" {- *p = PrecisionOption2- return nil- }val := PrecisionOption{valuer.NewString(v)}switch val {case PrecisionOption0, PrecisionOption1, PrecisionOption2, PrecisionOption3, PrecisionOption4, PrecisionOptionFull:diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.pyindex 888775f7b1..e5c087aa8e 100644--- a/tests/integration/tests/dashboard/03_v2_dashboard.py+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py@@ -1806,3 +1806,190 @@ def test_dashboard_v2_roundtrip_preserves_zero_values(headers=headers,timeout=5,)+++# ─── enum defaulting: absent applies the default, explicit "" is rejected ─────+# The v2 dashboard enums (timePreference, decimalPrecision, lineInterpolation,+# lineStyle, fillMode, legend position/mode, comparison operator, threshold+# format, list-variable sort) apply their default only when the field is omitted+# entirely: UnmarshalJSON never runs, so the zero value marshals back as the+# default. An explicit "" is validated like any other string and, since "" is+# never an allowed enum member, rejected.+++def test_dashboard_v2_omitted_enums_apply_defaults(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ headers = {"Authorization": f"Bearer {token}"}++ # The TimeSeriesPanel carries an empty plugin spec (every enum omitted); the+ # NumberPanel threshold omits operator and format. Each must read back as its+ # default.+ dashboard = {+ "schemaVersion": "v6",+ "name": f"enum-{uuid.uuid4().hex[:8]}",+ "tags": [],+ "spec": {+ "display": {"name": "Enum"},+ "panels": {+ "ts": {+ "kind": "Panel",+ "spec": {+ "display": {"name": "ts"},+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},+ "queries": [+ {+ "kind": "time_series",+ "spec": {+ "plugin": {+ "kind": "signoz/BuilderQuery",+ "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]},+ }+ },+ }+ ],+ },+ },+ "num": {+ "kind": "Panel",+ "spec": {+ "display": {"name": "num"},+ "plugin": {+ "kind": "signoz/NumberPanel",+ "spec": {"thresholds": [{"value": 1, "color": "#c2780b"}]},+ },+ "queries": [+ {+ "kind": "scalar",+ "spec": {+ "plugin": {+ "kind": "signoz/BuilderQuery",+ "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]},+ }+ },+ }+ ],+ },+ },+ },+ },+ }++ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json=dashboard,+ headers=headers,+ timeout=5,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ dashboard_id = response.json()["data"]["id"]++ try:+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard_id}"),+ headers=headers,+ timeout=5,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ panels = response.json()["data"]["spec"]["panels"]+ ts = panels["ts"]["spec"]["plugin"]["spec"]+ num_threshold = panels["num"]["spec"]["plugin"]["spec"]["thresholds"][0]++ default_cases = [+ ("timePreference", ts["visualization"]["timePreference"], "global_time"),+ ("decimalPrecision", ts["formatting"]["decimalPrecision"], "2"),+ ("lineInterpolation", ts["chartAppearance"]["lineInterpolation"], "spline"),+ ("lineStyle", ts["chartAppearance"]["lineStyle"], "solid"),+ ("fillMode", ts["chartAppearance"]["fillMode"], "none"),+ ("legend position", ts["legend"]["position"], "bottom"),+ ("legend mode", ts["legend"]["mode"], "list"),+ ("comparison operator", num_threshold["operator"], "above"),+ ("threshold format", num_threshold["format"], "text"),+ ]+ for description, actual, expected in default_cases:+ assert actual == expected, description+ finally:+ requests.delete(+ signoz.self.host_configs["8080"].get(f"{BASE_URL}/{dashboard_id}"),+ headers=headers,+ timeout=5,+ )+++# Every v2 enum shares the same UnmarshalJSON validation, so one panel enum+# (timePreference) and the list-variable sort are enough to prove an explicit ""+# is rejected; the rest behave identically.+def test_dashboard_v2_rejects_explicit_empty_enum(+ signoz: SigNoz,+ create_user_admin: Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+):+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ headers = {"Authorization": f"Bearer {token}"}++ bad_dashboards = [+ # A panel scalar enum: timePreference set to "".+ {+ "schemaVersion": "v6",+ "name": f"enum-{uuid.uuid4().hex[:8]}",+ "tags": [],+ "spec": {+ "display": {"name": "Enum"},+ "panels": {+ "p": {+ "kind": "Panel",+ "spec": {+ "display": {"name": "ts"},+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {"visualization": {"timePreference": ""}}},+ "queries": [+ {+ "kind": "time_series",+ "spec": {+ "plugin": {+ "kind": "signoz/BuilderQuery",+ "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]},+ }+ },+ }+ ],+ },+ }+ },+ },+ },+ # A variable enum: list-variable sort set to "".+ {+ "schemaVersion": "v6",+ "name": f"enum-{uuid.uuid4().hex[:8]}",+ "tags": [],+ "spec": {+ "display": {"name": "Enum"},+ "variables": [+ {+ "kind": "ListVariable",+ "spec": {+ "display": {"name": "lv"},+ "allowAllValue": False,+ "allowMultiple": False,+ "plugin": {"kind": "signoz/DynamicVariable", "spec": {"name": "service.name", "signal": "metrics"}},+ "name": "lv",+ "sort": "",+ },+ }+ ],+ },+ },+ ]++ for body in bad_dashboards:+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json=body,+ headers=headers,+ timeout=5,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text+ assert response.json()["error"]["code"] == "dashboard_invalid_input", response.text