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: validate layout size and positioning in backend (#11921)
Naman Vermadbb4eb9574bb
diff --git a/pkg/types/dashboardtypes/perses_dashboard_data.go b/pkg/types/dashboardtypes/perses_dashboard_data.goindex 77f8a2d7d0..36f2470d28 100644--- a/pkg/types/dashboardtypes/perses_dashboard_data.go+++ b/pkg/types/dashboardtypes/perses_dashboard_data.go@@ -138,14 +138,33 @@ func validateQueryAllowedForPanel(plugin QueryPlugin, allowed []QueryPluginKind,return nil}-// validateLayouts rejects grid items referencing a panel that doesn't exist.+const maxLayoutsPerDashboard = 500++// validateLayouts validates the dashboard's layouts: bounded section count,+// per-item geometry, resolvable panel references, and no panel placed twice.+// Geometry (validateGridLayoutGeometry) needs only each layout's own data but+// runs here so its errors can name the layout by index.func (d *DashboardSpec) validateLayouts() error {+ if len(d.Layouts) > maxLayoutsPerDashboard {+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts: dashboard has %d layouts; maximum is %d", len(d.Layouts), maxLayoutsPerDashboard)+ }++ // Could enforce this but skipping for now: panels in no grid item (orphans)+ // are allowed.++ // The frontend keys each grid item by its panel id, so placing one panel in+ // two grid items collides; reject duplicate references dashboard-wide. Maps+ // each referenced panel key to the path of the item that first placed it.+ referencedPanels := make(map[string]string, len(d.Panels))for li, layout := range d.Layouts {grid, ok := layout.Spec.(*dashboard.GridLayoutSpec)if !ok {// Unreachable via UnmarshalJSON; reaching here means a Go caller broke the Kind/Spec pairing.return errors.NewInternalf(errors.CodeInternal, "spec.layouts[%d].spec: unexpected layout spec type %T", li, layout.Spec)}+ if err := validateGridLayoutGeometry(grid, li); err != nil {+ return err+ }for ii, item := range grid.Items {path := fmt.Sprintf("spec.layouts[%d].spec.items[%d].content", li, ii)if item.Content == nil {@@ -158,6 +177,10 @@ func (d *DashboardSpec) validateLayouts() error {if _, ok := d.Panels[key]; !ok {return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s: references unknown panel %q", path, key)}+ if firstPath, dup := referencedPanels[key]; dup {+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s: panel %q is already placed by %s", path, key, firstPath)+ }+ referencedPanels[key] = path}}return nildiff --git a/pkg/types/dashboardtypes/perses_dashboard_patch_test.go b/pkg/types/dashboardtypes/perses_dashboard_patch_test.goindex cf45a59109..32ca5dd0b9 100644--- a/pkg/types/dashboardtypes/perses_dashboard_patch_test.go+++ b/pkg/types/dashboardtypes/perses_dashboard_patch_test.go@@ -299,19 +299,22 @@ func TestPatchableDashboardV2_Apply(t *testing.T) {// Layout edits// ─────────────────────────────────────────────────────────────────- t.Run("move panel by editing layout x coordinate", func(t *testing.T) {- out, err := decode(t, `[{"op": "replace", "path": "/spec/layouts/0/spec/items/0/x", "value": 6}]`).Apply(base)+ t.Run("move panel by editing layout y coordinate", func(t *testing.T) {+ // p2 fills the right half of row 0, so p1 can only move to a fresh row+ // without tripping overlap validation.+ out, err := decode(t, `[{"op": "replace", "path": "/spec/layouts/0/spec/items/0/y", "value": 6}]`).Apply(base)require.NoError(t, err)raw := jsonOf(t, out)- // The first item used to live at x=0, now lives at x=6.- assert.Contains(t, raw, `"x":6,"y":0,"width":6,"height":6,"content":{"$ref":"#/spec/panels/p1"}`)+ // The first item used to live at y=0, now lives at y=6.+ assert.Contains(t, raw, `"x":0,"y":6,"width":6,"height":6,"content":{"$ref":"#/spec/panels/p1"}`)})t.Run("resize panel by editing layout width", func(t *testing.T) {- out, err := decode(t, `[{"op": "replace", "path": "/spec/layouts/0/spec/items/0/width", "value": 12}]`).Apply(base)+ // p2 sits at x=6, so p1 (at x=0) can only shrink; widening it would overlap.+ out, err := decode(t, `[{"op": "replace", "path": "/spec/layouts/0/spec/items/0/width", "value": 3}]`).Apply(base)require.NoError(t, err)raw := jsonOf(t, out)- assert.Contains(t, raw, `"width":12`)+ assert.Contains(t, raw, `"width":3`)})t.Run("rename layout row title", func(t *testing.T) {@@ -321,11 +324,12 @@ func TestPatchableDashboardV2_Apply(t *testing.T) {})t.Run("append layout item", func(t *testing.T) {- out, err := decode(t, `[{- "op": "add",- "path": "/spec/layouts/0/spec/items/-",- "value": {"x": 0, "y": 6, "width": 12, "height": 6, "content": {"$ref": "#/spec/panels/p1"}}- }]`).Apply(base)+ // Appending needs a not-yet-placed panel, so add one in the same patch;+ // re-placing p1 or p2 would be a duplicate reference.+ out, err := decode(t, `[+ {"op": "add", "path": "/spec/panels/p3", "value": {"kind": "Panel", "spec": {"plugin": {"kind": "signoz/TablePanel", "spec": {}}, "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]}}}}]}}},+ {"op": "add", "path": "/spec/layouts/0/spec/items/-", "value": {"x": 0, "y": 6, "width": 12, "height": 6, "content": {"$ref": "#/spec/panels/p3"}}}+ ]`).Apply(base)require.NoError(t, err)// Item count went 2 → 3.raw := jsonOf(t, out)diff --git a/pkg/types/dashboardtypes/perses_dashboard_test.go b/pkg/types/dashboardtypes/perses_dashboard_test.goindex a3af121621..32d2a7a947 100644--- a/pkg/types/dashboardtypes/perses_dashboard_test.go+++ b/pkg/types/dashboardtypes/perses_dashboard_test.go@@ -8,6 +8,7 @@ import ("time""github.com/SigNoz/signoz/pkg/errors"+ "github.com/perses/spec/go/dashboard""github.com/stretchr/testify/assert""github.com/stretchr/testify/require""k8s.io/apimachinery/pkg/util/validation"@@ -25,19 +26,19 @@ func TestValidateBigExample(t *testing.T) {data, err := os.ReadFile("testdata/perses.json")require.NoError(t, err, "reading example file")_, err = unmarshalDashboard(data)- require.NoError(t, err, "expected valid dashboard")+ assert.NoError(t, err, "expected valid dashboard")}func TestValidateDashboardWithSections(t *testing.T) {data, err := os.ReadFile("testdata/perses_with_sections.json")require.NoError(t, err, "reading example file")_, err = unmarshalDashboard(data)- require.NoError(t, err, "expected valid dashboard")+ assert.NoError(t, err, "expected valid dashboard")}func TestInvalidateNotAJSON(t *testing.T) {_, err := unmarshalDashboard([]byte("not json"))- require.Error(t, err, "expected error for invalid JSON")+ assert.Error(t, err, "expected error for invalid JSON")}// TestUnmarshalErrorPreservesNestedMessage guards the wrap on dec.Decode in@@ -60,11 +61,11 @@ func TestUnmarshalErrorPreservesNestedMessage(t *testing.T) {_, err := unmarshalDashboard(data)require.Error(t, err)- require.Contains(t, err.Error(), "unknown panel plugin kind",+ assert.Contains(t, err.Error(), "unknown panel plugin kind","outer wrap should not smother the inner UnmarshalJSON message")- require.Contains(t, err.Error(), `"NonExistentPanel"`,+ assert.Contains(t, err.Error(), `"NonExistentPanel"`,"the offending value should still appear in the error")- require.Contains(t, err.Error(), "allowed values:",+ assert.Contains(t, err.Error(), "allowed values:","the allowed-values hint should still appear in the error")assert.True(t, errors.Ast(err, errors.TypeInvalidInput),@@ -77,7 +78,7 @@ func TestValidateEmptySpec(t *testing.T) {// no variables no panelsdata := []byte(`{}`)_, err := unmarshalDashboard(data)- require.NoError(t, err, "expected valid")+ assert.NoError(t, err, "expected valid")}func TestValidateOnlyVariables(t *testing.T) {@@ -109,7 +110,7 @@ func TestValidateOnlyVariables(t *testing.T) {"layouts": []}`)_, err := unmarshalDashboard(data)- require.NoError(t, err, "expected valid")+ assert.NoError(t, err, "expected valid")}func TestInvalidateDuplicateVariableNames(t *testing.T) {@@ -136,7 +137,7 @@ func TestInvalidateDuplicateVariableNames(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected error for duplicate variable name")- require.Contains(t, err.Error(), `duplicate variable name "env"`)+ assert.Contains(t, err.Error(), `duplicate variable name "env"`)}func TestInvalidateVariableNameWithInvalidChars(t *testing.T) {@@ -163,19 +164,19 @@ func TestInvalidateVariableNameWithInvalidChars(t *testing.T) {t.Run(name, func(t *testing.T) {_, err := unmarshalDashboard(listVarWithName(name))require.Error(t, err, "expected error for invalid variable name %q", name)- require.Contains(t, err.Error(), "is not a correct name")+ assert.Contains(t, err.Error(), "is not a correct name")})}for _, name := range []string{"service", "my_var", "MY_VAR", "MixedCase9", "with-hyphen", "with.dot"} {t.Run(name, func(t *testing.T) {_, err := unmarshalDashboard(listVarWithName(name))- require.NoError(t, err, "expected valid variable name %q", name)+ assert.NoError(t, err, "expected valid variable name %q", name)})}t.Run("digits only", func(t *testing.T) {_, err := unmarshalDashboard(listVarWithName("123"))require.Error(t, err)- require.Contains(t, err.Error(), "cannot contain only digits")+ assert.Contains(t, err.Error(), "cannot contain only digits")})}@@ -199,7 +200,7 @@ func TestInvalidatePanelKey(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected error for invalid panel key")- require.Contains(t, err.Error(), "is not a correct name")+ assert.Contains(t, err.Error(), "is not a correct name")}func TestInvalidateListVariableCrossFields(t *testing.T) {@@ -225,30 +226,30 @@ func TestInvalidateListVariableCrossFields(t *testing.T) {t.Run("customAllValue without allowAllValue", func(t *testing.T) {_, err := unmarshalDashboard(listVar(`"allowAllValue": false, "allowMultiple": false, "customAllValue": "*",`))require.Error(t, err)- require.Contains(t, err.Error(), "customAllValue cannot be set")+ assert.Contains(t, err.Error(), "customAllValue cannot be set")})t.Run("list defaultValue without allowMultiple", func(t *testing.T) {_, err := unmarshalDashboard(listVar(`"allowAllValue": false, "allowMultiple": false, "defaultValue": ["a", "b"],`))require.Error(t, err)- require.Contains(t, err.Error(), "allowMultiple")+ assert.Contains(t, err.Error(), "allowMultiple")})t.Run("single-element list default without allowMultiple", func(t *testing.T) {_, err := unmarshalDashboard(listVar(`"allowAllValue": false, "allowMultiple": false, "defaultValue": ["only"],`))require.Error(t, err)- require.Contains(t, err.Error(), "allowMultiple")+ assert.Contains(t, err.Error(), "allowMultiple")})t.Run("valid sort is accepted", func(t *testing.T) {_, err := unmarshalDashboard(listVar(`"sort": "alphabetical-asc",`))- require.NoError(t, err)+ assert.NoError(t, err)})t.Run("unknown sort is rejected", func(t *testing.T) {_, err := unmarshalDashboard(listVar(`"sort": "bogus",`))require.Error(t, err)- require.Contains(t, err.Error(), "unknown sort")+ assert.Contains(t, err.Error(), "unknown sort")})}@@ -275,7 +276,7 @@ func TestInvalidateEmptyVariableName(t *testing.T) {t.Run(name, func(t *testing.T) {_, err := unmarshalDashboard(data)require.Error(t, err, "expected error for empty variable name")- require.Contains(t, err.Error(), "name cannot be empty")+ assert.Contains(t, err.Error(), "name cannot be empty")})}}@@ -414,7 +415,7 @@ func TestInvalidateUnknownPluginKind(t *testing.T) {t.Run(tt.name, func(t *testing.T) {_, err := unmarshalDashboard([]byte(tt.data))require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)- require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)})}}@@ -435,7 +436,7 @@ func TestInvalidateOneInvalidPanel(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected error for invalid panel plugin kind")- require.Contains(t, err.Error(), "FakePanel", "error should mention FakePanel")+ assert.Contains(t, err.Error(), "FakePanel", "error should mention FakePanel")}func TestInvalidateLayoutPanelReferences(t *testing.T) {@@ -488,11 +489,11 @@ func TestInvalidateLayoutPanelReferences(t *testing.T) {t.Run(tt.name, func(t *testing.T) {_, err := unmarshalDashboard(tt.data)if tt.wantContain == "" {- require.NoError(t, err)+ assert.NoError(t, err)return}require.Error(t, err)- require.Contains(t, err.Error(), tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain)})}}@@ -570,7 +571,7 @@ func TestRejectUnknownFieldsInPluginSpec(t *testing.T) {t.Run(tt.name, func(t *testing.T) {_, err := unmarshalDashboard([]byte(tt.data))require.Error(t, err, "expected error for unknown field")- require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)})}}@@ -649,7 +650,7 @@ func TestInvalidateWrongFieldTypeInPluginSpec(t *testing.T) {_, err := unmarshalDashboard([]byte(tt.data))require.Error(t, err, "expected validation error")if tt.wantContain != "" {- require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)}})}@@ -874,7 +875,7 @@ func TestInvalidateBadPanelSpecValues(t *testing.T) {t.Run(tt.name, func(t *testing.T) {_, err := unmarshalDashboard([]byte(tt.data))require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)- require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)})}}@@ -907,7 +908,7 @@ func TestThresholdLabelOptional(t *testing.T) {spec := d.Panels["p1"].Spec.Plugin.Spec.(*TimeSeriesPanelSpec)require.Len(t, spec.Thresholds, 1)- require.Empty(t, spec.Thresholds[0].Label, "label should remain empty")+ assert.Empty(t, spec.Thresholds[0].Label, "label should remain empty")})}}@@ -924,7 +925,7 @@ func TestInvalidatePanelWithoutQueries(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected panel-without-queries to be rejected")- require.Contains(t, err.Error(), "panel must have one query")+ assert.Contains(t, err.Error(), "panel must have one query")}func TestInvalidatePanelWithEmptyQueriesArray(t *testing.T) {@@ -942,7 +943,7 @@ func TestInvalidatePanelWithEmptyQueriesArray(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected panel with explicit empty queries array to be rejected")- require.Contains(t, err.Error(), "panel must have one query")+ assert.Contains(t, err.Error(), "panel must have one query")}// Rendering multiple data sources in a single panel is supported via@@ -965,7 +966,7 @@ func TestInvalidatePanelWithMultipleDirectQueries(t *testing.T) {}`)_, err := unmarshalDashboard(data)require.Error(t, err, "expected panel with two top-level queries to be rejected")- require.Contains(t, err.Error(), "panel must have one query")+ assert.Contains(t, err.Error(), "panel must have one query")}func TestValidateRequiredFields(t *testing.T) {@@ -1053,7 +1054,7 @@ func TestValidateRequiredFields(t *testing.T) {t.Run(tt.name, func(t *testing.T) {_, err := unmarshalDashboard([]byte(tt.data))require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)- require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)+ assert.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)})}}@@ -1081,14 +1082,14 @@ func TestTimeSeriesPanelDefaults(t *testing.T) {require.IsType(t, &TimeSeriesPanelSpec{}, d.Panels["p1"].Spec.Plugin.Spec)spec := d.Panels["p1"].Spec.Plugin.Spec.(*TimeSeriesPanelSpec)- require.Equal(t, "2", spec.Formatting.DecimalPrecision.ValueOrDefault(), "expected DecimalPrecision default 2")- require.Equal(t, "spline", spec.ChartAppearance.LineInterpolation.ValueOrDefault(), "expected LineInterpolation default spline")- require.Equal(t, "solid", spec.ChartAppearance.LineStyle.ValueOrDefault(), "expected LineStyle default solid")- require.Equal(t, "none", spec.ChartAppearance.FillMode.ValueOrDefault(), "expected FillMode default none")- require.False(t, spec.ChartAppearance.SpanGaps.FillOnlyBelow, "expected SpanGaps.FillOnlyBelow default false")- require.Equal(t, "global_time", spec.Visualization.TimePreference.ValueOrDefault(), "expected TimePreference default global_time")- require.Equal(t, "bottom", spec.Legend.Position.ValueOrDefault(), "expected LegendPosition default bottom")- require.Equal(t, "list", spec.Legend.Mode.ValueOrDefault(), "expected LegendMode default list")+ assert.Equal(t, "2", spec.Formatting.DecimalPrecision.ValueOrDefault(), "expected DecimalPrecision default 2")+ assert.Equal(t, "spline", spec.ChartAppearance.LineInterpolation.ValueOrDefault(), "expected LineInterpolation default spline")+ assert.Equal(t, "solid", spec.ChartAppearance.LineStyle.ValueOrDefault(), "expected LineStyle default solid")+ assert.Equal(t, "none", spec.ChartAppearance.FillMode.ValueOrDefault(), "expected FillMode default none")+ assert.False(t, spec.ChartAppearance.SpanGaps.FillOnlyBelow, "expected SpanGaps.FillOnlyBelow default false")+ assert.Equal(t, "global_time", spec.Visualization.TimePreference.ValueOrDefault(), "expected TimePreference default global_time")+ assert.Equal(t, "bottom", spec.Legend.Position.ValueOrDefault(), "expected LegendPosition default bottom")+ assert.Equal(t, "list", spec.Legend.Mode.ValueOrDefault(), "expected LegendMode default list")// Re-marshal the full dashboard (what we'd store in DB / return in API response)// and verify the output contains the default values.@@ -1131,8 +1132,8 @@ func TestNumberPanelDefaults(t *testing.T) {spec := d.Panels["p1"].Spec.Plugin.Spec.(*NumberPanelSpec)require.Len(t, spec.Thresholds, 1, "expected 1 threshold")- require.Equal(t, "above", spec.Thresholds[0].Operator.ValueOrDefault(), "expected ComparisonOperator default above")- require.Equal(t, "text", spec.Thresholds[0].Format.ValueOrDefault(), "expected ThresholdFormat default text")+ assert.Equal(t, "above", spec.Thresholds[0].Operator.ValueOrDefault(), "expected ComparisonOperator default above")+ assert.Equal(t, "text", spec.Thresholds[0].Format.ValueOrDefault(), "expected ThresholdFormat default text")// Marshal back and verify defaults in JSON output.output, err := json.Marshal(d)@@ -1163,7 +1164,7 @@ func TestPersesFixtureStorageRoundTrip(t *testing.T) {require.NoError(t, err, "map → JSON (read-back shape)")var roundtripped DashboardSpec- require.NoError(t, json.Unmarshal(remarshaled, &roundtripped), "JSON → typed (the failure mode)")+ assert.NoError(t, json.Unmarshal(remarshaled, &roundtripped), "JSON → typed (the failure mode)")}// TestStorageRoundTrip simulates the future DB store/load cycle:@@ -1329,9 +1330,9 @@ func TestGenerateDashboardName(t *testing.T) {for _, tt := range tests {t.Run(tt.scenario, func(t *testing.T) {got := generateDashboardName(tt.input)- require.NotEmpty(t, got)- require.LessOrEqual(t, len(got), 63)- require.Empty(t, validation.IsDNS1123Label(got), "result must be a valid DNS-1123 label")+ assert.NotEmpty(t, got)+ assert.LessOrEqual(t, len(got), 63)+ assert.Empty(t, validation.IsDNS1123Label(got), "result must be a valid DNS-1123 label")if tt.wantPrefix == "" {assert.Len(t, got, dashboardNameSuffixLen, "expected the bare random suffix")@@ -1346,8 +1347,8 @@ func TestGenerateDashboardName(t *testing.T) {t.Run("prefix is truncated to leave room for the suffix", func(t *testing.T) {input := strings.Repeat("a", 100)got := generateDashboardName(input)- require.LessOrEqual(t, len(got), 63)- require.Empty(t, validation.IsDNS1123Label(got))+ assert.LessOrEqual(t, len(got), 63)+ assert.Empty(t, validation.IsDNS1123Label(got))assert.Equal(t, len(got), 63, "expected the result to be padded to the max DNS-1123 length")})@@ -1435,10 +1436,130 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {t.Run(tc.name, func(t *testing.T) {_, err := unmarshalDashboard(tc.data)if tc.wantErr {- require.Error(t, err)+ assert.Error(t, err)} else {- require.NoError(t, err)+ assert.NoError(t, err)}})}}++func TestValidateGridGeometry(t *testing.T) {+ tests := []struct {+ scenario string+ items []dashboard.GridItem+ expectErrContain string+ }{+ {+ scenario: "valid side-by-side items",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 6, Height: 6}, {X: 6, Y: 0, Width: 6, Height: 6}},+ expectErrContain: "",+ },+ {+ scenario: "valid full-width item",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 12, Height: 6}},+ expectErrContain: "",+ },+ {+ scenario: "stacked items do not overlap",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 6, Height: 6}, {X: 0, Y: 6, Width: 6, Height: 6}},+ expectErrContain: "",+ },+ {+ scenario: "zero width",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 0, Height: 6}},+ expectErrContain: "width must be at least 1",+ },+ {+ scenario: "zero height",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 6, Height: 0}},+ expectErrContain: "height must be at least 1",+ },+ {+ scenario: "negative x",+ items: []dashboard.GridItem{{X: -1, Y: 0, Width: 6, Height: 6}},+ expectErrContain: "x must not be negative",+ },+ {+ scenario: "negative y",+ items: []dashboard.GridItem{{X: 0, Y: -1, Width: 6, Height: 6}},+ expectErrContain: "y must not be negative",+ },+ {+ scenario: "width wider than grid",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 13, Height: 6}},+ expectErrContain: "width (13) exceeds grid width 12",+ },+ {+ scenario: "x at grid width",+ items: []dashboard.GridItem{{X: 12, Y: 0, Width: 1, Height: 6}},+ expectErrContain: "x (12) must be less than grid width 12",+ },+ {+ scenario: "x plus width overflows grid",+ items: []dashboard.GridItem{{X: 8, Y: 0, Width: 6, Height: 6}},+ expectErrContain: "x (8) + width (6) exceeds grid width 12",+ },+ {+ scenario: "overlapping items",+ items: []dashboard.GridItem{{X: 0, Y: 0, Width: 6, Height: 6}, {X: 3, Y: 3, Width: 6, Height: 6}},+ expectErrContain: "items[0] and items[1] overlap",+ },+ }+ for _, test := range tests {+ t.Run(test.scenario, func(t *testing.T) {+ err := validateGridLayoutGeometry(&dashboard.GridLayoutSpec{Items: test.items}, 0)+ if test.expectErrContain == "" {+ assert.NoError(t, err)+ return+ }+ require.Error(t, err)+ assert.Contains(t, err.Error(), test.expectErrContain)+ })+ }+}++func TestValidateGridItemLimit(t *testing.T) {+ err := validateGridLayoutGeometry(&dashboard.GridLayoutSpec{Items: make([]dashboard.GridItem, maxItemsPerGridLayout+1)}, 0)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "maximum is")+}++// Both panel refs are valid, so this errors only if geometry validation runs on+// the unmarshal path — it does, via DashboardSpec.Validate -> validateLayouts.+func TestInvalidateLayoutOverlapViaUnmarshal(t *testing.T) {+ data := []byte(`{+ "panels": {+ "p1": {"kind": "Panel", "spec": {"plugin": {"kind": "signoz/TablePanel", "spec": {}}, "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]}}}}]}},+ "p2": {"kind": "Panel", "spec": {"plugin": {"kind": "signoz/TablePanel", "spec": {}}, "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]}}}}]}}+ },+ "layouts": [{"kind": "Grid", "spec": {"items": [+ {"x": 0, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}},+ {"x": 3, "y": 3, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p2"}}+ ]}}]+ }`)+ _, err := unmarshalDashboard(data)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "overlap")+}++// The frontend keys each grid item by its panel id, so the same panel placed by+// two grid items crashes the section; the backend rejects it dashboard-wide. The+// two items are side by side so they clear the overlap check first.+func TestInvalidateDuplicatePanelReference(t *testing.T) {+ data := []byte(`{+ "panels": {+ "p1": {"kind": "Panel", "spec": {"plugin": {"kind": "signoz/TablePanel", "spec": {}}, "queries": [{"kind": "time_series", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "A", "signal": "logs", "aggregations": [{"expression": "count()"}]}}}}]}}+ },+ "layouts": [{"kind": "Grid", "spec": {"items": [+ {"x": 0, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}},+ {"x": 6, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}}+ ]}}]+ }`)+ _, err := unmarshalDashboard(data)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "already placed")+ // Both offending grid items are named.+ assert.Contains(t, err.Error(), "spec.layouts[0].spec.items[0].content")+ assert.Contains(t, err.Error(), "spec.layouts[0].spec.items[1].content")+}diff --git a/pkg/types/dashboardtypes/perses_replicas.go b/pkg/types/dashboardtypes/perses_replicas.goindex 9b2c737054..b0aad786c7 100644--- a/pkg/types/dashboardtypes/perses_replicas.go+++ b/pkg/types/dashboardtypes/perses_replicas.go@@ -322,6 +322,55 @@ func (l *Layout) UnmarshalJSON(data []byte) error {return nil}+const (+ gridColumnCount = 12+ maxItemsPerGridLayout = 100+)++// validateGridLayoutGeometry checks a single grid layout's item geometry (size,+// position, and intra-section overlap), which Perses does not. It reads only the+// layout's own items; layoutIndex is supplied by the caller (validateLayouts)+// solely to name the layout in error paths.+func validateGridLayoutGeometry(spec *dashboard.GridLayoutSpec, layoutIndex int) error {+ if len(spec.Items) > maxItemsPerGridLayout {+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items: has %d items; maximum is %d", layoutIndex, len(spec.Items), maxItemsPerGridLayout)+ }+ for i, item := range spec.Items {+ // The width/x bounds keep x+width small enough not to overflow.+ switch {+ case item.Width < 1:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: width must be at least 1, got %d", layoutIndex, i, item.Width)+ case item.Height < 1:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: height must be at least 1, got %d", layoutIndex, i, item.Height)+ case item.X < 0:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: x must not be negative, got %d", layoutIndex, i, item.X)+ case item.Y < 0:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: y must not be negative, got %d", layoutIndex, i, item.Y)+ case item.Width > gridColumnCount:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: width (%d) exceeds grid width %d", layoutIndex, i, item.Width, gridColumnCount)+ case item.X >= gridColumnCount:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: x (%d) must be less than grid width %d", layoutIndex, i, item.X, gridColumnCount)+ case item.X+item.Width > gridColumnCount:+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d]: x (%d) + width (%d) exceeds grid width %d", layoutIndex, i, item.X, item.Width, gridColumnCount)+ }+ // Could cap y/height but skipping for now: the grid grows vertically+ // without limit (frontend autoSize), so "too big" has no natural bound.+ }+ // Two items overlap iff their rectangles intersect on both axes.+ overlap := func(a, b dashboard.GridItem) bool {+ return a.X < b.X+b.Width && b.X < a.X+a.Width &&+ a.Y < b.Y+b.Height && b.Y < a.Y+a.Height+ }+ for i := 0; i < len(spec.Items); i++ {+ for j := i + 1; j < len(spec.Items); j++ {+ if overlap(spec.Items[i], spec.Items[j]) {+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.layouts[%d].spec.items[%d] and items[%d] overlap", layoutIndex, i, j)+ }+ }+ }+ return nil+}+func (Layout) JSONSchemaOneOf() []any {return []any{LayoutEnvelope[dashboard.GridLayoutSpec]{Kind: string(dashboard.KindGridLayout)},diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.pyindex 5616aaab7b..c0507367b8 100644--- a/tests/integration/tests/dashboard/03_v2_dashboard.py+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py@@ -173,6 +173,125 @@ def test_create_rejects_too_many_tags(assert response.json()["error"]["code"] == "dashboard_invalid_input"+def test_create_rejects_invalid_grid_layout(+ 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)++ def panel(name: str) -> dict:+ return {+ "kind": "Panel",+ "spec": {+ "display": {"name": name},+ "plugin": {"kind": "signoz/TablePanel", "spec": {}},+ "queries": [+ {+ "kind": "time_series",+ "spec": {+ "plugin": {+ "kind": "signoz/BuilderQuery",+ "spec": {+ "name": "A",+ "signal": "logs",+ "aggregations": [{"expression": "count()"}],+ },+ }+ },+ }+ ],+ },+ }++ # Two grid items reference valid, distinct panels but share cells, so the+ # overlap is the only violation.+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "rejects-overlap",+ "spec": {+ "display": {"name": "Rejects Overlap"},+ "panels": {"p1": panel("P1"), "p2": panel("P2")},+ "layouts": [+ {+ "kind": "Grid",+ "spec": {+ "items": [+ {"x": 0, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}},+ {"x": 3, "y": 3, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p2"}},+ ]+ },+ }+ ],+ },+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST+ assert response.json()["error"]["code"] == "dashboard_invalid_input"+ assert "overlap" in response.json()["error"]["message"]++ # One panel placed by two grid items (side by side, so they clear the overlap+ # check first). The frontend keys grid items by panel id, so this is rejected.+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "rejects-multiref",+ "spec": {+ "display": {"name": "Rejects Multiref"},+ "panels": {"p1": panel("P1")},+ "layouts": [+ {+ "kind": "Grid",+ "spec": {+ "items": [+ {"x": 0, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}},+ {"x": 6, "y": 0, "width": 6, "height": 6, "content": {"$ref": "#/spec/panels/p1"}},+ ]+ },+ }+ ],+ },+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST+ assert response.json()["error"]["code"] == "dashboard_invalid_input"+ assert "already placed" in response.json()["error"]["message"]++ # More grid items than allowed. The item-count check runs before the+ # panel-ref check, so content-less items suffice here.+ response = requests.post(+ signoz.self.host_configs["8080"].get(BASE_URL),+ json={+ "schemaVersion": "v6",+ "name": "rejects-too-many-items",+ "spec": {+ "display": {"name": "Rejects Too Many"},+ "layouts": [+ {+ "kind": "Grid",+ "spec": {"items": [{"x": 0, "y": 0, "width": 1, "height": 1} for _ in range(101)]},+ }+ ],+ },+ "tags": [],+ },+ headers={"Authorization": f"Bearer {token}"},+ timeout=5,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST+ assert response.json()["error"]["code"] == "dashboard_invalid_input"+ assert "maximum" in response.json()["error"]["message"]++@pytest.mark.parametrize("params",[