Repository navigation
fix(dashboard): don't 500 on inconsistent position_json - #43575
Conversation
`position_json` is only validated for JSON parseability, so a layout whose
`children` array names an id that is not a key in the layout is accepted by
`PUT /api/v1/dashboard/{id}` and stored. `Dashboard.tabs` then raises
`KeyError` walking it, and because `process_tab_diff` reads the layout from
the database rather than from the request body, every subsequent update to
that dashboard fails with a 500 -- including the update that would repair
the layout. The dashboard is left unwritable through the API.
The write that causes this returns 200, and the failure surfaces on the next
request, so nothing points at the request that did it.
Two changes:
- `process_tab_diff` only reads the stored layout when the payload actually
carries `position_json`. A tab can only be deleted by an update that
supplies a layout, so publishing or renaming a dashboard no longer walks
the tree at all.
- `Dashboard.tabs` tolerates a layout it cannot fully resolve instead of
raising: unresolvable or malformed nodes are skipped, untitled tabs get an
empty title, and a layout with no usable `ROOT_ID` yields no tabs. Every
degraded node is logged at WARNING, so the broken layout stays visible to
operators rather than being silently hidden.
Well-formed layouts are walked exactly as before.
No structural validation is added to `DashboardPutSchema`: payloads that are
accepted today would start returning 400, which is a breaking change for API
clients and needs its own discussion.
Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #818a8fActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
Pull request overview
Prevents dashboards from becoming permanently unwritable via the REST API when a stored position_json layout is structurally inconsistent (e.g., missing referenced node IDs), by making layout walking more defensive and avoiding reading the stored layout when no new layout is supplied.
Changes:
- Make
Dashboard.tabsresilient to missing/malformed nodes inposition_json(skip/degenerate nodes instead of raising). - Avoid computing tab diffs (and thus walking the stored layout) on dashboard updates that don’t include a
position_json. - Add unit tests covering both the new defensive behavior in
Dashboard.tabsand theprocess_tab_diffearly-return behavior.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
superset/models/dashboard.py |
Hardens Dashboard.tabs to avoid raising on inconsistent stored layout data and logs degradations. |
superset/commands/dashboard/update.py |
Skips tab-diff logic when the update payload does not include position_json, preventing 500s on unrelated updates. |
tests/unit_tests/models/dashboard_test.py |
Adds regression + defensive-behavior tests for Dashboard.tabs with malformed layouts and logging assertions. |
tests/unit_tests/commands/dashboard/update_test.py |
Adds tests ensuring process_tab_diff doesn’t read stored tabs without position_json, and still deactivates reports for deleted tabs. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| new_children: list[dict[str, Any]] = [] | ||
| # new children to overwrite parent's children | ||
| for child_id in node.get("children", []): | ||
| child = get_node(child_id) |
| def tabs(self) -> dict[str, Any]: # noqa: C901 | ||
| if not isinstance(self.position, dict): | ||
| logger.warning("Dashboard %s: layout is not a mapping", self.id) | ||
| return {} | ||
| if self.position == {}: |
| node["title"] = meta.get("text", "") | ||
| node_id = node.get("id") |
There was a problem hiding this comment.
Suggestion: The fallback only handles a missing text key; it does not handle an unusable value such as meta: {"text": null}. Such a TAB is documented and tested as needing an empty title, but this code stores None in both the tree and all_tabs, producing a non-string API payload despite TabsPayloadSchema declaring string titles. Normalize non-string title values to the empty string. [api mismatch]
Severity Level: Minor 🧹
- ⚠️ Tabs API can emit null or non-string titles.
- ⚠️ Clients expecting `TabsPayloadSchema` strings may reject responses.
- ⚠️ Tab labels become inconsistent for malformed metadata.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/models/dashboard.py
**Line:** 407:408
**Comment:**
*Api Mismatch: The fallback only handles a missing `text` key; it does not handle an unusable value such as `meta: {"text": null}`. Such a TAB is documented and tested as needing an empty title, but this code stores `None` in both the tree and `all_tabs`, producing a non-string API payload despite `TabsPayloadSchema` declaring string titles. Normalize non-string title values to the empty string.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix| node["value"] = node_id | ||
| all_tabs[node_id] = node["title"] |
There was a problem hiding this comment.
Suggestion: The new no-id protection only excludes None. A valid JSON TAB can have an object or array as its id; assigning that value as a dictionary key raises TypeError, so one malformed tab still takes down the entire tabs response. Restrict TAB identifiers to hashable string values or skip invalid identifiers. [type error]
Severity Level: Major ⚠️
- ❌ Invalid TAB identifiers abort tab registration.
- ❌ Dashboard updates may fail during stored-layout inspection.
- ⚠️ Tabs responses become unavailable for malformed layouts.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/models/dashboard.py
**Line:** 415:416
**Comment:**
*Type Error: The new no-id protection only excludes `None`. A valid JSON TAB can have an object or array as its `id`; assigning that value as a dictionary key raises `TypeError`, so one malformed tab still takes down the entire tabs response. Restrict TAB identifiers to hashable string values or skip invalid identifiers.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix| for child_id in node.get("children", []): | ||
| child = get_node(child_id) |
There was a problem hiding this comment.
Suggestion: The defensive walk still assumes children is iterable. A valid JSON layout can contain children: null or a scalar, causing TypeError at this loop before the malformed-child guard runs and allowing the dashboard tabs endpoint to return 500. Only iterate when children is a list (or otherwise normalize invalid values to an empty list). [type error]
Severity Level: Major ⚠️
- ❌ Malformed layouts can abort dashboard tab traversal.
- ❌ Dashboard updates can fail in `process_tab_diff`.
- ⚠️ Tabs GET returns 400 instead of usable partial results.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/models/dashboard.py
**Line:** 438:439
**Comment:**
*Type Error: The defensive walk still assumes `children` is iterable. A valid JSON layout can contain `children: null` or a scalar, causing `TypeError` at this loop before the malformed-child guard runs and allowing the dashboard tabs endpoint to return 500. Only iterate when `children` is a list (or otherwise normalize invalid values to an empty list).
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix`Dashboard.tabs` walked a layout defensively but still assumed the type of
the values it read, so three layouts that `position_json` accepts today
still raised out of the walk:
- `children` set to `null` or a scalar, or holding an entry that is not an
id, raised `TypeError` on iteration or on the node lookup
- an `id` that is an object or an array raised `TypeError: unhashable type`
when used as an `all_tabs` key
- a `meta.text` that is present but not a string produced a `None` title
with no warning, where the API expects a string
These reach the walk the same way as the ids that do not resolve: they are
valid JSON, so they are stored by `PUT /api/v1/dashboard/{id}`, and the
dashboard is then unwritable through the API.
Each value is now checked for the type it is used as, and every node that
is skipped or degraded is logged at WARNING, as with the other cases.
Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #314eceActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
| if node_type == "TABS": | ||
| # if TABS add create a new list and append children to it | ||
| # new_children.append(child) | ||
| children.append(child) |
There was a problem hiding this comment.
The non-string-ID guard still puts the node into tab_tree before register_tab rejects it. A stored TAB with id: [] therefore produces an entry with no string value, so /tabs violates TabSchema and the tab picker cannot select it. Should invalid tabs be excluded from the tree as well?
There was a problem hiding this comment.
Yes — they should be, and they now are. Fixed in c8d8bbb.
You're right about the ordering: the TABS parent appends the child before register_tab gets a chance to reject it, so a TAB with id: [] ended up in tab_tree with no value, while being correctly excluded from all_tabs. Reproduced against the previous head:
all_tabs = {'TAB-2': 'Good'}
tree entry: id=[] value=<missing> title='Bad'
tree entry: id='TAB-2' value='TAB-2' title='Good'
Such a tab is unusable either way — it cannot key all_tabs, and it cannot carry a value for the picker — so it is now skipped where the parent appends it, with the same WARNING as the other degraded nodes. tab_tree and all_tabs stay consistent, and every tree entry has a value again.
test_tabs_skips_tab_nodes_without_an_id now also asserts the unusable tabs are absent from the tree and that each remaining entry carries a value. It fails against the previous commit.
Generated by Claude Code
A TAB whose `id` is not a string was excluded from `all_tabs` but still appended to `tab_tree` by its TABS parent, because the parent appends the child before the child is validated. The resulting entry carries no `value`, so it does not satisfy `TabSchema` and the tab picker cannot select it. Such a tab is unusable either way, so it is now dropped from the tree as well, keeping `tab_tree` and `all_tabs` consistent. As with the other degraded nodes, the skip is logged at WARNING. Co-Authored-By: Claude Opus 5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #43575 +/- ##
==========================================
+ Coverage 79.08% 79.32% +0.24%
==========================================
Files 2877 2885 +8
Lines 165451 167571 +2120
Branches 38235 38605 +370
==========================================
+ Hits 130849 132931 +2082
- Misses 32121 32140 +19
- Partials 2481 2500 +19
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Codecov flagged the layout walk as partly uncovered by the new unit tests. Two gaps, both real paths rather than dead code: - A TAB stored directly under GRID or ROOT never passes the check in the TABS branch, so it is rejected when its id is read instead. Only a TABS node contributes children to the tree, which is why that path exists. - A node that carries children but is not one of the four handled types is walked through without contributing to the tree, and a tab can hold more than one child. The happy-path layout now carries a row and a chart beside the nested tab bar, which is closer to a real dashboard, and a new test covers the tab reached without a tab bar. No production code changed. Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #8344b1Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
| continue | ||
| # if TABS add create a new list and append children to it | ||
| # new_children.append(child) | ||
| children.append(child) |
There was a problem hiding this comment.
An untyped child of a TABS node is appended here before the queued node is rejected at build_tab_tree's type guard. The tabs response then contains a tree entry without a selectable value or title, even though malformed layouts are meant to degrade safely. Should the child be validated before it is added to tab_tree?
There was a problem hiding this comment.
Confirmed, and it is the same defect as the id one — my earlier guard was too narrow, since it only rejected a child that was already typed TAB. An untyped child slipped past it, got appended, and was then rejected at build_tab_tree's type guard, leaving exactly the entry you describe:
tree: id='TAB-1' value=<missing> title=<missing>
tree: id='TAB-2' value='TAB-2' title='Good'
Fixed in 46e86b4: a child is added to the tree only if it will actually register as a tab, i.e. it is a TAB with a string id. Everything else is kept out of the tree but still walked, so tabs stored below it are not lost. A ROW child of a TABS node is covered by the same check.
| @property | ||
| def tabs(self) -> dict[str, Any]: | ||
| def tabs(self) -> dict[str, Any]: # noqa: C901 | ||
| if not isinstance(self.position, dict): |
There was a problem hiding this comment.
Returning {} for a JSON-valid non-mapping layout turns the former failure into a response without all_tabs or tab_tree. The alert report modal calls tabTree.map, so opening its tab picker now fails instead of receiving an empty option list. Should malformed-layout exits return the normal empty payload shape (all_tabs: {}, tab_tree: [])?
There was a problem hiding this comment.
You are right, and this one is worse than a shape inconsistency — it is a regression I introduced. Before this PR those layouts raised, so the request failed and the promise rejected. Returning {} makes the request succeed with a payload that has neither key, and AlertReportModal.tsx:1104 destructures tab_tree and calls .map on it with no guard, so the picker throws instead of showing an empty list. (SaveModal.tsx:270 checks Array.isArray first, so it was unaffected.)
Every exit now returns {"all_tabs": {}, "tab_tree": []}.
One thing worth flagging: I also changed the empty-layout exit, which returned a bare {} on master too. It is outside what you asked about, but it reaches AlertReportModal through the same path and would fail the same way, and leaving one exit returning a different shape from the others seemed worse than fixing it. Happy to split that back out if you would rather keep this PR strictly to the paths it introduced.
Tests cover both: the tree no longer accepts a node without value/title, and each exit is asserted against the full payload shape. All four new assertions fail against the previous commit.
…of the tree
Two problems with how the layout walk degrades, both reported in review.
A TABS node contributes its children to `tab_tree` before those children are
themselves validated, so a child that never registers as a tab -- one with no
`type`, or one whose `id` cannot key `all_tabs` -- was left in the tree with
no `value` and no `title`. Such an entry does not satisfy `TabSchema` and
cannot be selected. Only a node that registers as a tab is added to the tree
now; it is still walked, so tabs stored below it are not lost.
The malformed-layout exits returned a bare `{}`, which reaches the API as a
payload carrying neither `all_tabs` nor `tab_tree`. `AlertReportModal` reads
`tab_tree` and calls `.map` on it without a guard, so its tab picker would
fail rather than show an empty list. Every exit returns the normal empty
payload shape instead. This also covers the empty-layout exit, which returned
a bare `{}` before this change as well.
Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #b15ad3Actionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
The commented-out `new_children.append(child)` and the line above it describe the opposite of what the code does: the child is appended to `children`. The lines predate this branch, but it moved them into the guarded block, where they sit directly under a comment explaining the actual behaviour and contradict it. Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #32c244Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
| tabs.assert_not_called() | ||
|
|
||
|
|
||
| def test_process_tab_diff_deactivates_reports_on_deleted_tabs( |
There was a problem hiding this comment.
The new coverage only mocks tabs and calls process_tab_diff directly, so it does not exercise the reported persisted-corruption → repair-request path. A JSON-parseable layout with a dangling child can still be stored before this change; could we add the two-step API regression that stores it, then updates it with a corrected position_json and asserts the repair returns 200 and persists?
| self.id, | ||
| child_id, | ||
| ) | ||
| queue.append((child, new_children)) |
There was a problem hiding this comment.
The defensive walk still has no visited-node guard. A JSON-valid stored layout with ROOT_ID.children = ["ROOT_ID"] re-enqueues the root forever here, so /tabs hangs and an update that supplies a corrective layout also blocks while process_tab_diff reads the stored tabs. Could we detect already-visited node IDs (or otherwise reject cycles) before enqueueing?
|
Nice work chasing down all these edge cases, @tien238lnd, but @sadpandajoe's cycle question from a couple days ago is still open: a self-referencing layout like Want to add a guard for it? Their other ask would be an API-level test that stores a broken layout via |
The walk is a queue, so a layout that lists a node among its own descendants re-enqueues it on every pass and never finishes. A dashboard stored with such a layout could not be read or written again, since an update reads the stored tabs to find the deleted ones — the same class of unwritable dashboard this branch already addresses, reached by a hang rather than by an error. The walk keeps the node ids it has reached, seeded with ROOT_ID, and skips a child it has reached before instead of enqueueing it. The check also covers a node reached from two parents, which is not a cycle but is not a tree either: the walk writes title, value and children onto every node it visits, so a second visit was overwriting the first. Such a node keeps the place it is reached from first. Co-Authored-By: Claude Opus 5 <[email protected]>
The tab-diff coverage mocks the tabs property, so it does not exercise the path from the report: a layout that is JSON-parseable reaches the metadata database, and every later update fails while reading it back. The new test stores a dashboard row with such a layout, PUTs a corrected one, and asserts the response is 200 and the correction persists, with nothing mocked on that path. It is parametrized over a tab bar pointing at a tab the layout does not hold, which raised before this branch, and over a self-referencing layout, which hung. Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #cf7bccActionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
Since the tabs property answers with both keys for every layout, including one it could not walk, the falsy check on its result can no longer be true and the early return is dead. An empty all_tabs needs no guard of its own: the comprehension below already diffs nothing against the new layout. Co-Authored-By: Claude Opus 5 <[email protected]>
Code Review Agent Run #353dfeActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
SUMMARY
position_jsonis validated for JSON parseability only, so a layout whosechildrenarray names an id that is not a key in that layout is accepted byPUT /api/v1/dashboard/{id}and stored.Dashboard.tabsthen raisesKeyErrorwalking it, and sinceUpdateDashboardCommand.process_tab_diffreads the layout from the database rather than from the request body, every subsequent update to that dashboard returns 500 — including the update that would repair the layout. The dashboard is left unwritable through the API, recoverable only by export → edit YAML → import with overwrite.The write that causes it returns 200 and the failure surfaces on the next request, so nothing points back at the request responsible.
Two changes:
superset/commands/dashboard/update.py—find_deleted_tabscomputedself._model.tabsbefore checking whether the payload carried aposition_json, so everyPUTwalked the whole stored layout,{"published": true}included. It now returns early when there is no incoming layout. A tab can only be deleted by an update that supplies one, so behaviour is unchanged for every input that could produce a non-empty result.superset/models/dashboard.py—Dashboard.tabsno longer raises on stored layout data:get_nodeuses.get(); achildrenentry that is missing or is not an object is skipped rather than dereferenced. Skipping is required, not just tolerating: aNonepushed onto the queue would fail onnode.get("children", [])in the next iteration withAttributeError, which is still a 500.typeis skipped. A node whosetypeis present but not one ofROOT/GRID/TABS/TABis walked through without contributing to the tree, exactly as before — that is how ordinary rows and charts have always been handled, so it stays silent.TABwhose title cannot be read gets an empty title.metais checked withisinstance, not just.get("meta", {}): ametathat is present but is a string or a list would otherwise raiseAttributeError, which is not caught insuperset/dashboards/api.py, turning a 400 into a 500.ROOT_ID, or one that parses to something other than an object (null,[]), returns{}.The patch does not hide the problem: every node that is skipped or degraded is logged at WARNING with the dashboard id and the node id, so a broken layout stays visible to operators instead of quietly producing fewer tabs. Well-formed layouts produce identical output.
No structural validation was added to
DashboardPutSchema, on purpose. It would turn payloads that are accepted today into 400s — a breaking change for any client scripting dashboards — and doing it properly means formally specifying theposition_jsoninvariants, which Superset has never specified. That belongs in its own discussion.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not applicable — backend-only change, no UI surface.
TESTING INSTRUCTIONS
pytest tests/unit_tests/models/dashboard_test.py \ tests/unit_tests/commands/dashboard/update_test.pyThe pre-existing integration coverage for the function reworked in
update.pyshould also still pass:Cases covered by the new tests:
tests/unit_tests/models/dashboard_test.py—Dashboard.tabsall_tabsmapping andtab_treeshape as before (the regression guard)childrenentry naming an id that is not in the layout is skipped, and a WARNING is loggedchildrenentry resolving to something that is not an object is skipped, and a WARNING is loggedtypeis skipped, and a WARNING is loggedTABwith nometa, an emptymeta, or a non-objectmetagets an empty title, and a WARNING is loggedTABwith noidis left out ofall_tabs, and a WARNING is loggedROOT_ID, an empty layout, and a layout that is not a mapping all return{}tests/unit_tests/commands/dashboard/update_test.py—process_tab_diffposition_jsondoes not readself._model.tabsat allVerified as real regression guards: reverting only the two source files fails 8 of the 17 new tests, and downgrading the
logger.warningcalls todebugfails 7 of them.Manual check, against an affected dashboard:
GET /api/v1/dashboard/{id}/tabsreturns 200 with the tabs that resolve instead of 500, andPUT /api/v1/dashboard/{id}with a correctedposition_jsonnow succeeds and repairs the dashboard.ADDITIONAL INFORMATION
Not a breaking change: no request that succeeds today starts failing, and no response shape changes for a well-formed layout.