Skip to content

fix(canvas): one filter shape on the data binding, refused when unknown - #46608

Merged
msyavuz merged 4 commits into
msyavuz/feat/canvasfrom
msyavuz/fix/canvas-binding-filters
Nov 26, 2026
Merged

msyavuz merged 4 commits into
msyavuz/feat/canvasfrom
msyavuz/fix/canvas-binding-filters

Conversation

@msyavuz

@msyavuz msyavuz commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Follow-up to #45022.

A chart binding's filters was hidden from the control schema (SkipJsonSchema) and applied only when it happened to be in Explore's adhoc shape. Any other shape was skipped at query time, so a chart asked to filter to country = 'Atlantis' showed every row under a filtered title, and View query had no WHERE.

Now the binding has one typed filter shape, visible in the schema with its operators spelled out (=, !=, <, <=, >, >=, LIKE, NOT LIKE, ILIKE, NOT ILIKE, IN, NOT IN, IS NULL, IS NOT NULL, IS TRUE, IS FALSE, TEMPORAL_RANGE):

{"column": "country", "op": "=", "value": "FR"}
{"column": "order_date", "op": "TEMPORAL_RANGE", "value": "Last month"}
{"sql": "SUM(sales) > 1000", "clause": "HAVING"}

A filter of any other shape is a validation error on write (widget update, draft ops) and a QueryObjectValidationError on read for anything already stored, never a silent skip. A filter on a column the dataset doesn't have is also an error: the chart data pipeline drops it and reports it as rejected, and run_binding now refuses instead of returning the unfiltered rows.

The three querying widgets (echarts, metric-tile, ag-grid-table) move to schema version 2. The migrator turns a stored adhoc SIMPLE/SQL filter into the filter it was applied as, and leaves out anything version 1 never applied, so widgets saved before this stay editable and show the same rows.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A, no UI change. Before: an invalid or unknown-column filter is dropped and the chart shows unfiltered rows. After: the write is refused, or the widget shows a query error.

TESTING INSTRUCTIONS

  1. Through MCP, add an ECharts widget whose dataBinding.filters is [{"column": "country", "op": "=", "value": "Atlantis"}]. View query shows WHERE country = 'Atlantis' and the chart is empty.
  2. Use {"column": "nonexistent", "op": "=", "value": "zzz"} instead: the widget shows a query error naming the column.
  3. Try [{"expressionType": "SIMPLE", "subject": "country", "operator": "==", "comparator": "FR"}]: the write is refused with a validation error at dataBinding/filters/0. A widget that already stores that shape at schema version 1 is still editable and queries WHERE country = 'FR'.
  4. pytest tests/unit_tests/canvas tests/unit_tests/widgets tests/unit_tests/mcp_service/canvas

ADDITIONAL INFORMATION

  • Has associated issue: No, found in acceptance testing of feat(canvas): Canvas, the document that places widgets #45022
  • Required feature flags: CANVAS
  • Changes UI: No
  • Includes DB Migration: No, stored props upgrade on read through the widget's props migrator
  • Introduces new feature or API: No, changes the shape of an unreleased field
  • Removes existing feature or API: No

A chart binding's fixed filters were hidden from the control schema and
applied only when they happened to be in Explore's adhoc shape; anything
else was skipped, so a chart showed every row under a filtered title and
View query had no WHERE clause.

The binding's filters are one typed shape, visible in the schema with the
operators spelled out: {column, op, value} on one column, or {sql, clause}
for a free predicate on WHERE or HAVING. A filter of any other shape is a
validation error on write and a query error on read, never a silent skip.
@netlify

netlify Bot commented Nov 26, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 8567e2a
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6b0825a2281d36ea71a9caf6
😎 Deploy Preview https://deploy-preview-46608--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; no actionable issues were identified in the review.

Assessed commit: 30e9b55a0753

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.35%. Comparing base (e63d5e4) to head (4134ca0).

