Repository navigation
feat(time-range-limits): add time range limits for chart queries - #46038
DamianPendrak wants to merge 94 commits into
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #46038 +/- ##
==========================================
+ Coverage 86.09% 86.61% +0.52%
==========================================
Files 3140 3190 +50
Lines 219205 227936 +8731
Branches 51973 54359 +2386
==========================================
+ Hits 188721 197427 +8706
+ Misses 27055 27018 -37
- Partials 3429 3491 +62
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:
|
| "quantity": 3, | ||
| "time_grain": "P1M" | ||
| }, | ||
| "message": "Range can't be longer than 3 months. This one is 3 months and 3 days." |
There was a problem hiding this comment.
This fixture locks in a bug: the span check adds months forward from since (Feb 28 + 3M = May 28), but the preset clamps since backward from until (May 31 − 3M = Feb 28). As a result, "Last 3 months" fails a 3-month max_span on month-end days and passes on other days, and the README's own example config hits this; "Last month" on Mar 31 fails the same way at line 2167.
There was a problem hiding this comment.
Agreed, fixed in 39baff4. The longest range is now counted back from the end, the same way "Last N months" is built, on the server and in the browser. The fixture has month-end cases.
| "quantity": 6, | ||
| "time_grain": "PT1H" | ||
| }, | ||
| "message": "Range can't be longer than 6 hours. This one is 7 hours." |
There was a problem hiding this comment.
A range of 6h 0m 1s is reported as "This one is 7 hours", so the rounding-up message overstates how far over the limit the range is.
There was a problem hiding this comment.
Following the product decision, refused ranges are again shown in the limit's own unit rounded up to a whole unit.
| Mirrors the column lookup of ``get_sqla_query`` (name, then verbose name): a | ||
| filter whose column isn't found is skipped there, and one on an adhoc column or | ||
| a metric fails the query, so neither bounds anything. A filter on a column that | ||
| isn't temporal bounds nothing either. A filter a dataset template removes still |
There was a problem hiding this comment.
I think a dataset template can widen the range past this check. get_time_filter('order_date', remove_filter=True) reads the raw request via get_form_data(), so an extra adhoc_filters key the schema drops wins (whole table back as Gamma). Could the sync path render from the checked query, as the worker does?
There was a problem hiding this comment.
| - **Editor notice:** when the global limits turn on, or a global rule gets stricter, each dashboard editor sees a one-time info alert at the top of the dashboard ("Your admin turned on time range limits: …" or "Your admin changed time range limits: …") with a **Got it** button. Editors are the users whose own user, roles or groups are listed as the dashboard's editors, plus any editors `EXTRA_EDITORS_RESOLVER` adds; admins see it only when one of these lists them. Viewers, embedded guests and standalone views (embedded dashboards, reports) don't see it, and loosening the limits shows nothing. **Got it** hides it and stores the global limits the editor acknowledged as one `key_value` row per editor (resource `app`, keyed by a UUID derived from the user id, no expiry), so the notice comes back only when the limits get stricter than that. The row names no user, so deleting the user still works and leaves the row behind; deleting a row only shows the notice to that editor again. | ||
| - **Dataset editor:** the **Settings** tab has the same section for the dataset, below the Basic and Advanced cards. It saves inside the dataset's `extra` with the rest of the dataset, and the **Extra** field doesn't show the `time_range_limits` key. A dataset with no time column shows its stored value, disabled, since there is nothing to limit. | ||
|
|
||
| ## Guarded paths |
There was a problem hiding this comment.
| dashboard, | ||
| now, | ||
| [ | ||
| (ranges, is_native or result_type == ChartDataResultType.SAMPLES) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Removed the exemption in cc918cc. A samples query without a time range answers 400.
| def _limits_could_apply(chart: Slice, dashboard: Optional[Dashboard]) -> bool: | ||
| datasource = cast("Explorable", chart.resolved_datasource) | ||
| try: | ||
| temporal = datasource is None or has_temporal_column(datasource) |
There was a problem hiding this comment.
Fixed in 8fc36be. Charts with no dataset are skipped, so the report renders as it does with the flag off.
| force: boolean, | ||
| key: string = ENTRY_KEY, | ||
| ): Promise<ChartRangesEntry> { | ||
| const queryContext = await buildV1ChartDataPayload({ |
There was a problem hiding this comment.
IIUC this build goes through the plugin's buildQuery, which remembers the last filters, so it uses up the table's reset to page 0. On page 3, a new time range sent row_offset: 20 (0 with the flag off) and showed "No results". Could Explore reuse this payload for the run, like the dashboard does?
explore-pagination-flag-on.mp4
| @@ -238,6 +256,7 @@ class DashboardJSONMetadataSchema(Schema): | |||
| allow_none=True, | |||
| validate=OneOf(["default", "force_on", "force_off"]), | |||
| ) | |||
| time_range_limits = fields.Raw(allow_none=True) | |||
There was a problem hiding this comment.
There was a problem hiding this comment.
Done in fd61cfa, as you suggested. With the flag off, writes and imports check the shape with parse_time_range_limits(check_units=False): a value that isn't a policy object gets 400 on writes and 422 on imports.
| @@ -331,6 +340,17 @@ def get_column_values( | |||
| except SupersetSecurityException as ex: | |||
| return self.response(403, message=ex.message) | |||
|
|
|||
| try: | |||
| check_datasource_open_query(datasource) | |||
There was a problem hiding this comment.
Not sure this one is intended: with any rule set, this refuses the column values of every temporal dataset, so the Explore filter value dropdown lists nothing (4 regions with the flag off). Native Select filter option queries may run open, and this is the same kind of query. Could it get the same exemption?
There was a problem hiding this comment.
Agreed, done in 996b3b6. Column values are exempt like native Select options, so the Explore dropdown loads again.
| return self.response_403() | ||
| try: | ||
| with limit_scope(dashboard_id=dash.id): | ||
| DashboardDAO.prefetch_chart_access(dash) |
There was a problem hiding this comment.
I think the prefetch runs before dash.slices is loaded, so nothing holds those rows and each can_access_chart below loads the chart's editors and viewers again. The dashboard GET avoids it by loading the slices first, as get_charts_for_dashboard notes. Would reading slices = dash.slices before the prefetch work here?
There was a problem hiding this comment.
Done in 647b508. The slices are loaded before the prefetch, so the access check reuses them. There's a test for it.
| ranges.append((None, None, None, None, ())) | ||
|
|
||
| if query_object.time_offsets: | ||
| ranges.extend(_time_offset_ranges(query_object, filters)) |
There was a problem hiding this comment.
I think the comparison base can differ from the SQL's when chart Jinja removes a filter. With no time_range and the last temporal filter removed by get_time_filter(..., remove_filter=True), this reads the base from the copy, while processing_time_offsets uses the removed filter's value. Could the base come from the original query object here?
| is not cached. Engines whose cancel id only exists once a query is running, | ||
| such as Trino, still cannot cancel chart-data queries: their tasks stay | ||
| non-abortable, as before. | ||
| - Run `superset init` after upgrading to create the time range limits API and |
There was a problem hiding this comment.
There was a problem hiding this comment.
Added a rollback paragraph to UPDATING in ad9e66f.
…hanges Master refuses time comparisons on semantic views before any other check, so the limit tests for such comparisons now assert that refusal instead. A bad range in a comparison's re-shifted filter is reported as a QueryObjectValidationError, and the async eligibility test sets the limit value-list window its MagicMock would otherwise leave truthy.
With limits on, the picker shows its own actual time range row, so the empty range warning master added for the default row never appeared. The row now shows the same warning when the current draft's check resolved both bounds to the same instant. The limit check and Apply are unchanged.
rusackas
left a comment
There was a problem hiding this comment.
Thanks @DamianPendrak, and thanks @geido and @msyavuz for the really thorough passes already.
I think this one needs a SIP before it can go much further. It's well over 18k lines of non-test changes (plus ~53k lines of tests and fixtures), and it reaches into the chart data path, reports, async workers, Jinja macros, importers, saved dashboard and dataset metadata, a new permission and an admin page. I couldn't find a SIP or a dev@ mailing list thread for it, but holler if I missed one. A couple of the recent thread replies also mention a "product decision"... it'd be great for calls like that to happen somewhere the community can weigh in, and a SIP is the place for it. Happy to help with the process.
Once there's agreement on the approach, I'd love to see this land as a series of smaller PRs (e.g. policy and enforcement on the backend first, then Explore, then dashboards). I don't think anyone can meaningfully review this much in one go.
Also, sharded-frontend-tests is failing on the new ExploreViewContainer.timeRangeLimits.focus.test.tsx (the Retry focus case).
A successful policy refresh was judged by the previous check’s unavailable result, so the focus intent was dropped.
Reuse the copy clamp for inherited import rules and fit native time defaults after attaching the imported charts. Copies also refuse a clamp that would leave both look-back and look-forward at zero.
…ashboard
A dashboard report's time range value now uses the limits of the
dashboard's own filter bar: the dashboard's time range limits and the
datasets of the charts in the filter's scope that the report renders,
loaded from the existing dashboard endpoints. The rendered charts follow
the tab and anchor rule the save check uses; a shared fixture runs the
same cases through both. With limits on, the picker hides "No filter",
shows the limit line and refuses an out-of-limit draft, and a stored
value that breaks the limits is flagged under the field with the filter
bar's text. Limits that can't be loaded or come back incomplete, a
dataset policy that failed and a rendered chart without a known
datasource show the dashboard's unavailable alert with Retry instead of
the picker. Each time filter row gets its own picker name. Alerts, and
the flag off, keep the picker as it was.
A refused save gives each reason once. The 422 keeps its shape
({"message": {"extra": [...]}}); the reason alone when every chart in
scope gives the same one, else each reason after the names of its charts.
… import A dashboard copy or import whose time ranges no longer fit the time range limits now stores nothing and answers 422 with the list of changes it would make: stale dashboard rules rewritten to the admin limit and Time Range filter defaults fitted to the limits. Save as and the dashboard import dialog show the list and offer to adjust or cancel. API callers apply the listed changes by sending the request again with adjust_time_ranges set to true; the CLI import commands take --adjust-time-ranges. The applied changes are the listed ones, computed by the same code. With the feature flag off nothing changes.
…ng dashboard The first import over an existing dashboard fits its stale rule to the admin limit, so the next import of the same file differed from the stored value and was refused. An import over an existing dashboard, live or archived, matched by UUID or slug, now fits every rule looser than the admin limit and asks for consent, also when the dashboard has no stored rule. An import that creates a new dashboard still refuses a looser rule. The legacy importer does the same.
…ect list A numeric Range filter's min and max query read all the data. It now reads the same window as a Select filter's option list when it has no time range of its own, and a range it carries is kept and checked as before.
The "Pre-filter available values" time range picker in filter settings ignored the time range limits. It now gets the limits like a Time Range filter's default: it offers no "No filter", and a range past the limits shows the reason under the field and blocks Save.
…t renders A triggered alert that attaches a chart or dashboard rendered it without the time range check reports get, so a PNG alert stayed in Working and a CSV alert failed with a generic message. The alert now runs the same check before it renders and fails with the same reason. An alert that doesn't trigger, or that attaches nothing, isn't checked.
…a/p1-kuz-150 # Conflicts: # tests/unit_tests/datasets/commands/importers/v1/import_test.py # tests/unit_tests/views/datasource/views_test.py
…cleanup Removing a native filter drops its id from the dependent filters, which the MCP tool then sends as modified. The time range limits check refused the whole removal when such a dependent Time Range filter held a default the current limits no longer allow, though its default was unchanged.
Flattening the Range filter suite off describe left the required range cascade clear test inside the test above it, so Jest fails the outer test with "Tests cannot be nested". Close the outer test before it, as the two were siblings inside the describe.







SUMMARY
Add time range limits for chart queries: a longest range (
max_span), earliest start (max_look_back), and latest end (max_look_forward). Deployment config sets the global policy; dataset and dashboard editors can add stricter limits. The strictest applicable rule wins.TIME_RANGE_LIMITSis off by default. With it on, the server checks before cache lookup, async execution, or SQL. An out-of-range or unbounded chart query returns HTTP 400 withTIME_RANGE_LIMIT_ERROR(issue 1042); an invalid applicable stored policy fails closed with HTTP 503. Charts on datasets or semantic views with no temporal column run unchanged, even when a policy is invalid.superset export-example), which leaves out the data of limited datasets. Reports and alerts with a refused chart send nothing and fail with the time range reason. Async tasks recheck before SQL.time_range_limitskey behave as before. Dashboard values are still checked for shape (400 on writes, 422 on imports, 500 on an asset bundle import), but not for units or strictness; dataset values aren't checked, as on master. Review stored policies before turning the flag on; invalid applicable policies then fail closed. An older version without this feature answers 400 "Unknown field" when a dashboard with a storedtime_range_limitskey is saved, so remove the key before rolling back (see UPDATING).adjust_time_rangesand the listed changes' fingerprint (CLI:--adjust-time-ranges). A default that doesn't fit becomes a rolling range of the allowed length (e.g. "Last 14 days"). MCPduplicate_dashboardreturns the list as its error. Stricter rules and the source dashboard are never changed. A new dashboard with a looser rule is refused with 422, and so is a copy or import that would leave look-back and look-forward both at 0, or whose Time Range default can't fit any rolling range.Shared-code changes:
ImportExportMixinfind-existing lookup helpers centralize matching for import validation, including existing rows that a policy may overwrite.common/utils/time_range_utils.pyso query building and limit checks use the same offset handling.url_param,get_filters/filter_values,get_time_filter) read the query the check validated, through a newget_form_data(checked=True)parameter, as the async worker already does. Plainget_form_data()is unchanged.buildV1ChartDataPayloadtakes an optionalcachedChanges. When a caller passesextras.cachedChanges, the Table and AG GridcachedBuildQuerywrappers read that cache and leave their own alone; everything else is as on master. Explore's time range check uses it, so it never uses up the table's reset to the first page.Upgrade: Run
superset initto register the newTimeRangeLimitspermission and admin menu item. No database migration is required.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
TESTING INSTRUCTIONS
superset_config.py, enableFEATURE_FLAGS["TIME_RANGE_LIMITS"] = Trueand setTIME_RANGE_LIMITS_GLOBAL = {"schema_version": 1, "max_span": {"quantity": 3, "time_grain": "P1M"}, "max_look_back": {"quantity": 13, "time_grain": "P1M"}, "max_look_forward": {"quantity": 0, "time_grain": "P1D"}}. Restart Superset and runsuperset init.POLICY_UNAVAILABLE. Turn the flag off and confirm chart queries are unaffected, the time range limits endpoints return 404, and a dashboard save with"time_range_limits": "junk"returns 400.adjust_time_rangesreturns 422 with the list.pytest tests/unit_tests/utils/test_time_range_enforcement.py tests/unit_tests/utils/test_time_range_limits.py tests/unit_tests/utils/test_time_range_save_check.py tests/integration_tests/time_range_limits_tests.py. Run focused frontend tests fromsuperset-frontend:npm run test -- timeRangeLimits.test.ts TimeRangeLimitsSection.test.tsx TimeRangeLimits.test.tsx.ADDITIONAL INFORMATION
TIME_RANGE_LIMITS