Repository navigation
Conversation
Canvas is a new entity, separate from dashboards, that places widgets
on a canvas. Widgets are their own entities; a canvas definition only
references them by id and holds their placement and filter scopes.
- Model: `canvases` (integer id + uuid, audit columns, title,
description, definition, definition_version, revision) with
editors/viewers, and a `canvas_ops` log of applied operations. The id
+ uuid shape keeps entity versioning possible later.
- Definition: a root grid (24 columns) and a flat node map
`{widget, layout, children?}` with server-generated node ids.
Containers are widget types that declare nesting, a child grid or
child layout model, size limits and filter roles through
`CanvasLayoutRules` in superset-core; a `WidgetResolver` reports
widget types and which widgets the user may place. Unresolved widgets
stay as placeholders.
- Operations: add, remove, move, place and set_filter_scope, applied
atomically. A write based on an older revision is merged unless it
overlaps a later change (409 otherwise).
- Filter scope: a filter drives the filterable widgets under its
nearest scoping container, or the whole canvas at the root, with
per-filter overrides.
- API under /api/v1/canvas/: CRUD with editors/viewers sharing, GET and
PATCH /<id>/definition (with resolved filter scopes, placements and
widget types), GET /<id>/definition/changes, and GET /schema for the
published contract. Writes need editorship; admins, editors and
viewers can read.
- CANVAS feature flag (off by default) gates the API.
Adds read-only /canvas/list/ and /canvas/<id>/ pages and a menu entry, gated on the CANVAS feature flag. The view page renders the server's resolved placements as a CSS grid, reloads on entity.changed (polling /definition/changes when websockets are off), opens the global chat as a panel and publishes the active canvas. Widget renderers register through the new canvas namespace in @apache-superset/core; unregistered or unresolved widgets render a placeholder. The definition response gains gridColumns, the column count of each grid container.
An add operation may carry an id, a canonical lowercase UUID not already on the canvas; otherwise the server generates one as before. Later operations in the same request can then reference the new node, so a container and its children are built in one atomic request, a UI can draw a node before the response, and a retried add fails instead of duplicating the node.
…nges Stored definitions are upgraded to the current schema version on load through a chain of per-version upgrades; the next write stores the upgraded form and restarts the operation log, so clients on an older base reload. A definition newer than the server supports is refused with a 422 that says Superset needs upgrading. Widget rules (nesting, sizes, child layouts, filter roles) are enforced only on the nodes a write touches. Nodes saved under rules that have since tightened keep their stored placement and no longer block edits elsewhere on the canvas.
The definition gains a settings section: automatic refresh (interval, stagger, exempt nodes), shared colors (scheme and fixed label colors) and display (data timestamps). A set_settings operation replaces one section or resets it. Each section is its own concurrency group, so concurrent changes to different sections, or to settings and layout, merge. Removing a node drops it from the refresh exemptions.
Widget types can declare themselves cross-filter sources or customizations (e.g. dynamic group-by). Each kind gets its own scope overrides under interactions and resolves like filters: auto drives the filterable widgets under the nearest scope-bounding container, never the node itself, with global and custom overrides. The definition response returns crossFilterScopes and customizationScopes alongside filterScopes; cross-filter scopes are empty while settings.crossFilters is off. set_filter_scope becomes set_scope with a kind. Each kind is its own concurrency group, and removing a node prunes it from every kind.
Canvases gain the row metadata dashboards have: a unique slug used in the canvas URL (never all digits, and not "list"), a theme, custom CSS, certification and external-management fields. Create and update reject a slug already taken by any canvas and a theme that doesn't exist. The canvas page is served by id or slug.
Widget renderers receive cross-filter and customization values for the nodes whose scope includes them, setters for each kind (cross-filters are ignored while turned off), the canvas colors, whether to show data timestamps, and a refresh key the page bumps on every automatic refresh, spread over the configured stagger and skipping exempt nodes. The canvas page resolves /canvas/<slug>/ as well as ids, applies the canvas theme and custom CSS, and shows certification on the page and in the list.
The caps on node count, nesting depth, operations per request, widget id length and the upper bounds on grid and settings values were never calibrated against real dashboards, so they're removed. Only structural minimums remain. Reading order is computed iteratively so deep trees can't exhaust the recursion limit.
Placement, scopes, filter values and refresh exemptions are all keyed by node, so two nodes can reference the same widget without sharing any canvas state.
Brings the widget framework prototype (superset_core.widgets, the widget registry and built-ins, the control schema API and widget MCP tools) onto the canvas branch and rebuilds the canvas on it: - Placements hold a persisted instance by UUID or an inline instance (widget, schemaVersion, props); placement ids are readable slugs. - Widgets declare schema versions, props migrators, WidgetBehavior and WidgetUi, replacing the canvas layout rules registry; core adds tabs, tab and group containers. - Inline props are validated where written, migrated on read, and replaced with the new set_props op. - get_canvas and apply_canvas_ops MCP tools; the canvas and widget APIs and MCP tools are all gated by CANVAS. - Definition versions are checked, not upgraded on read; format changes ship as Alembic migrations. - Built-in renderers for the core containers and markdown.
- add and set_props accept a schemaVersion and migrate older props. - filter.select is filterable, so filters whose scope reaches it cascade. - Definition routes and the canvas MCP tools take a canvas id or UUID. - Request and operation errors carry JSON-pointer paths; add applies the widget's default size; MCP tools report definition-version errors. - Canvas and widget MCP tools are gated by CANVAS and declare typed outputs; built-in renderers for the core containers and markdown.
- Placements reference a persisted widget as widgetId and hold an inline instance as widgetType; the resolver is WidgetResolver and the class registry is the widget types. - The canvas and widget APIs are always registered and answer 404 while CANVAS is off, so their permissions exist before the flag is turned on. - The canvas page relies on realtime updates; the polling fallback is gone.
# Conflicts: # superset/mcp_service/app.py
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
|
|
||
| // The refetch after a 409 has landed: reapply the reverted gesture if | ||
| // everything it names is still there, otherwise say it was undone. | ||
| useEffect(() => { |
There was a problem hiding this comment.
The queued retry after a 409 isn't invalidated by a newer gesture, so a drag made during the refetch round trip gets reverted when the replay lands — silently, since the write itself succeeded.
The era/generation guard used elsewhere in this file would cover it.
There was a problem hiding this comment.
Fixed. Gestures made while the post-409 refetch is in flight are queued and replayed after the retry, so the newest drop wins. There's a test for it.
| ) | ||
| _fit_rows(entries, MAX_RESPONSE_BYTES) | ||
| result["widgets"] = entries | ||
| result.update( |
There was a problem hiding this comment.
The unread list is merged in after _fit_rows has trimmed to 40 KB, and nothing bounds it. At roughly 205 bytes an entry, a canvas with enough unread placements pushes the response past the 50 KB guard and the whole call fails rather than returning trimmed data.
There was a problem hiding this comment.
Fixed: unread is capped at 20, and the row budget now accounts for skipped and unread, so the response stays under the guard.
| fetchedColumns.current, | ||
| ); | ||
| return { | ||
| revision: Math.max(fetched.current, confirmed.current ?? 0) + 1, |
There was a problem hiding this comment.
The optimistic applied.revision leaves out adopted, so a drag made right after an undo or redo is dropped when the refetch lands and the widget snaps back for a round trip.
There was a problem hiding this comment.
Right, the optimistic revision and the write base now share one helper that includes adopted. There's a test for a drop right after an undo.
| def canvas_id(self) -> int: | ||
| return self.canvas.id | ||
|
|
||
| def resolver(self) -> PendingWidgetResolver: |
There was a problem hiding this comment.
resolver() re-parses the whole canvas definition — and can query placeable — and it's called four times per draft write. That's on the drag path, so it's paid on every gesture.
There was a problem hiding this comment.
The saved-canvas parse is now cached per request, and each write builds the resolver once before and once after. placeable still runs on both sides, because the draft's widgets differ.
| expect(result.current.removed.has('kpi')).toBe(false); | ||
| }); | ||
|
|
||
| test('a removal undone before a fetch saw it gone shows the widget again', async () => { |
There was a problem hiding this comment.
Two of the fixes from the last round aren't pinned by a test:
- the
removed-set reset on a surface change (this test covers the revision-based clearing, not the reset) - the drop-settling precedence — this passes whether settled or requested placements win, so it wouldn't catch a regression to the old behaviour
There was a problem hiding this comment.
Added both. The precedence test drops onto the lower half of a widget so the drop is the one pushed, and it fails if requested placements win.
…anvas data size - keep a narrowed-grid child's size when it is auto-placed - queue gestures made during a 409 refetch so the newest drop wins - include the adopted revision in the optimistic and base revision - cap unread widgets in get_canvas_data and budget rows against the lists - parse the saved canvas once per draft write
|
| for key, value in (("skipped", skipped), ("unread", unread[:MAX_UNREAD])) | ||
| if value | ||
| } | ||
| # The lists share the budget with the rows: trimmed rows alone could still | ||
| # leave the response past the size guard. | ||
| _fit_rows(entries, MAX_RESPONSE_BYTES - len(json.dumps(listed))) |
There was a problem hiding this comment.
unread[:20] covers the case from last round: twenty entries fit between the 40 KB row budget and the 50 KB guard, even when the rows fill the whole budget. skipped is still unbounded, and _fit_rows only shortens rows, then returns once there is nothing left to cut. A skipped list on the order of a thousand ids is already past 40 KB, so the budget goes to zero or below, the rows are wiped, and the response still fails the guard. Subtracting len(json.dumps(listed)) does not shrink that list.
The new test does not pin this. It builds no rows and no skipped list, and twenty unread entries are a few KB, so len(json.dumps(result)) < MAX_RESPONSE_BYTES passes with the subtraction deleted. It needs a case where the rows already fill the budget and a list pushes the serialized response past the guard.
unread past 20 is dropped with no signal. Trimmed rows set truncated; here the caller cannot tell the canvas has more of these widgets.
|
|
||
| assert result["nodes"]["a"]["layout"] == layout | ||
| assert placed["placements"]["a"]["rowSpan"] == 3 | ||
| assert placed["placements"]["a"]["colSpan"] <= 12 |
There was a problem hiding this comment.
rowSpan == 3 catches the old render-via-{} result. colSpan <= 12 also passes for a width of 1; this placement should come back with colSpan == 12.
These assertions read render_context. The overflowing child's stored layout is left as-is (kept), and resolve_grid does not write a settled row back onto an auto-placed sibling. If validation.py goes back to appending {}, render stays the same and an explicitly placed sibling settles one row down from a height of 1 rather than 3. That shows up on result["nodes"][<sibling>]["layout"]["row"].
# Conflicts: # UPDATING.md # superset/translations/messages.pot # tests/integration_tests/deletion_retention/purge_performance_tests.py # tests/integration_tests/versioning/conftest.py
| } | ||
| # The lists share the budget with the rows: trimmed rows alone could still | ||
| # leave the response past the size guard. | ||
| _fit_rows(entries, MAX_RESPONSE_BYTES - len(json.dumps(listed))) |
There was a problem hiding this comment.
Still goes over. skipped isn't capped, and _fit_rows only trims rows — each entry's columns, title and error stay. I measured 136,091 bytes with zero rows left, against a 50,000 limit, so the call still fails instead of coming back trimmed.
Capping skipped like unread, and letting _fit_rows drop an entry once its rows are gone, should cover it.
| // Still saving: the follow-up sets the flag again straight away. | ||
| send(next); | ||
| } else { | ||
| setSaving(false); |
There was a problem hiding this comment.
A gesture waiting for the retry isn't in queued yet, so this sets saving false while a change is still unsent. Save and Publish stay enabled and then drop it.
| }); | ||
| queued.current.clear(); | ||
| if (entries.size === 0) return; | ||
| retrying.current = fits; |
There was a problem hiding this comment.
Only re-fires on revision. If the refetch after a 409 comes back without moving it, the gesture never gets replayed and the hook stays stuck.
I pinned revision to see it rather than making a real reload fail, so I'm sure about the stuck state, less sure how easily you'd hit it.
| // Changed elsewhere, such as by an agent in the same draft: the | ||
| // gesture is tried once more on the refetched draft. | ||
| if (isRetry) { | ||
| setError(UNDONE()); |
There was a problem hiding this comment.
The next write clears the error, so this message disappears as soon as anything else is dragged — you're told your change was undone and then it's gone.
| if on_grid and isinstance(layout, dict): | ||
| # Checked here, not only on the layout a write names: a write that | ||
| # only adds to a container grows it without naming its layout. | ||
| if rows > MAX_GRID_ROW_SPAN: |
There was a problem hiding this comment.
Falls out of the fix above: now the child keeps its rowSpan, _fit can grow a narrowed container past MAX_GRID_ROW_SPAN, and then this refuses every write, including the one that would undo the narrowing. Checked both ways.
Clamping instead of rejecting would avoid the dead end.
rusackas
left a comment
There was a problem hiding this comment.
Thanks @msyavuz, this has come a long way over all these rounds. A few small things inline from my pass.
The new threads from @alexandrusoare today and @SBIN2010 yesterday are still open too, so I'll hold off on stamping for now.
| @@ -530,6 +553,7 @@ def log( # pylint: disable=too-many-arguments,too-many-locals | |||
| json=json_string, | |||
| dashboard_id=dashboard_id or record.get("dashboard_id"), | |||
| slice_id=slice_id or record.get("slice_id"), | |||
| canvas_id=canvas_id or record.get("canvas_id"), | |||
There was a problem hiding this comment.
I think the per-record id needs to win here, since the batch-level one comes from the beacon's first event. As written, a batch that spans a canvas switch still gets labeled with the first canvas, which is the case the comment in useCanvasLogger.ts says the body field covers.
| canvas_id=canvas_id or record.get("canvas_id"), | |
| canvas_id=record.get("canvas_id") or canvas_id, |
| for adhoc in binding.get("filters") or []: | ||
| if adhoc.get("expressionType") == "SQL": | ||
| if adhoc.get("sqlExpression"): | ||
| where.append(f"({adhoc['sqlExpression']})") |
There was a problem hiding this comment.
Not sure if bindings ever carry a chart's adhoc filters as-is, but if they do, a clause: "HAVING" filter lands in extras.where here and the query will fail on the aggregate. Should those go to extras.having instead?
| canvas_id: int | str, draft_token: str | None | ||
| ) -> _PreviewSource | dict[str, Any]: | ||
| """Resolve the preview once, using the draft's canvas when a token is given.""" | ||
| if draft_token: |
There was a problem hiding this comment.
With a draft_token, canvas_id is ignored entirely, so a token from a different canvas previews that one instead of erroring. placement_data.py refuses the mismatch on the REST side. Maybe this (and _load in get_canvas_data.py) should do the same?
A tooltipTemplate chrome control and an inline {"$template": ...} value
compile to the formatter function a JSON option cannot carry, with
formatNumber, formatDate and default helpers. Output is drawn as rich
text, never HTML.
- per-record canvas_id wins in the DB event logger - HAVING adhoc filters go to extras.having - a draft token only reads or previews the canvas it belongs to - get_canvas_data caps skipped/unread at 20 with totals and drops entries that still do not fit - a container grown past MAX_GRID_ROW_SPAN is clamped, not refused - useCanvasLayout keeps saving through a 409 retry, replays after a refetch that leaves the revision alone, and keeps the undone notice
Filter widgets are titled by name in the same row as every other widget. Change marks and the edit handles live on the grid surface as a compact top-right cluster over the title row, so widgets reserve no room for them and titles no longer shift. The New/Edited outline is gone; the badge alone carries the change.
A template under any other key compiled to a function too, and some of those, such as the data view's optionToContent, return HTML that ECharts injects as markup. Only formatter and valueFormatter take one; their output is drawn as text.
- a draft token must name its own canvas, compared on the draft itself so the preview still resolves the canvas once - Handlebars compiles lazily: parse up front so a bad template throws when the option is built - a reload that returns nothing still settles a 409 retry - grid tests follow the top-right handle cluster
|
The definition hook's reload returns a promise; a reload that returns nothing leaves the retry to the next fetched revision, as the layout hook's tests expect. The body test now hands in a promise-returning reload, as the real one is.
# Conflicts: # UPDATING.md
…ound The canvases migration chain follows master's teams installations migration. The grid tests that guard against row-by-row placement allow ten seconds: a loaded CI runner took just over one.
master added tests/unit_tests/integrations/teams/config_test.py; with no __init__.py in either directory pytest imports both as config_test and refuses to collect the second.
SUMMARY
Implements the Canvas SIP (#44989), the companion to SIP-231 (#44875): a new
Canvasentity whose definition places widgets, edited through atomic, validated operations by people and agents alike. Built on SIP-231'swidgetstable and API (merged from thecanvasbranch), all behind theCANVASflag.revenue-trend) on a 24-column grid. Structural widgets (group,tabs,tab,filter.bar,markdown) live on the placement; every other widget is awidgetsrow the placement references bywidgetId.X-Canvas-Draft) takeadd,set_props,rename,place,move,swap,remove,set_scope,set_settings, with undo/redo; a new content widget is held in the draft and saved with the canvas on commit, which is rejected (409) if the canvas or a touched widget changed since. Every commit is a version that can be previewed and restored.SECURITY.md).POST .../placement/<id>/dataruns the query a widget's binding describes, as the caller.create_canvas_draft,apply_canvas_draft_ops,commit_canvas_draft,preview_widget,get_canvas_data, versionedlist_widget_types/get_widget_control_schema, ...).MCP_CANVAS_AGENT_PUBLISH = Falseleaves publishing to people.canvas_id(newlogs.canvas_idcolumn)./canvas/<id or slug>/renders the canvas and its draft, with drag/resize editing, Publish/Discard and version history;/canvas/redirects to the list.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A: new page behind a flag that is off by default.
TESTING INSTRUCTIONS
Test environment flags: FEATURE_CANVAS=true
FEATURE_FLAGS = {"CANVAS": True}, runsuperset db upgradeandsuperset init.POST /api/v1/canvas/with a title, thenPOST .../<id>/draftandPATCH /api/v1/canvas/draft(returnedtokenasX-Canvas-Draft) with{"revision": <draft revision>, "ops": [{"op": "add", "widgetType": "markdown", "props": {"content": "Hello"}}]}.POST /api/v1/canvas/draft/commit, open/canvas/<id>/; the markdown renders. With the flag off, canvas routes and APIs answer 404.pytest tests/unit_tests/canvas tests/unit_tests/widgets tests/unit_tests/mcp_service/canvasADDITIONAL INFORMATION
CANVAScanvases,canvas_ops,canvas_editors,canvas_viewers,widgets(+ editors/viewers); moves inline content widgets intowidgets; adds a nullablelogs.canvas_idcolumn (no index, no backfill), the only change to an existing table, which runs withCANVASoff toologs(metadata-only on Postgres and MySQL 8, so fast even on a largelogs); no downtime