Additional details and impacted files
@@                 Coverage Diff                  @@
##           msyavuz/feat/canvas   #46608   +/-   ##
====================================================
  Coverage                86.34%   86.35%           
====================================================
  Files                     3251     3251           
  Lines                   226348   226440   +92     
  Branches                 53345    53360   +15     
====================================================
+ Hits                    195450   195544   +94     
+ Misses                   27394    27393    -1     
+ Partials                  3504     3503    -1     
Flag Coverage Δ
hive 34.08% <37.39%> (+<0.01%) ⬆️
javascript 83.19% <ø> (+<0.01%) ⬆️
mysql 51.17% <37.39%> (-0.05%) ⬇️
postgres 51.20% <37.39%> (-0.04%) ⬇️
presto 35.71% <37.39%> (+<0.01%) ⬆️
python 88.80% <100.00%> (+<0.01%) ⬆️
sqlite 50.89% <37.39%> (-0.05%) ⬇️
unit 84.54% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread superset/canvas/data.py
raise QueryObjectValidationError(
f"The chart's filter {first['loc'][0]} is not valid: {first['msg']}"
) from ex
for fixed_filter in fixed:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A filter on a column that isn't on the dataset is still dropped silently, which is the same failure this PR is fixing.

I ran it: filters: [{"column": "nonexistent", "op": "=", "value": "zzz"}] came back with all 7 rows and SELECT category, SUM(amount) FROM amounts GROUP BY category LIMIT 1000 — no WHERE, no error. helpers.py:7982 skips it by design, and query_actions.py already returns rejected_filter_columns naming it, but run_binding throws that away.

Either surface the rejected columns or check the column on write, the way filter.select does.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 30e9b55: run_binding raises on the pipeline's rejected_filters, naming the column, with a SQLite-backed test through the placement data API. Kept it at read time: filter.select only enriches the enum and fails open, and dimensions and metrics aren't checked against the dataset on write either.

