Repository navigation
fix(query_object_factory): normalize deprecated query fields before constructing QueryObject - #41204
Conversation
…ng QueryObject Stored `query_context` JSON (in `slices.query_context`) may contain the legacy `groupby` key instead of `columns`. When loaded via `Slice.get_query_context()`, this dict bypasses the Marshmallow schema `@post_load` renaming and is passed directly to `QueryObjectFactory.create()`, triggering a `logger.warning()` in `QueryObject._rename_deprecated_fields` on every chart render — producing continuous Datadog noise with no caller able to act on it. Normalise all `DEPRECATED_FIELDS` in `QueryObjectFactory.create()` before any downstream processing, mirroring what `ChartDataQueryObjectSchema` does for the REST API path. `setdefault` is used so that an explicit `columns` key (if present) is not overwritten by a stale `groupby` value.
Code Review Agent Run #bb96efActionable Suggestions - 0Additional Suggestions - 2
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 |
| def test_deprecated_groupby_renamed_to_columns( | ||
| self, | ||
| query_object_factory: QueryObjectFactory, | ||
| raw_query_context: dict[str, Any], | ||
| ): |
There was a problem hiding this comment.
Suggestion: Add an explicit return type hint to this newly added test method so it is fully typed. [custom_rule]
Severity Level: Minor
Why it matters? 🤔
This is a newly added Python test method, and it omits an explicit return type annotation. The surrounding code was changed, so the rule requiring new Python functions/classes to be fully typed applies here.
(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** tests/unit_tests/common/test_query_object_factory.py
**Line:** 142:146
**Comment:**
*Custom Rule: Add an explicit return type hint to this newly added test method so it is fully typed.
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|
The suggestion to add an explicit return type hint to the newly added test method is correct, as it improves code clarity and adheres to type-checking standards. You can resolve this by adding Here is the corrected code for the test method: def test_deprecated_groupby_renamed_to_columns(
self,
query_object_factory: QueryObjectFactory,
raw_query_context: dict[str, Any],
) -> None:
"""groupby in stored query_context should be silently renamed to columns."""There are no other comments on this pull request to address. tests/unit_tests/common/test_query_object_factory.py |
…f-review
Self-review findings (session 019edb8049b071838bfdd5c6):
1. Simplify rename loop: outer `if old_name in kwargs` is redundant because
`kwargs.pop(old_name, None)` already returns None (falsy) for absent keys.
Replace with a single walrus line: `if old_val := kwargs.pop(old_name, None)`.
2. Add missing unit tests:
- groupby=[] (falsy value popped cleanly, columns defaults to [])
- granularity_sqla -> granularity rename
- timeseries_limit -> series_limit rename
- timeseries_limit=0 (integer 0 is falsy; documents that 0 is not propagated
but QueryObject default is also 0, so behavior is correct)
| for field in DEPRECATED_FIELDS: | ||
| if field.old_name in kwargs: | ||
| if value := kwargs.pop(field.old_name): | ||
| kwargs.setdefault(field.new_name, value) |
There was a problem hiding this comment.
Suggestion: The deprecated-field normalization can drop valid groupby/deprecated values when the canonical key is present but null-like (for example columns: None). Because setdefault treats an existing None key as already set, the deprecated value is discarded after pop, so grouping can be silently lost and queries can return different results. Normalize with explicit precedence logic that still promotes deprecated values when the canonical field is missing or null-like, instead of unconditional setdefault on a possibly null existing key. [logic error]
Severity Level: Major ⚠️
- ❌ /superset/v1/query/ can ignore valid groupby columns.
- ⚠️ QueryContextFactory users risk losing grouping semantics.
- ⚠️ Aggregation queries may return ungrouped, inflated result sets.Steps of Reproduction ✅
1. Use the legacy query endpoint `POST /superset/v1/query/` which is implemented in
`superset/views/api.py:8-22`. This endpoint reads `request.form["query_context"]` (line
16) and calls `QueryContextFactory.create(**json.loads(request.form["query_context"]))`
(lines 16-18).
2. In the request body, supply a `query_context` JSON where a query object contains both a
null-like canonical field and a populated deprecated field, for example:
```json
{
"datasource": {"id": 1, "type": "table"},
"queries": [{
"columns": null,
"groupby": ["country"],
"metrics": ["sum__value"]
}],
"result_type": "full",
"result_format": "json"
}
When json.loads runs in Api.query, this becomes a Python dict where the
single-element dict in queries has {"columns": None, "groupby": ["country"], "metrics": [...]}.
-
The call stack proceeds into
QueryContextFactory.createin
superset/common/query_context_factory.py:38-48, which iterates thequerieslist and
for eachquery_objcallsself._query_object_factory.create(result_type, datasource=datasource, server_pagination=server_pagination, **query_obj)(lines 38-47).
For our example,kwargsinQueryObjectFactory.createcontains bothcolumns=Noneand
groupby=["country"]. -
Inside
QueryObjectFactory.createinsuperset/common/query_object_factory.py:52-96,
the deprecated-field normalization loop runs at lines 69-74:for field in DEPRECATED_FIELDS: if field.old_name in kwargs: if value := kwargs.pop(field.old_name): kwargs.setdefault(field.new_name, value)
For the
DeprecatedField(old_name="groupby", new_name="columns"),field.old_nameis
"groupby"andfield.new_nameis"columns". Since"groupby"is inkwargswith
value["country"],valueis truthy and"groupby"is popped. However, because
"columns"already exists inkwargswith valueNone,kwargs.setdefault("columns", ["country"])does nothing (dictsetdefaultdoes not overwrite an existing key even
if its value isNone). The effect is:-
groupbyis removed fromkwargs. -
columnsremainsNone.
When the function later constructs a
QueryObject(lines 89-95), it passes
columns=None, soQueryObject.__init__insuperset/common/query_object.py:112-167
setsself.columns = columns or [](line 142), resulting inself.columns == []and
no grouping. Prior to this PR, the same input would reach
QueryObject._rename_deprecated_fieldsinsuperset/common/query_object.py:219-237,
which would seegroupbyinkwargsand setself.columnsfromgroupby, preserving
the grouping. Thus, a validgroupbyconfiguration is silently dropped whencolumns
is present but null-like, changing query semantics and returned results. -
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ced994bcbe0a441e898f0903670452d8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ced994bcbe0a441e898f0903670452d8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/common/query_object_factory.py
**Line:** 71:74
**Comment:**
*Logic Error: The deprecated-field normalization can drop valid `groupby`/deprecated values when the canonical key is present but null-like (for example `columns: None`). Because `setdefault` treats an existing `None` key as already set, the deprecated value is discarded after `pop`, so grouping can be silently lost and queries can return different results. Normalize with explicit precedence logic that still promotes deprecated values when the canonical field is missing or null-like, instead of unconditional `setdefault` on a possibly null existing key.
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
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #41204 +/- ##
==========================================
- Coverage 64.33% 64.33% -0.01%
==========================================
Files 2651 2651
Lines 144766 144769 +3
Branches 33401 33403 +2
==========================================
+ Hits 93131 93132 +1
- Misses 49965 49966 +1
- Partials 1670 1671 +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:
|
Code Review Agent Run #69fdacActionable 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 |
Backported apache/superset#41204 (merged 3wks ago on master) to the 6.0-bug-fixes line, which never got it and was still logging the groupby/timeseries_limit deprecation warning ~250x/day in prod.
What changed
Deprecation warning found in production Datadog logs:
Charts with a stored
query_contextcolumn (inslices.query_context) that was savedusing the old
groupbykey emit this warning on every render viaSlice.get_query_context(). That path parses the stored JSON and callsQueryContextFactory.create()directly, bypassing the MarshmallowChartDataQueryObjectSchema.rename_deprecated_fields@post_loadhook that theREST API path relies on. By the time
QueryObject._rename_deprecated_fieldsseesgroupbyin**kwargs, there is no caller who can act on the warning — it is purenoise in production logs.
What was changed
QueryObjectFactory.create()now normalises all fourDEPRECATED_FIELDS(
groupby → columns,granularity_sqla → granularity,timeseries_limit → series_limit,timeseries_limit_metric → series_limit_metric) before any downstream processing.Two effects:
QueryObject._rename_deprecated_fieldsnever sees the old keys for the factory path,so no warning is emitted for stored
query_context._process_time_rangecallsget_x_axis_label(kwargs.get("columns")).Previously, for stored
query_contextthat usedgroupby,columnswasNoneat thatpoint, causing the x-axis temporal filter match to silently fall back to the first temporal
filter. After this fix,
columnsis populated fromgroupbybefore time-range resolution.setdefaultsemantics: if both the deprecated key and the canonical key are present,the canonical key wins (semantically more correct than the old
setattroverwrite inQueryObject._rename_deprecated_fields). In practice, no storedquery_contextwillhave both keys simultaneously.
No behavior change
Charts that use stored
query_contextwithgroupbycontinue to produce the correctresult. The only observable change is the suppression of the deprecation warning and
the correctness improvement to temporal filter resolution described above.
Test plan
test_query_object_factory.py:test_deprecated_groupby_renamed_to_columnstest_deprecated_groupby_does_not_overwrite_columns(canonical wins)test_deprecated_groupby_empty_list_is_ignored(falsy edge case)test_deprecated_granularity_sqla_renamed_to_granularitytest_deprecated_timeseries_limit_renamed_to_series_limittest_deprecated_timeseries_limit_zero_is_not_renamed(integer 0 falsy edge case, documents correct default)TestQueryObjectFactorytests continue to pass.