Skip to content

fix(query_object_factory): normalize deprecated query fields before constructing QueryObject - #41204

Merged
eschutho merged 2 commits into
apache:masterfrom
eschutho:fix/query-object-groupby-deprecated-rename
Jun 18, 2026
Merged

eschutho merged 2 commits into
apache:masterfrom
eschutho:fix/query-object-groupby-deprecated-rename

Conversation

@eschutho

@eschutho eschutho commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

What changed

Deprecation warning found in production Datadog logs:

The field `groupby` is deprecated, please use `columns` instead.
  file: query_object.py, line 219, func: _rename_deprecated_fields
  env: production, service: superset

Charts with a stored query_context column (in slices.query_context) that was saved
using the old groupby key emit this warning on every render via
Slice.get_query_context(). That path parses the stored JSON and calls
QueryContextFactory.create() directly, bypassing the Marshmallow
ChartDataQueryObjectSchema.rename_deprecated_fields @post_load hook that the
REST API path relies on. By the time QueryObject._rename_deprecated_fields sees
groupby in **kwargs, there is no caller who can act on the warning — it is pure
noise in production logs.

What was changed

QueryObjectFactory.create() now normalises all four DEPRECATED_FIELDS
(groupby → columns, granularity_sqla → granularity, timeseries_limit → series_limit,
timeseries_limit_metric → series_limit_metric) before any downstream processing.

Two effects:

  1. QueryObject._rename_deprecated_fields never sees the old keys for the factory path,
    so no warning is emitted for stored query_context.
  2. Bonus correctness fix: _process_time_range calls get_x_axis_label(kwargs.get("columns")).
    Previously, for stored query_context that used groupby, columns was None at that
    point, causing the x-axis temporal filter match to silently fall back to the first temporal
    filter. After this fix, columns is populated from groupby before time-range resolution.

setdefault semantics: if both the deprecated key and the canonical key are present,
the canonical key wins (semantically more correct than the old setattr overwrite in
QueryObject._rename_deprecated_fields). In practice, no stored query_context will
have both keys simultaneously.

No behavior change

Charts that use stored query_context with groupby continue to produce the correct
result. The only observable change is the suppression of the deprecation warning and
the correctness improvement to temporal filter resolution described above.

Test plan

  • New unit tests in test_query_object_factory.py:
    • test_deprecated_groupby_renamed_to_columns
    • test_deprecated_groupby_does_not_overwrite_columns (canonical wins)
    • test_deprecated_groupby_empty_list_is_ignored (falsy edge case)
    • test_deprecated_granularity_sqla_renamed_to_granularity
    • test_deprecated_timeseries_limit_renamed_to_series_limit
    • test_deprecated_timeseries_limit_zero_is_not_renamed (integer 0 falsy edge case, documents correct default)
  • All existing TestQueryObjectFactory tests continue to pass.
  • CI green.

…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.
@bito-code-review

bito-code-review Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #bb96ef

Actionable Suggestions - 0
Additional Suggestions - 2
  • superset/common/query_object_factory.py - 2
    • Missing deprecation warnings in factory · Line 69-74
      Add a deprecation warning before renaming each deprecated kwarg in `QueryObjectFactory.create`. For example:
      logger.warning(
          "The field `%s` is deprecated, please use `%s` instead.",
          field.old_name,
          field.new_name,
      )
      

      Also import or configure logger as done in QueryObject._rename_deprecated_fields.

    • Incomplete test coverage for deprecated fields · Line 69-74
      Test coverage for deprecated field transformations is incomplete. Only `groupby → columns` has tests (lines 142-169), but `granularity_sqla → granularity`, `timeseries_limit → series_limit`, and `timeseries_limit_metric → series_limit_metric` lack test coverage. Following adaptive rule [11730], add comprehensive tests for all new transformation logic.
Review Details
  • Files reviewed - 2 · Commit Range: e1be509..e1be509
    • superset/common/query_object_factory.py
    • tests/unit_tests/common/test_query_object_factory.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment on lines +142 to +146
def test_deprecated_groupby_renamed_to_columns(
self,
query_object_factory: QueryObjectFactory,
raw_query_context: dict[str, Any],
):

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.

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.

Fix in Cursor Fix in VSCode Claude

(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
👍 | 👎

@bito-code-review

Copy link
Copy Markdown
Contributor

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 -> None: to the method signature.

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

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."""

@eschutho
eschutho requested a review from betodealmeida June 18, 2026 16:13
…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)
Comment thread superset/common/query_object_factory.py Outdated
Comment on lines +71 to +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)

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.

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": [...]}.

  1. The call stack proceeds into QueryContextFactory.create in
    superset/common/query_context_factory.py:38-48, which iterates the queries list and
    for each query_obj calls self._query_object_factory.create(result_type, datasource=datasource, server_pagination=server_pagination, **query_obj) (lines 38-47).
    For our example, kwargs in QueryObjectFactory.create contains both columns=None and
    groupby=["country"].

  2. Inside QueryObjectFactory.create in superset/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_name is
    "groupby" and field.new_name is "columns". Since "groupby" is in kwargs with
    value ["country"], value is truthy and "groupby" is popped. However, because
    "columns" already exists in kwargs with value None, kwargs.setdefault("columns", ["country"]) does nothing (dict setdefault does not overwrite an existing key even
    if its value is None). The effect is:

    • groupby is removed from kwargs.

    • columns remains None.

    When the function later constructs a QueryObject (lines 89-95), it passes
    columns=None, so QueryObject.__init__ in superset/common/query_object.py:112-167
    sets self.columns = columns or [] (line 142), resulting in self.columns == [] and
    no grouping. Prior to this PR, the same input would reach
    QueryObject._rename_deprecated_fields in superset/common/query_object.py:219-237,
    which would see groupby in kwargs and set self.columns from groupby, preserving
    the grouping. Thus, a valid groupby configuration is silently dropped when columns
    is present but null-like, changing query semantics and returned results.

</details>

[![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](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) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](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

codecov Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.33%. Comparing base (74ae5a4) to head (6036201).

Files with missing lines Patch % Lines
superset/common/query_object_factory.py 50.00% 1 Missing and 1 partial ⚠️
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     
Flag Coverage Δ
hive 39.32% <25.00%> (-0.01%) ⬇️
mysql 58.06% <50.00%> (-0.01%) ⬇️
postgres 58.12% <50.00%> (-0.01%) ⬇️
presto 40.91% <50.00%> (-0.01%) ⬇️
python 59.57% <50.00%> (-0.01%) ⬇️
sqlite 57.78% <50.00%> (-0.01%) ⬇️
unit 100.00% <ø> (ø)

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.

@bito-code-review

bito-code-review Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #69fdac

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: e1be509..6036201
    • superset/common/query_object_factory.py
    • tests/unit_tests/common/test_query_object_factory.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@eschutho
eschutho merged commit 7040388 into apache:master Jun 18, 2026
59 of 60 checks passed
eschutho added a commit to preset-io/agor-teammate that referenced this pull request Jul 10, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants