Repository navigation
feat(datasets): partition filter mapping - #43870
Conversation
|
Bito Automatic Review Skipped - Branch Excluded |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
949b0af to
413e5c6
Compare
e51df8a to
240191d
Compare
413e5c6 to
6142a9e
Compare
240191d to
de8d5b7
Compare
6142a9e to
eeb4218
Compare
de8d5b7 to
42d68c0
Compare
eeb4218 to
2e57d43
Compare
|
The flagged issue is correct: the To resolve this, you should ensure the indicator only renders when the Proposed FixUpdate // In OptionControlLabel component
{partitionMapping?.active && (
<PartitionPruningIndicator mapping={partitionMapping} />
)}This ensures the glyph only appears when the mapping is active, preventing misleading indicators for inactive or unrelated filters. Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well? superset-frontend/src/explore/components/controls/OptionControls/index.tsx |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #43870 +/- ##
==========================================
+ Coverage 84.44% 84.53% +0.09%
==========================================
Files 3059 3067 +8
Lines 202769 204894 +2125
Branches 47512 48128 +616
==========================================
+ Hits 171223 173217 +1994
- Misses 28289 28376 +87
- Partials 3257 3301 +44
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:
|
42d68c0 to
0118629
Compare
2e57d43 to
6132109
Compare
0118629 to
e68a360
Compare
6132109 to
63316d4
Compare
…migration The popover test added in #44843 asserted that a config stored under the display alias `Time` is ignored. #44955 deliberately reads legacy `Time`-keyed configs and migrates them onto `__timestamp`, so the assertion is stale. Assert the intended behaviour instead: the legacy config is read back and an edit is saved under `__timestamp`. Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 34d5617)
…er range
- An Oracle DATE keeps the time of day, but Superset maps it to sa.Date, so
the days-only exemption in the temporal literal path skipped the
precision check and wrote 06:30 as TO_DATE('2026-01-12', 'YYYY-MM-DD').
Whether a key holds only days is now read from the database's own
dialect, which makes Oracle's DATE a DateTime; the mirror is declined
where the literal would drop the time, and an exact midnight still
mirrors.
- A chart hands the transform a temporal value as text (simple filters) or
as a datetime the dialect writes as a typed literal (time ranges). The
preview probed only the text, so TO_DATE(:value, fmt) previewed valid on
Oracle while every time range landed in year 0012. A temporal sample is
now previewed as a time range sends it, the text shape is probed too, and
the preview refuses a transform whose two answers differ.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hard Each case mounts the whole dataset modal, edits two collections and saves. That takes about 8s locally, the same on this branch and on master, but it crossed the global 20s testTimeout on loaded CI shards. Raise it for this file to 60s, as other heavy modal suites do with jest.setTimeout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| ): | ||
| # The format is unreachable in `dttm_sql_literal` for this column, | ||
| # so reproducing it here would describe a different bound. | ||
| return dttm |
There was a problem hiding this comment.
When the engine answers convert_dttm for a DATE column, the filter compares against the date-only literal ('2026-01-01' on SQLite), but this returns the widened datetime, which the probe binds as '2026-01-01 00:00:00.000000'. With a DATE column event_date, a text partition key p = CAST(event_date AS TEXT) and a monotonic CAST(:value AS TEXT) transform, a January range mirrors as p >= '2026-01-01 00:00:00.000000', which sorts above the key '2026-01-01' and drops every January 1 row the filter keeps. Could the probe use the same rendering the engine gives the original bound (for example the date itself when the literal carries no time of day)?
There was a problem hiding this comment.
{ai generated comment}
Thanks, fixed in d913891. When the engine renders the bound and the column holds only days, _mirror_probe_value now returns dttm.date() at midnight, so the probe binds the same day the filter compares. Columns that store a time of day keep the datetime: TIMESTAMP, and Oracle DATE (via holds_days_only, which reads the dialect's own type). With your example run against a real SQLite file, a January range now mirrors as p >= '2026-01-01' AND p <= '2026-02-01' and keeps every January 1 row.
One note: at the head you reviewed, this case no longer dropped rows. The new two-shapes check saw the timestamp answer (…00:00:00.000000) disagree with the text one (…00:00:00) and declined the mirror, so results were correct but the pruning was lost. With the date probe the two forms agree, so the mirror is kept. Covered by test_a_midnight_bound_on_a_date_column_is_probed_as_the_day.
| - escaping | ||
| - transform_escaping | ||
| - engine | ||
| - type |
There was a problem hiding this comment.
_preview_probe() also returns HTTP 200 with reason: "shape" when the range and text probes emit different predicates (for example an Oracle TO_DATE(:value, 'YYYY-MM-DD HH24:MI:SS') transform on a temporal sample), but shape is not in this enum, the generated openapi.json entry, or the TypeScript union. A client generated from the spec with a strict enum would reject that response. Could shape be added to all three and the spec regenerated?
| enforced on every write rather than only inside `UpdateDatasetCommand`. A | ||
| transform arriving on any other column is dropped -- by the deprecated | ||
| `POST /datasource/save/`, and by `PUT /api/v1/dataset/<pk>` and dataset import | ||
| even when `PARTITION_FILTER_MAPPING` is off. An API client that was storing one there |
There was a problem hiding this comment.
This says a transform sent on a non-mapped column is dropped and the field reads null afterwards, including with the flag off, and partition-filter-mapping.mdx repeats it. But drop_unmapped_value_transforms() deliberately keeps an unchanged echo of the stored value (stored_by_name), which is exactly what a GET-then-PUT, a legacy save, or an overwrite import sends. An operator who follows this note to clear a parked transform by re-saving the dataset will still find it there. Could both places state the unchanged-echo exception and say how to clear it (send null)?
geido
left a comment
There was a problem hiding this comment.
Thanks for the Oracle fixes, CAST(:value AS DATE) checks out here. I did a last pass on 81c5e54 against six engines: with the flag off I found no regressions against master, and with it on I found one new issue on ClickHouse (inline), while the TO_DATE thread still reproduces from the editor.
| seen.add(key) | ||
| deduped.append((operator, value)) | ||
|
|
||
| return build_mirrored_predicates(cast("SqlaTable", self), mapping, deduped) |
There was a problem hiding this comment.
I think this can now fail every chart filtering the mapped column on ClickHouse. _holds_days_only (from 6f37942) calls .get on dialect.ischema_names, a list in clickhouse-connect 1.10/1.11, so toDate(:value) onto a Date key returns 500 with the flag on (200 off) and the preview shows "Fatal error". Could the lookup accept only a Mapping, and this call fail open, as the docs say?
There was a problem hiding this comment.
Thanks, my bug. Fixed in 83f0660f2a: the lookup only reads a Mapping and treats any failure as "may hold a time of day", and the chart path (and preview) now fail open on any error building the mirror.
…ral shapes on charts - _holds_days_only read dialect.ischema_names with .get, but clickhouse-connect 1.10/1.11 make it a list, so every chart filtering the mapped column returned 500 and the preview showed a fatal error. It now reads only a Mapping and treats any lookup failure as "may hold a time of day". The chart path's mirror build and the preview also fail open: an unexpected error costs the pruning, not the chart. - The text-vs-timestamp check moves from the preview into build_mirrored_predicates, so charts run it too. evaluate_transform takes a text_answers sink and asks each date or timestamp as text in the same round trip (one probe per query still), retrying with the typed values alone if the text is refused. The text bypasses the mirror request gates, which declined it before the comparison on a TIMESTAMP column at a time of day, so the preview said valid for Oracle's TO_DATE(:value, fmt). Co-Authored-By: Claude Opus 5.5 <[email protected]>
| continue | ||
| # `bool` is checked separately because it satisfies every numeric | ||
| # `isinstance` there is while rendering as `true`. | ||
| held = isinstance(value, allowed) and ( |
There was a problem hiding this comment.
A probe result of inf or nan passes this type check, so a transform such as CASE WHEN :value = 0 THEN CAST('Infinity' AS DOUBLE PRECISION) ELSE :value END on a PostgreSQL double partition column returns inf for n = 0. The mirrored predicate is then rendered as p = inf, which the database rejects (column "inf" does not exist), while preview still reports the mapping as valid, so the chart fails instead of just losing pruning. Should a non-finite float be treated as not held here so the mirror declines?
| app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False | ||
|
|
||
| with app.app_context(): | ||
| with patch(PROBE, side_effect=AssertionError("probe must not run")): |
There was a problem hiding this comment.
Since the mirror builder now swallows any exception and returns [], the AssertionError raised by this booby-trapped probe is caught too, so the test passes whether or not the probe runs. If the chart path regressed and probed with the flag off, "dt_epoch" not in sql would still hold. Could this bind the patch (as probe) and assert probe.assert_not_called() after _query()? The same pattern is at the other side_effect=AssertionError(...) tests in this file.
aminghadersohi
left a comment
There was a problem hiding this comment.
The new typed-vs-text probe check leaves the stored mirror verdict wrong in both directions.
| if isinstance(value, date) and not is_unmirrorable(value) | ||
| ] | ||
| if indexes: | ||
| combined = evaluate_transform( |
There was a problem hiding this comment.
On Oracle, CAST(:value AS DATE) and TRUNC(:value, 'HH') evaluate a typed bound but fail on its text form (ORA-01861, ORA-01722), so every time-range chart reruns this failing probe (failures are not cached) and stores evaluable=false, hiding the glyph while queries still prune.
| if not _bounds_are_ordered(evaluated, spans): | ||
| return [] | ||
|
|
||
| if _declined_for_reading_by_type(evaluated, text_answers, shape_errors): |
There was a problem hiding this comment.
When this declines (Oracle TO_DATE(:value, fmt) puts the typed bound in year 0012), the stored verdict stays evaluable=true, so the time-range glyph keeps promising pruning that no time-range query gets.
sha174n
left a comment
There was a problem hiding this comment.
LGTM — the mirror is a strictly-narrowing redundant predicate; round-trip checks on the probe look thorough.
- DrillDetailPane.test.tsx and tests/unit_tests/views/datasource/test_utils.py: both sides appended tests (this branch's lower-bound Samples paging, master's sunburst chart-type tests from #45571); kept both. - superset/views/datasource/utils.py: #45571 retyped get_samples' payload from SamplesPayloadSchema to dict[str, Any] and dropped the import; the branch's _count_star_query_context now takes the same type, and the test that needed a type: ignore for the old one no longer does. - Translations: took master's catalogs and re-ran scripts/translations/babel_update.sh on a tracked-files snapshot of the merged tree; against master only this branch's msgids and each file's POT-Creation-Date change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| parsed = make_url_safe(db_obj.sqlalchemy_uri) | ||
| if parsed.password and parsed.password != PASSWORD_MASK: | ||
| db_obj.set_sqlalchemy_uri(db_obj.sqlalchemy_uri) | ||
| imported.extend(db_obj.tables or []) |
There was a problem hiding this comment.
db_obj.tables is every dataset attached to the database, not only the ones this bundle imported, so _repair_partition_mappings() also runs on unrelated datasets. Importing a legacy bundle that contains only dataset B therefore sends dataset A through clear_unmapped_partition_transforms, which drops A's parked transform and monotonicity declaration (for example one saved while the feature flag was off). Should this collect only the datasets the import actually wrote, rather than expanding the database relationship?
| return True | ||
|
|
||
| rendered = _compile_literal(sa.literal(value), dialect) | ||
| if rendered == f"'{value}'" and "'" not in value and "\\" not in value: |
There was a problem hiding this comment.
A probe result containing a NUL passes this short-circuit, since it has no quote or backslash and renders as '<value>' unchanged. On SQLite, mapping text column c to text partition column p with :value || char(0) returns 'a\x00' for c = 'a'; the guard accepts it, and the mirrored statement then fails with ProgrammingError: the query contains a null character, so the chart errors instead of just losing pruning. Should a value containing \x00 be treated as not round-tripping here?
| transform, | ||
| values + [_as_filter_text(values[index]) for index in indexes], | ||
| ) | ||
| if combined is not None: |
There was a problem hiding this comment.
I think a transform that refuses the text still slips through here. TO_DATE(:value, 'YYYY-MM-DD') onto a day key raises ORA-01830 on '2026-01-12 06:30:00', so this falls back to the typed answer (year 0012) unchecked: the preview says Valid and the range returns 0 rows (48 with the flag off), Last week too. Could a refused text form decline the temporal mirror instead?
There was a problem hiding this comment.
{ai generated comment}
Thanks, agreed. Fixed in 09c728c5c4: a temporal value whose text form the transform refuses now gets no mirror (the typed answer can't be checked without it). Charts still do one probe, and the preview re-asks the typed value alone to say the text form was refused. Engines that write timestamps as plain text are unaffected.
…refused TO_DATE(:value, 'YYYY-MM-DD') onto an Oracle day key raises ORA-01830 on '2026-01-12 06:30:00', so the combined probe failed and fell back to the typed values alone -- whose answer, year 0012, then went unchecked: the preview said valid and every time range (Last week too) returned 0 rows. A transform that cannot read the instant as text cannot be checked, so it now gets no mirror; the query path stops at its one round trip, and the preview asks the typed values alone only to say why. Engines that write a timestamp as plain text send the same SQL either way and are unaffected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Translations: tr/messages.po conflicted. Took master's catalogs and re-ran scripts/translations/babel_update.sh on a tracked-files snapshot of the merged tree, which also picks up the new partition-mapping message; no master msgid is lost. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The filter compares a DATE column against the day itself ('2026-01-01' on
SQLite, DATE '2026-01-01' on Trino), but the probe was handed the midnight
datetime, which binds as '2026-01-01 00:00:00.000000'. On a text key
p = CAST(event_date AS TEXT) mirrored by CAST(:value AS TEXT), that asked
for p >= '2026-01-01 00:00:00.000000' and sorted above every January 1
key. The two-shapes check now declines that mirror, so results were
already correct, but the mapping lost its pruning.
_mirror_probe_value now returns the date when the engine renders the bound
and the column holds only days (holds_days_only, made public for this, so
an Oracle DATE, which stores the time of day, keeps its datetime).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nstant Oracle refuses the text '2026-01-12 06:30:00' under its default NLS_DATE_FORMAT for every transform, correct or not, so declining on the refusal alone (09c728c) cost Oracle every time-range mirror: TRUNC(:value) onto a day key previewed "not valid" and never pruned. When the text is refused, the typed values are now asked alone (a second round trip, only on that path) and kept where each answer is a date or timestamp within a year and a day of the instant it was asked about, which is the widest any time bucket can sit. TO_DATE(:value, 'YYYY-MM-DD')'s year-0015 misreading and numeric answers still decline. Also rewords the refusal message, which read "the timestamp's cannot be checked". Co-Authored-By: Claude Opus 5.5 <[email protected]>
geido
left a comment
There was a problem hiding this comment.
Thanks for all the iterations here! I re-ran the full matrix on 738a278 across six engines and everything we flagged checks out, flag on and off. One thing before merging: the required unit tests fail because messages.pot is missing the new string, so it needs regenerating.


SUMMARY
Adds partition filter mapping: a dataset owner names one partition column and one business column whose filters are mirrored onto it, and every query then carries an equivalent predicate on the partition column, so chart authors change nothing and queries prune. Behind
PARTITION_FILTER_MAPPING, off by default.Datasets on Hadoop-family engines are commonly partitioned on a technical column — an epoch integer, a lowercased region key — that no analyst would filter on. Unless a query carries a predicate on that column the engine scans every partition, and the only workaround today is hand-writing the predicate as custom SQL in a virtual dataset, which pushes a performance concern onto every chart author and takes the dataset out of the physical/syncable path.
Storage
Four columns, following the
always_filter_main_dttm/currency_code_columnprecedent for "a dataset-level setting that names a column":tables.partition_columntables.partition_mapped_columnNULLfollowsmain_dttm_coltable_columns.partition_value_transform:valueexpressiontable_columns.partition_transform_is_monotonicThe effective mapped column is
partition_mapped_column or main_dttm_col, so "re-pointing the default datetime column moves the mapping with it, unless overridden" falls out of the model rather than needing code. A JSON blob insidetables.extrawas considered and rejected:extrais a user-editable free-text box,buildExtraJsonObjectrebuildscolumn.extrafrom a hardcoded key list on every save, and there is no validation layer for it. (#44816 explored that route and is closed; if the migration is the blocker, that is the conversation to reopen, not this storage choice.)Operator safety is the heart of the query rewrite
A mirrored predicate
P2may only beAND-ed onto a query when the originalP1implies it. Getting this wrong is silent — it shows up as wrong chart numbers, not an error.col = v,col IN (…)Tis a functioncol >=,>,<,<=,TEMPORAL_RANGETis monotoniccol != v,NOT IN,LIKE,IS NULL, …Negations are never safe because
Tneed not be injective:lower(:value)withcountry != 'US'mirrors toregion_key != 'us', excluding rows whosecountryis already lowercase'us'— rows the original filter keeps.Monotonicity is declared, not inferred. An earlier draft inferred it from the column type; that is wrong on partition schemes people actually use —
hour(:value),date_format(:value, 'dd')anddayofweek(:value)are all reasonable transforms on aTIMESTAMPand none preserve ordering.T(lower) <= T(upper)is asserted at runtime as a backstop.Three more properties the rewrite holds to:
NULLpartition value isNULL, so the emitted clause is(preds) OR partition_col IS NULL— Hive and Impala park rows with a NULL key in__HIVE_DEFAULT_PARTITION__, and those rows must survive. A grained range compares the truncated column, so its raw bounds do not describe the rows it keeps; those mirror by widening both bounds one bucket, and grained=/INdo not mirror at all.get_time_filterapplied the dataset timezone and legacy hour offset internally; that is extracted intoadjust_time_boundsrather than duplicated.PARTITION_FILTER_MAPPINGmust be a static boolean.FEATURE_FLAGSalso accepts per-request callables, and since the mapping only enters the cache key when active, a flag resolving per user would let a flag-off user read a cache entry written from pruned SQL by a flag-on user.The dataset editor
A Partition column select in the Columns tab's Default Column Settings, plus a read-only computed Maps to partition — deliberately not a peer dropdown, since it reflects
partition_mapped_column ?? main_dttm_coland a second select would let it drift silently. The partition column's row is muted, carries aPARTITIONtag, and defaultsIs filterable/Is dimensionoff. A Partition filter mapping section in the row expand has three states: the mapped column holds the transform, every other column offers to take the mapping over, the partition column itself shows nothing.A live Preview panel shows sample input → emitted predicate, backed by
POST /api/v1/dataset/<pk>/partition_mapping/preview/:It fires a real warehouse query from a text input, so the order of its guards is the point: validation and the stored-expression policy run before anything reaches the engine (so a half-typed transform costs zero queries, and a transform cannot smuggle a subquery past the gate that governs every other stored expression); it shares the evaluator and probe cache with the query path, so preview and runtime cannot drift; and it is rate-limited per user and dataset in a fixed window, because client debouncing is a courtesy, not a guard.
Two places the spec and the backend disagreed, resolved in the UI's favour:
dt_epochbounds) was unreachable. Hence Transform preserves ordering.unix_timestamp(:value)as the temporal default, but that is Hive syntax and would not parse on Postgres, Trino or BigQuery. The default moves to the engine spec (partition_value_transform_default); engines without one offer no pre-fill rather than a wrong one.The Explore indicator
A small glyph on any filter whose column the dataset mirrors, with the tooltip "This filter is also applied to a partition column for faster queries. See 'View query' for the generated SQL." Chart authors configure nothing and ideally never learn the word "partition"; the indicator exists only to explain the speed-up and point at the SQL.
It shows only where the query path really does mirror — it checks the operator against the set the server computes from declared monotonicity, and excludes grained filters, the
<NULL>sentinel, and a time range with no temporal column selected. The one gap is deliberate and commented: a virtual dataset's Jinjaget_filters(..., remove_filter=True)makes the backend skip both the filter and its mirror, butremoved_filtersis built during query generation and is not inform_data, so the browser cannot know. The glyph is advisory; "View query" is the authority.partitionColumnalready exists on these components as the unrelated Prestolatest_partitionfeature, so the prop ispartitionMappingthroughout — two meanings of one word, one prop apart, is not worth the saving.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
See the screenshots on the closed PRs, which remain valid: the editor controls and preview panel on #43891, and the indicator on #43870 —
02-adhoc-operator-matrix.pngthere is the clearest single frame, one chart carrying eight filters with the glyph on exactly the two that mirror.TESTING INSTRUCTIONS
pytest tests/unit_tests/connectors/sqla/partition_mapping_test.py \ tests/unit_tests/models/partition_mirroring_test.py \ tests/unit_tests/datasets/partition_mapping_preview_test.py \ tests/unit_tests/datasets/partition_mapping_serialization_test.py \ tests/unit_tests/dao/dataset_test.py \ tests/unit_tests/commands/dataset/ \ tests/unit_tests/datasets/commands/importers/v1/import_test.py \ tests/unit_tests/sql/parse_tests.py cd superset-frontend && npm run test -- \ src/components/Datasource \ src/explore/components/PartitionPruningIndicator \ packages/superset-ui-chart-controls/test/shared-controlsManual, in a dev stack with
PARTITION_FILTER_MAPPING: True, against a physical table partitioned on a technical column:PARTITIONtag, and drops out of Explore's dimension and filter pickers.unix_timestamp(:value) and confirm it reports a parse error without hitting the warehouse.!=on the mapped column) and confirm no glyph and no mirrored predicate.ADDITIONAL INFORMATION
PARTITION_FILTER_MAPPING(off by default)ADD COLUMNs with no backfill and no index, plus the matching Continuum shadow columns so dataset version history and restore keep working; effectively instant on Postgres/MySQL, no downtime expected