Repository navigation
fix(canvas): one filter shape on the data binding, refused when unknown - #46608
Conversation
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.
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
…z/fix/canvas-binding-filters
| raise QueryObjectValidationError( | ||
| f"The chart's filter {first['loc'][0]} is not valid: {first['msg']}" | ||
| ) from ex | ||
| for fixed_filter in fixed: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| try: | ||
| fixed = _binding_filters.validate_python(binding.get("filters") or []) | ||
| except ValidationError as ex: | ||
| first = ex.errors()[0] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| column: str = Field(min_length=1, description="A column of the dataset.") | ||
| op: Literal[ |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Mirrored as a ColumnFilterOperator literal union in 30e9b55, and value is typed as scalar or list.
|
One more, which I couldn't attach inline because the file isn't in this diff. The new union makes validation errors explode in
|
rebenitez1802
left a comment
There was a problem hiding this comment.
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_dumpround trip. - Every write path now refuses a bad shape: draft
set_props, draftadd, 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:
sqltakes the same path as base'ssqlExpression, with the subquery refusal, Jinja and RLS still applied, andcolumnnever 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.
| # A filter the binding's schema doesn't accept is refused, never skipped: | ||
| # skipping it would show unfiltered data under a filtered title. |
There was a problem hiding this comment.
🟡 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.
There was a problem hiding this comment.
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.
| first = ex.errors()[0] | ||
| raise QueryObjectValidationError( | ||
| f"The chart's filter {first['loc'][0]} is not valid: {first['msg']}" | ||
| ) from ex |
There was a problem hiding this comment.
🟡 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 characterfilter 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.)
| 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 |
| 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 |
There was a problem hiding this comment.
Imports for the Discriminator suggestion on BindingFilter below.
| 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, | |
| ) |
| ) | ||
|
|
||
|
|
||
| BindingFilter = ColumnFilter | SqlFilter |
There was a problem hiding this comment.
🟡 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.
| 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), | |
| ] |
| # 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( |
There was a problem hiding this comment.
🟡 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 FalseA 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"There was a problem hiding this comment.
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.
SUMMARY
Follow-up to #45022.
A chart binding's
filterswas 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 tocountry = 'Atlantis'showed every row under a filtered title, and View query had noWHERE.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
QueryObjectValidationErroron 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, andrun_bindingnow 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 adhocSIMPLE/SQLfilter 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
dataBinding.filtersis[{"column": "country", "op": "=", "value": "Atlantis"}]. View query showsWHERE country = 'Atlantis'and the chart is empty.{"column": "nonexistent", "op": "=", "value": "zzz"}instead: the widget shows a query error naming the column.[{"expressionType": "SIMPLE", "subject": "country", "operator": "==", "comparator": "FR"}]: the write is refused with a validation error atdataBinding/filters/0. A widget that already stores that shape at schema version 1 is still editable and queriesWHERE country = 'FR'.pytest tests/unit_tests/canvas tests/unit_tests/widgets tests/unit_tests/mcp_service/canvasADDITIONAL INFORMATION
CANVAS