Repository navigation
fix(api): restore three schema fields disabled by a stray trailing comma - #43225
Conversation
Code Review Agent Run #b92497Actionable Suggestions - 0Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #43225 +/- ##
==========================================
- Coverage 80.40% 80.39% -0.01%
==========================================
Files 2932 2932
Lines 174525 174525
Branches 40548 40548
==========================================
- Hits 140319 140313 -6
- Misses 31537 31543 +6
Partials 2669 2669
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 #8da7abActionable 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 |
aminghadersohi
left a comment
There was a problem hiding this comment.
Nice catch. A stray trailing comma turning groupby = (fields.List(...),) into a one-element tuple is exactly the kind of bug that hides in plain sight: Marshmallow only collects Field instances, so all three declarations were silently dropped from their schemas — required=True never applied, never emitted to the spec. The regression test that walks every Schema subclass looking for tuple-wrapped Fields (test_schema_attributes_are_fields_not_tuples) is a good, general guard against the whole class of mistake, not just these three sites. Both bot threads were handled well too — the Dict value-typing deferral on :541 is correctly reasoned (the parent options is a bare fields.Dict, so tightening the nested schema would document, not enforce), and the minLength→Length(min=1) switch on :871 was verified empirically before landing. Reviewed at d8c18e1; nothing here blocks.
One correction, non-blocking, worth a sentence for the next reader:
validate=Length(min=1) fixes the documented constraint, not runtime enforcement. The in-code comments are precise ("the schema has to say so", "emits the correct constraint"). But the PR thread reply describing it as enforcing the bound overstates slightly. These three per-operation schemas are never .load()ed anywhere:
$ grep -rn "ChartDataPivotOptionsSchema\|ChartDataAggregateOptionsSchema\|ChartDataRollingOptionsSchema" superset/
schemas.py: <class definitions>
schemas.py:1914,1918,1919: CHART_SCHEMAS = (...) # api.py:309 -> openapi_spec_component_schemas
Their only consumer is OpenAPI component registration. At runtime, post_processing[].options is a bare fields.Dict (schemas.py:991), and exec_post_processing (query_object.py:554) does options = post_process.get("options", {}) then getattr(pandas_postprocessing, operation)(df, **options) — the raw dict is splatted straight into pandas. So an empty index is still rejected only by pivot() itself (pandas_postprocessing/pivot.py:117, "Pivot operation requires at least one index"), surfacing as an InvalidPostProcessingError, not a schema 400. The fix is real and strictly better than inert minLength metadata (arrays use minItems, and metadata isn't a validator) — it just corrects the emitted spec; it doesn't add a runtime gate.
Smaller notes:
- No breaking-change risk. Because nothing loads these schemas, restoring the fields changes zero runtime behavior for existing clients. The actual request path is
ChartDataQueryObjectSchema(Meta.unknown = EXCLUDE) →post_processinglist → untypedoptions— malformed values were passed through before and still are. test_pivot_and_aggregate_reject_an_empty_column_listis slightly weaker than it reads. Since it.load()s the per-op schema directly (a legitimate way to test a schema production never loads — but note it exercises a path production doesn't), and these schemas inherit Marshmallow's defaultunknown=RAISE, reverting the production fix makesindex/groupbyunknown fields, which also raises with anindex/groupbymessage key. So the empty-rejection asserts would pass against buggy code too, for the wrong reason; only the closing non-empty positive assertion (load({"index": ["__timestamp"], ...})) actually fails on revert. The other two new tests (..._are_fields_not_tuples,..._are_documented) fail cleanly on revert and are the load-bearing ones. Consider asserting the error message mentions the length bound to isolate the validator — optional.- OpenAPI snapshot:
docs/static/resources/openapi.jsoncontains these schemas but is a manually-committed artifact with no CI freshness gate (no workflow/Makefile references it; last touched by an unrelated PR). Live/swagger/v1regenerates from source and will be correct; the static snapshot is a pre-existing, ungated staleness gap, not this PR's to fix. # noqa: E501removals are correct — de-indenting the description strings out of the tuple wrapper brings them to ≤85 chars (limit 88), so the suppressions are genuinely unneeded now.
Note: I could not run pytest in this environment (superset_core not installed) — the test analysis above is by inspection; CI is green (60 success / 9 skipped / 3 neutral, zero failures).
|
Both questions were right, and they were right in opposite directions. thanks,
return {
operation: 'aggregate',
options: {
groupby: [],
aggregates,
},
};That fires for every aggregation that is not if groupby:
df_groupby = df.groupby(by=groupby)
else:
df_groupby = df.groupby(lambda _: True)So
if not index:
raise InvalidPostProcessingError(
_("Pivot operation requires at least one index")
)Verified against the generated spec rather than the field declarations:
The test that asserted @aminghadersohi your correction is right and I have confirmed it. the only Verified: 219 passed in |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Code Review Agent Run #af1755Actionable 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 |
| "example": {"weekly_rolling_sales": "sales"}, | ||
| }, | ||
| ), | ||
| columns = fields.Dict( |
There was a problem hiding this comment.
This now publishes rolling.columns as an object, but PostProcessingRolling still declares it as string[]. Typed clients must choose between the exported TypeScript contract and the OpenAPI contract; an array reaches rolling() and fails at columns.keys(). Should the exported type be updated to the string-to-string mapping this operation accepts?
There was a problem hiding this comment.
Good catch — and I think the object (OpenAPI) side is the correct one here; it's the exported TS type that's stale, and it was already inconsistent before this PR surfaced it.
Tracing all three sides at this head:
- Runtime
rolling()takescolumns: dict[str, str](superset/utils/pandas_postprocessing/rolling.py:40) and doesdf.loc[:, columns.keys()](:69). An array reaching it hitslist.keys()→AttributeError, exactly as you describe. - What the frontend actually emits:
rollingWindowOperator.ts:48buildsconst columnsMap = Object.fromEntries(columns.map(col => [col, col]))and sendscolumns: columnsMap(:71, and:55forcum) — a string→string object, not astring[]. So Superset's own operator already produces the mapping the OpenAPI object type describes. - The exported type
_PostProcessingRolling.options.columns: string[](superset-ui-core/src/query/types/PostProcessing.ts:154) is therefore the stale side — it contradicts the operator that feeds it._PostProcessingCum(:164) has the samestring[]while the operator emitscolumnsMapforcumtoo.
This PR didn't introduce the divergence: columns was always fields.Dict; the stray-tuple bug had dropped it from the published spec entirely, so the conflict was invisible until the field was restored. The OpenAPI contract now matches both rolling()'s signature and the operator's real output.
So I don't think anything needs to change in this Python-only PR — the correct follow-up is a separate frontend change fixing PostProcessingRolling (and PostProcessingCum) to Record<string, string>. Leaving that call to you and the author.
There was a problem hiding this comment.
Thanks both, agreed with @aminghadersohi's read, and with keeping it out of this PR.
I'd reached the same conclusion independently: the OpenAPI object is correct and the exported TypeScript type is the stale side. Two details that I think settle it beyond the signature trace:
Every assertion already in the repo expects an object, so the mapping isn't a new contract, it's the one that was always in force:
rollingWindowOperator.test.ts columns: { 'count(*)': 'count(*)', ... }
MixedTimeseries/buildQuery.test.ts columns: { count: 'count', ... }
The only string[] anywhere is the ROLLING_RULE fixture in PostProcessing.test.ts, which uses one solely because the type asks for it.
And the reason a contradiction this direct never failed the build: columns.map(col => [col, col]) widens each pair to (string | undefined)[] rather than a tuple, which selects the untyped Object.fromEntries overload —
fromEntries<T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T };
fromEntries(entries: Iterable<readonly any[]>): any; // <- selectedso columnsMap is any and assigns to string[] silently. Forcing the tuple surfaces the real error:
error TS2322: Type 'string[]' is not assignable to type 'Record<string, string>'.
Index signature for type 'string' is missing in type 'string[]'.
So this PR stays Python-only as it stands, and I'll send the frontend fix separately. I'll include diff alongside rolling and cum, diff() takes columns: dict[str, str] and does df[columns.keys()] too, so _PostProcessingDiff carries the identical mismatch even though no operator emits it today.
@sadpandajoe the two earlier threads are addressed at this head as well, whenever you get a chance to look.
There was a problem hiding this comment.
The separate fix is still open, so merging this head first would publish an object in OpenAPI while the exported client type still says string[]. Can #43589 merge first, or can this PR include the type change, so the two public contracts cannot ship out of order?
There was a problem hiding this comment.
Fair concern, and I would rather not fix it by widening this PR.
The frontend change is #43589, and it is already approved and mergeable -- it retypes
columns from string[] to Record<string, string> in
superset-ui-core/src/query/types/PostProcessing.ts for the rolling, diff and cum
types. So the ordering you are asking for is available without any new work: merge
#43589 first, then this one, and the two contracts never disagree in a released state.
For what it is worth the window is narrower than it looks. Master publishes no
columns property on ChartDataRollingOptionsSchema at all today -- the trailing
comma dropped the field before apispec ever saw it -- so the spec is currently silent
rather than wrong. Merging this first would move it from silent to contradicting the
exported type, which I agree is worse than silence, hence the ordering.
Happy to hold this PR until #43589 lands if that is easiest for you. I would rather not
pull the TypeScript change in here, since it would put a frontend edit in a PR that is
otherwise Python-only and would make it harder to revert either half independently.
|
Frontend follow-up is up as #43589, Worth noting the one red check there is |
b9e51e7 to
7453682
Compare
Code Review Agent Run #97a5f9Actionable 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 |
aminghadersohi
left a comment
There was a problem hiding this comment.
Round-3 review at 7453682e58da. The gate on this PR is @sadpandajoe — his three threads are the open items, and whether they are satisfied is his call, not mine. What follows is measurement only, offered to save him time; I am not resolving anything or crediting his threads as closed.
I re-verified the three claims his threads turn on against the runtime at this head, and mutation-tested every new guard.
His three threads, measured against the code at this head
1. groupby should not carry minItems: 1 (thread on Aggregate.groupby, now outdated)
Runtime agrees with him. aggregate() branches on the empty case explicitly — if groupby: df.groupby(by=groupby) else: df.groupby(lambda _: True) (superset/utils/pandas_postprocessing/aggregate.py:42-46) — so groupby: [] is the global-aggregation request, not a malformed one. aggregateOperator.ts:54 emits groupby: [] verbatim. At this head the field carries required=True and no validator, and openapi.json publishes groupby as a required array with no minItems. Matches what he asked for.
2. rolling.columns should be required (thread live at line 594)
Runtime agrees. rolling() takes columns: dict[str, str] positionally with no default (superset/utils/pandas_postprocessing/rolling.py:37-46) and immediately does df.loc[:, columns.keys()] (:69). At this head columns carries required=True and openapi.json lists columns in Rolling.required alongside rolling_type and window. Matches.
3. rolling.columns typed as object vs. PostProcessingRolling: string[] (thread live at line 594)
This one is a genuine cross-language divergence and it is not resolved by this PR — by design, as he and the author discussed. The OpenAPI object side matches both rolling()'s signature and what rollingWindowOperator.ts actually emits; the exported TS type is the stale side, and it was stale before this PR. The PR stays Python-only and the author has committed to a separate frontend change. Whether that is an acceptable split is @sadpandajoe's call.
Mutation testing — the new guards are not vacuous
I reverted each fix in superset/charts/schemas.py one at a time, confirmed the mutation landed, and re-ran tests/unit_tests/charts/test_schemas.py (43 passed clean):
| Mutation (symbol) | Result |
|---|---|
Re-wrap ChartDataPivotOptionsSchema.index in the original 1-tuple |
3 fail, incl. test_schema_attributes_are_fields_not_tuples |
Drop validate=Length(min=1) from ...PivotOptionsSchema.index |
test_pivot_rejects_an_empty_index fails |
Drop required=True from ...RollingOptionsSchema.columns |
test_required_post_processing_options_are_documented fails |
Add validate=Length(min=1) to ...AggregateOptionsSchema.groupby |
test_aggregate_accepts_an_empty_groupby fails |
Every guard kills its mutant. The tuple-detector genuinely catches the original bug rather than merely asserting present-state.
I also ran a static AST scan for the same stray-comma pattern across all of superset/: no other field declarations are wrapped in a tuple, so the fix is complete in scope.
openapi.json matches the schema changes exactly — the three added entries and nothing else, no unrelated regeneration drift.
One non-blocking observation (pre-existing; entirely optional)
ChartDataPivotOptionsSchema.aggregates (superset/charts/schemas.py:966) has the same shape as the rolling.columns gap @sadpandajoe asked to close in thread 2: pivot() raises "Pivot operation must include at least one aggregate" (pivot.py:243-245), but the schema leaves aggregates optional. Measured under app context at this head:
required(aggregates) = False
load {"index": ["a"]} -> {'index': ['a']} # aggregates omitted, accepted
load {"index": ["a"], "aggregates": {}} -> accepted
Both are payloads the published spec permits and the operation rejects. This is pre-existing and untouched by this PR — aggregates was never one of the tuple-disabled fields — so I am explicitly not asking for it here. Flagging it only because it is the exact class of defect this PR is closing, in case @sadpandajoe wants it pulled into scope rather than left for a follow-up.
Context worth stating plainly
ChartDataPostProcessingOperationSchema.options is fields.Dict (schemas.py:1080) — untyped. These per-operation option schemas are therefore documentation/spec artifacts, not request-time validators; nothing here changes what the API accepts at runtime. That makes the blast radius of this PR small, and it is also why the minLength-as-metadata bug could sit unnoticed. It does not diminish the fix — a published contract that contradicts the operation is worth correcting — but it should temper how the change is described.
CI: re-derived from statusCheckRollup taking the latest run per leg name (74 raw entries collapse to 60 unique) — 49 SUCCESS, 9 SKIPPED, 2 NEUTRAL, zero failures.
Deferring to @sadpandajoe on all three of his threads.
|
Thanks for the round-3 measurement, and for being explicit that the three open threads are @sadpandajoe's to close rather than yours. Nothing for me to action there. On your non-blocking observation about It is not one field. I swept all twelve
Four fields, three schemas. Every other option schema is consistent with its operation. The omitted-key case is a 500, not a 400. A bare The empty-value case splits three ways, which is why Pivot already handles empty correctly, your Marking them required is safe for existing charts. Every frontend operator that emits these operations sets the keys unconditionally: So: agreed, out of scope here, and I am not asking for it to be pulled in. I will take it as a separate change, |
Review caught that un-tupling the three field declarations was right but the constraints attached to them were not uniform. `groupby` must not carry a lower bound. `aggregate()` reads an empty groupby as the global-aggregation case, grouping the frame as a whole via `df.groupby(lambda _: True)`, and the frontend's `aggregateOperator` emits `groupby: []` verbatim for every aggregation that is not LAST_VALUE or raw. Publishing `minItems: 1` would have documented Superset's own request as invalid. The parameter still has no default, so it stays required. `rolling()` takes `columns` positionally with no default, exactly as it takes `rolling_type`, which this schema already marked required. Mark `columns` required too, so the spec matches the operation contract instead of describing a payload that fails when invoked. `pivot.index` keeps its lower bound: pivot() raises "Pivot operation requires at least one index" on an empty list, so minItems: 1 is what the operation actually enforces. Also hoist the new tests' imports to module scope, matching the rest of the file and clearing the import-outside-toplevel warnings the previous commit introduced. Found by sadpandajoe in review. Co-Authored-By: Claude Opus 5 <[email protected]>
7453682 to
881645f
Compare
Code Review Agent Run #fc1c07Actionable 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 |
aminghadersohi
left a comment
There was a problem hiding this comment.
Rebase-only push: the PR's own diff at 881645f2 is byte-identical to 7453682e, and both upstream Prophet changes to these files survived. 50/50 pass, every guard kills its mutant, CI 61/61 clean.
@sadpandajoe's three threads are still open and remain his to close.
…lumns `rolling()` selects `df.loc[:, columns.keys()]`, so the keys are the source columns and must already exist on the frame. The example inverted that, mapping `weekly_rolling_sales` to `sales`, which asks the operation to read a source column no client would have and rejects the request before the target column can be created. It also contradicted the field's own description one line above, which states the mapping runs source to target. The field was disabled by a trailing comma before this PR, so it never reached the published spec and the example had no way to mislead anyone. Restoring the field is what exposes it, so the correction belongs here. Found by sadpandajoe in review.
Code Review Agent Run #b76ed4Actionable 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 |
rusackas
left a comment
There was a problem hiding this comment.
Nice catch on the trailing comma, and I like that you traced exactly which post-processing operator depends on each dropped field. LGTM, will get this merged once CI's green.
|
...and holler if you need a hand with the rebase, but leaving that to you for now. |
…fields # Conflicts: # tests/unit_tests/charts/test_schemas.py
|
Thanks! Merged |
…mma (#43225) Co-authored-by: Claude Opus 5 <[email protected]> (cherry picked from commit c6d0890)
SUMMARY
Three field declarations in
superset/charts/schemas.pyare wrapped inparentheses with a trailing comma, which makes them one-element tuples
rather than
Fieldinstances:Marshmallow collects only
Fieldinstances into a schema, so an attributelike this is dropped entirely: it never appears in the OpenAPI spec, and its
required=Trueis never applied.The three affected declarations are each the parameter its post-processing
operation cannot run without:
ChartDataAggregateOptionsSchemagroupbyaggregate(df, groupby, aggregates)ChartDataRollingOptionsSchemacolumnsrolling(df, rolling_type, columns, ...)ChartDataPivotOptionsSchemaindexpivot(df, index, aggregates, ...)All three are parameters with no default, and the frontend operators send all
three (
pivotOperatorsendsindex,rollingWindowOperatorsendscolumns).So
/swagger/v1currently documentspivotwithoutindexandaggregatewithout
groupby— the one option each caller must provide.Confirmed before and after:
No runtime behaviour changes. These schemas are documentation only —
ChartDataPostProcessingOperationSchema.optionsis a barefields.Dict, sonothing validates against them; they are registered solely for OpenAPI spec
generation. The only place any of them is
.load()ed is a unit test forrolling, whose payload does not includecolumns, andcolumnsstaysoptional.
I scanned the whole
superset/tree for the pattern; these three are the onlyoccurrences.
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A — the change is to the OpenAPI schema definitions.
TESTING INSTRUCTIONS
Two tests are added:
test_schema_attributes_are_fields_not_tuplesField— a general guard against this typo recurring anywheretest_required_post_processing_options_are_documentedgroupby,indexandcolumnsare present, and the tworequired=Trueones are marked requiredRe-introducing the trailing comma on any one of the three makes both fail.
To see the spec change, start Superset, open
/swagger/v1and compare theChartDataAggregateOptions,ChartDataRollingOptionsandChartDataPivotOptionsdefinitions.ADDITIONAL INFORMATION
CHECKLIST