# Pydantic's default `extra="ignore"` drops fields the model doesn't
# declare.
filters: SkipJsonSchema[list[dict[str, Any]]] = Field(default_factory=list)
filters: list[BindingFilter] = Field(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes the props shape without bumping echarts.schema_version (still 1, migrators empty), so canvases already holding old-shape filters can't be edited at all — I tried a pure retitle and it's refused, even though newly_unreadable deliberately lets retitles through.

placements.py already runs upgrade_props on read, so the hook is there. Nothing in-repo writes the old shape, so this is only dev and acceptance canvases authored via MCP, but on this branch those exist.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 30e9b55: the three querying widgets are at schema version 2 with a shared migrator. An adhoc SIMPLE/SQL filter becomes the filter it was applied as, shapes version 1 skipped are dropped so the rows don't change, and a test re-saves a version-1 widget through entity_props.

Comment thread superset/canvas/data.py Outdated
try:
fixed = _binding_filters.validate_python(binding.get("filters") or [])
except ValidationError as ex:
first = ex.errors()[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

first['loc'][0] raises IndexError when filters isn't a list at all — pydantic gives loc=() there. Reproduced with both a dict and a string.

The message is also misleading one line down: {"sql": "a > 1", "clause": "where"} reports "filter 0 is not valid: Field required" rather than the clause error, because it picks the wrong union branch.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 30e9b55: the union is discriminated on the sql key, so the clause case reports filter 0 (clause) ... 'WHERE' or 'HAVING', and a non-list gives "filters are not valid" instead of an IndexError. Both are tested.

Comment thread superset/widgets/controls.py Outdated
model_config = ConfigDict(extra="forbid")

column: str = Field(min_length=1, description="A column of the dataset.")
op: Literal[

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No TEMPORAL_RANGE in the operator list (also no NOT ILIKE, IS TRUE, IS FALSE), so a date range can only be written as raw SQL — which seems like the thing this PR is trying to move away from.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added NOT ILIKE, IS TRUE, IS FALSE and TEMPORAL_RANGE (string value required, passed straight to the query object) in 30e9b55. The array operators stay out until a binding can say a column is multi-valued.

{"col": "status", "op": "IS NOT NULL", "val": None},
]
assert query["extras"] == {
"where": "(a > 1)",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two gaps worth covering: a stored old-shape filter being read back, and a filter naming a column that isn't on the dataset. The second is the one that still silently drops.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both added in 30e9b55 (binding_filters_upgrade_test.py and the rejected-column API test), plus non-list filters and the clause message.


/** A fixed filter of a binding: on one column, or a free SQL predicate. */
export type BindingFilter =
| { column: string; op: string; value?: unknown }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

op is typed string here while clause is mirrored exactly. Nothing consumes filters on the frontend today, so it's cosmetic — but it's the kind of drift that stops being cosmetic later.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mirrored as a ColumnFilterOperator literal union in 30e9b55, and value is typed as scalar or list.

@alexandrusoare

Copy link
Copy Markdown
Contributor

One more, which I couldn't attach inline because the file isn't in this diff.

The new union makes validation errors explode in superset/canvas/definition/ops.py:235: one bad filter produces 11 messages, with the validator tag in the path —

/props/dataBinding/filters/0/function-after[_value_fits_operator(), ColumnFilter]/column

request_pointer already handles this shape elsewhere, so it's probably a small fix there. Caused here, surfaces there.

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Replacing the silent skip with one typed filter shape that is refused when wrong is the right fix, and I found no blockers.

What I checked:

  • All 13 operators give the same SQL and rows as base on real SQLite.
  • The value union keeps exact types through the model_validate → model_dump round trip.
  • Every write path now refuses a bad shape: draft set_props, draft add, and widget POST/PUT.
  • Nothing on the canvas branch still writes or reads the old adhoc shape.
  • Canvases that already store an old-shape filter still load and publish; only that widget's query fails, with a 400.
  • Security is unchanged: sql takes the same path as base's sqlExpression, with the subquery refusal, Jinja and RLS still applied, and column never becomes SQL.

I left three non-blocking 🟡 notes inline: an unknown column is still skipped, error messages don't name the field, and the MCP minimal schema isn't collapsed. I verified the suggestions together: the canvas, widgets and MCP canvas suites pass 878/878, with ruff and mypy clean on the changed files.

Comment thread superset/canvas/data.py
Comment on lines +87 to +88
# A filter the binding's schema doesn't accept is refused, never skipped:
# skipping it would show unfiltered data under a filtered title.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: a filter on a column the dataset doesn't have is still skipped.

{"column": "categoryy", "op": "=", "value": "A"} returns 200 with every row and no WHERE, because core get_sqla_query drops a filter whose column it can't resolve (superset/models/helpers.py, "column not found! Silently skip"). This predates the PR, but it's the exact "unfiltered data under a filtered title" case this comment promises to refuse. Now that column is documented in the schema, a typo or a renamed column is the most likely way to hit it. A missing dimension already fails with "Columns missing in dataset".

The fix belongs in run_binding, which is outside the diff, so I can't post it as a suggestion. Run it after command.validate() so it names no column to a caller who can't read the dataset. Saved metric names must stay allowed because they become HAVING filters:

def unknown_filter_columns(binding: dict[str, Any], datasource: Any) -> list[str]:
    """The columns ``binding``'s fixed filters name that ``datasource`` has
    neither as a column (by name or verbose name) nor as a saved metric."""
    known = {
        name
        for column in datasource.columns
        for name in (column.column_name, column.verbose_name)
        if name
    } | {metric.metric_name for metric in datasource.metrics}
    return sorted(
        {
            fixed.column
            for fixed in _binding_filters.validate_python(binding.get("filters") or [])
            if isinstance(fixed, ColumnFilter) and fixed.column not in known
        }
    )


# in run_binding, right after command.validate():
    if missing := unknown_filter_columns(binding, query_context.datasource):
        raise QueryObjectValidationError(
            f"The chart filters on columns the dataset doesn't have: {missing}"
        )

Tested on the sqlite aggregate_table through _preview_widget_impl: on head, categoryy returns 7 rows. With the fix it gets a QueryError, and category, every operator, and a filter on the saved metric total_amount still work.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 30e9b55 via the pipeline's own rejected_filters rather than a pre-check: run_binding raises after command.run(), so access is checked first, and it also covers runtime filters from filter widgets whose column is gone. Saved metrics aren't affected since the pipeline only rejects columns.

Comment thread superset/canvas/data.py Outdated
Comment on lines +92 to +95
first = ex.errors()[0]
raise QueryObjectValidationError(
f"The chart's filter {first['loc'][0]} is not valid: {first['msg']}"
) from ex

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: say which field is wrong, and don't 500 on a non-list.

first['loc'][0] raises IndexError when the stored filters isn't a list (loc == ()), which turns into a 500 instead of a 400. The message also never names the field. With this change, plus the Discriminator suggestion in controls.py, the messages read:

  • filter 0 is not valid: sql: String should have at least 1 character
  • filter 0 is not valid: clause: Input should be 'WHERE' or 'HAVING'
  • filters are not valid: Input should be a valid list

(at rather than where, which is already this function's WHERE-clause list, and mypy flags the clash.)

Suggested change
first = ex.errors()[0]
raise QueryObjectValidationError(
f"The chart's filter {first['loc'][0]} is not valid: {first['msg']}"
) from ex
first = ex.errors()[0]
if not first["loc"]:
raise QueryObjectValidationError(
f"The chart's filters are not valid: {first['msg']}"
) from ex
# ``loc`` is the filter's index, the form it was read as, then the key.
index, *rest = first["loc"]
key = "/".join(map(str, rest[1:]))
at = f"{key}: " if key else ""
raise QueryObjectValidationError(
f"The chart's filter {index} is not valid: {at}{first['msg']}"
) from ex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 30e9b55 and 4134ca0: the loc is read safely (loc=() gives "filters are not valid"), and the union tag is stripped so the message reads filter 0 (clause) is not valid: ....

Comment thread superset/widgets/controls.py Outdated
Comment on lines +32 to +34
from typing import Any, ClassVar, Literal

from pydantic import BaseModel, ConfigDict, Field
from pydantic.json_schema import SkipJsonSchema
from pydantic import BaseModel, ConfigDict, Field, model_validator

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imports for the Discriminator suggestion on BindingFilter below.

Suggested change
from typing import Any, ClassVar, Literal
from pydantic import BaseModel, ConfigDict, Field
from pydantic.json_schema import SkipJsonSchema
from pydantic import BaseModel, ConfigDict, Field, model_validator
from typing import Annotated, Any, ClassVar, Literal
from pydantic import (
BaseModel,
ConfigDict,
Discriminator,
Field,
model_validator,
Tag,
)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 30e9b55.

Comment thread superset/widgets/controls.py Outdated
)


BindingFilter = ColumnFilter | SqlFilter

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: the plain union makes every refusal report the ColumnFilter branch.

ex.errors()[0] in data.py therefore says filter 0 is not valid: Field required for an Explore-shaped filter, for {"sql": ""} and for {"sql": "a > 1", "clause": "where"}. On writes, each bad filter returns 5–11 errors with paths like /filters/0/function-after[_value_fits_operator(), ColumnFilter]/column.

Choosing the form from the keys checks each filter against one model only. {"column": "c", "op": "IN", "value": "a"} then gives one error (IN takes a non-empty list of values) instead of five. The schema becomes oneOf, and isinstance(..., ColumnFilter) in data.py keeps working. This needs the import suggestion at the top of the file too.

Suggested change
BindingFilter = ColumnFilter | SqlFilter
def _filter_form(value: Any) -> str:
"""Which form a filter is written in: ``SqlFilter`` when it has a
predicate, ``ColumnFilter`` otherwise. Checking it against that form alone
reports what is wrong with it, not also every key the other form lacks."""
if isinstance(value, dict):
return "SqlFilter" if "sql" in value else "ColumnFilter"
return "SqlFilter" if isinstance(value, SqlFilter) else "ColumnFilter"
BindingFilter = Annotated[
Annotated[ColumnFilter, Tag("ColumnFilter")]
| Annotated[SqlFilter, Tag("SqlFilter")],
Discriminator(_filter_form),
]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 30e9b55 with the same shape (callable discriminator on the sql key); 4134ca0 also strips the tag from error locations so write errors point at /filters/0/clause rather than /filters/0/sql/clause.

# Pydantic's default `extra="ignore"` drops fields the model doesn't
# declare.
filters: SkipJsonSchema[list[dict[str, Any]]] = Field(default_factory=list)
filters: list[BindingFilter] = Field(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: making filters schema-visible bloats the MCP minimal schema.

_is_collapsible in superset/widgets/schema_tools.py only treats array items that are directly an object as collapsible. items: {"anyOf": [$ref ColumnFilter, $ref SqlFilter]} is therefore treated as a cheap leaf, so get_widget_control_schema without paths inlines both filter models every time (orderBy is collapsed correctly). The minimal schema grows from 2104 to 4060 bytes for ag-grid-table, from 2459 to 4415 for metric-tile, and from 5164 to 7120 for echarts, which breaks the tool's "optional nested branches come back as x-collapsed" contract. That file isn't in the diff, so here's the fix:

    if node.get("type") == "array":
        items = node.get("items")
        if isinstance(items, dict):
            # Items of several shapes (``anyOf`` / ``oneOf``) are objects when
            # any of the shapes is.
            shapes = items.get("anyOf") or items.get("oneOf") or [items]
            return any(
                isinstance(shape, dict) and _is_object(_deref(root, shape))
                for shape in shapes
            )
    return False

A test that fails on head and passes with the fix:

def test_filters_of_several_shapes_are_collapsed() -> None:
    widget = registry.get("ag-grid-table")
    assert widget is not None
    minimal = prune_to_minimal_viable(widget.get_control_schema(None, None))
    filters = minimal["properties"]["dataBinding"]["properties"]["filters"]
    assert filters["x-collapsed"] is True
    assert filters["x-path"] == "dataBinding/filters"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 4134ca0 with your test; filters are back behind x-collapsed for all three widgets.

…full operator set

Review follow-ups:
- the three querying widgets move to schema version 2 with a migrator
  from the adhoc shape, so widgets saved before stay editable
- a filter on a column the dataset lacks is a query error instead of
  unfiltered rows: run_binding reads the pipeline's rejected_filters
- the filter union is discriminated by key, so a bad SQL filter is
  reported against its own fields, and filters that aren't a list are
  refused without an IndexError
- NOT ILIKE, IS TRUE, IS FALSE and TEMPORAL_RANGE join the operators
- the frontend type mirrors the operator set
…e in the minimal schema

The union tag pydantic puts between the filter's index and its field is
not a level of the stored value, so it is dropped from error locations on
write and read. An array whose items take several object shapes is
collapsed in the MCP minimal control schema like an array of one shape.
@msyavuz

msyavuz commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

The error explosion was the plain union: with the discriminator (30e9b55) one bad filter gives one error, and 4134ca0 drops the union tag from the location, so the pointer is /props/dataBinding/filters/0/clause. Covered in test_registry.py.

@msyavuz
msyavuz merged commit db41461 into msyavuz/feat/canvas Nov 26, 2026
70 checks passed
@msyavuz
msyavuz deleted the msyavuz/fix/canvas-binding-filters branch November 26, 2026 16:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants