Repository navigation
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. |
c7a6548 to
a45d99f
Compare
e51df8a to
240191d
Compare
a45d99f to
0b835a9
Compare
240191d to
de8d5b7
Compare
| before enabling a mapping on a production dataset. | ||
|
|
||
| Related: a predicate like `dt_epoch >= X` also drops rows where `dt_epoch` is `NULL`. | ||
| Partition keys in Hive and Impala are non-null by construction, so this is accepted rather |
There was a problem hiding this comment.
Hive and Impala both support special partitions for NULL partition-key values. A mapped filter such as event_time >= ... then appends dt_epoch >= ... and drops those matching rows, so this feature can return an incomplete chart result. Should this explicitly reject/handle NULL partition values (and update the documentation) rather than assert they cannot occur?
|
The current documentation for partition filter mapping does not explicitly address NULL partition-key values. Given that Hive and Impala treat NULLs as special partitions, and that appending a predicate like |
0b835a9 to
a2d7cb3
Compare
de8d5b7 to
42d68c0
Compare
| sampleValues: sampleValuesFor(item), | ||
| operator: previewOperatorFor(item), | ||
| isMonotonic, | ||
| enabled: state === 'mapped', |
There was a problem hiding this comment.
Suggestion: Every mapped row sends previews after debounce, including invalid transforms; the backend consumes its rate-limit budget before validation, so repeated typing can block later valid previews. [performance]
Assessment: 🟠 Major · 🔁 Occurrence: Sometimes
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionMappingSection.tsx
**Line:** 86:86
**Comment:**
*Performance: Every mapped row sends previews after debounce, including invalid transforms; the backend consumes its rate-limit budget before validation, so repeated typing can block later valid previews.
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| partition_mapped_column: columnName | ||
| ? prev.partition_mapped_column | ||
| : null, |
There was a problem hiding this comment.
Suggestion: Changing the partition column preserves an explicit mapped column even when both names match, creating a self-mapping that backend validation rejects. [incorrect condition logic]
Assessment: 🟠 Major · 🔁 Occurrence: Sometimes
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx
**Line:** 1311:1313
**Comment:**
*Incorrect Condition Logic: Changing the partition column preserves an explicit mapped column even when both names match, creating a self-mapping that backend validation rejects.
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| predicates = build_mirrored_predicates( | ||
| datasource, mapping, [(operator, value)], errors=errors | ||
| ) |
There was a problem hiding this comment.
Suggestion: Preview accepts TEMPORAL_RANGE, but this call sends it to a comparison handler that raises ValueError, causing the endpoint to return 500. [api mismatch]
Assessment: 🟠 Major · 🔁 Occurrence: Sometimes
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset/connectors/sqla/partition_mapping.py
**Line:** 821:823
**Comment:**
*Api Mismatch: Preview accepts `TEMPORAL_RANGE`, but this call sends it to a comparison handler that raises `ValueError`, causing the endpoint to return 500.
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 fixThere was a problem hiding this comment.
TEMPORAL_RANGE is allowed by the preview schema, but this path forwards the single transformed value to handle_comparison_filter, whose base implementation only handles scalar comparison operators and raises ValueError for TEMPORAL_RANGE. Should the preview either reject this operator or build both range bounds with the same temporal-range path as chart queries?
There was a problem hiding this comment.
Yes, this is a valid issue. TEMPORAL_RANGE is included in MIRRORABLE_OPERATORS, but this preview path supplies a scalar value:
[(operator, value)]build_mirrored_predicates eventually routes that to the scalar comparison handler, where TEMPORAL_RANGE raises ValueError, resulting in a 500.
The preview should not advertise an operator it cannot construct correctly. Since the current payload and UI provide only one sample bound, the minimal safe fix is to reject TEMPORAL_RANGE for preview requests with a validation response, or remove it from the preview schema’s OneOf list while leaving it supported by the chart-query path.
If preview support is required, it must instead accept two bounds and pass them through the same temporal-range representation used by chart queries; it should not call the scalar comparison handler. Add a regression test asserting that a TEMPORAL_RANGE preview cannot produce a 500.
There was a problem hiding this comment.
✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of cf75501.
Added an early mapping.mirrors(operator) guard that returns a structured invalid response before calling build_mirrored_predicates for unsupported operators.
If that's not right, unresolve this thread and CodeAnt will leave it open.
There was a problem hiding this comment.
✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 1229c46.
Range-style operators are rejected with a structured invalid-operator response before reaching build_mirrored_predicates, preventing TEMPORAL_RANGE from being sent to the comparison handler.
If that's not right, unresolve this thread and CodeAnt will leave it open.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## hughhhh/pfm-3-preview-and-editor #43891 +/- ##
==================================================================
Coverage 81.74% 81.74%
==================================================================
Files 2979 2983 +4
Lines 182109 182363 +254
Branches 42084 42178 +94
==================================================================
+ Hits 148860 149071 +211
- Misses 30512 30556 +44
+ Partials 2737 2736 -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:
|
a2d7cb3 to
44d5539
Compare
42d68c0 to
0118629
Compare
44d5539 to
1da5aa6
Compare
0118629 to
e68a360
Compare
1da5aa6 to
dd8b41e
Compare
e68a360 to
f79a91f
Compare
PR #43891 added `partition_value_transform_default` on the engine spec so the dataset editor can pre-fill a temporal column's value transform, and set it only on Hive/Impala (Spark inheriting from Hive). That gates *which transform to suggest*, not *whether the feature applies to the engine at all*: the editor still offered the "Partition column" dropdown on every database whenever the `PARTITION_FILTER_MAPPING` flag was on, and `validate_partition_mapping` only used the engine to check the transform text parsed for that dialect -- never to reject the feature on engines where partition-directory pruning does not exist. Mirroring a filter onto a physical partition column only prunes work on engines whose tables are laid out as partition directories (Hive-family). On Postgres the concept does not exist; on Snowflake micro-partitions are automatic and invisible; BigQuery and Redshift use different mechanisms entirely. There the dropdown is clutter that maps to nothing. Add a `supports_partition_filter_mapping` capability flag on `BaseEngineSpec` (default `False`), set `True` on the same two specs that carry `partition_value_transform_default` -- `HiveEngineSpec` and `ImpalaEngineSpec`, with `SparkEngineSpec` inheriting it from Hive. Thread it to the client the same way the transform default travels: a read-only `SqlaTable` property sourced from the engine spec, exposed through `DatasetRestApi.show_columns`, and added to the frontend datasource types. The editor's `partitionMappingEnabled` gate now also requires the flag, so the partition mapping UI only appears on an engine that advertises it. Scope is kept identical to the existing stack: Hive/Impala/Spark only. Presto/Trino and everything else stay `False`, matching the decision that left `partition_value_transform_default` off Presto. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@hughhhh good to see the mirrors(operator) guard landed for the TEMPORAL_RANGE bug, codeant looks satisfied. @sadpandajoe's NULL-partition-key question is still open though, along with codeant's debounce and self-mapping catches. |
sha174n
left a comment
There was a problem hiding this comment.
Scoped review — backend only. I read the ~300 non-test Python lines (partition_mapping.py, datasets/api.py, datasets/schemas.py, the engine specs) and none of the ~7.7k lines of editor UI or the docs page. Not an approval of the PR; someone should own the frontend separately.
The security posture on the backend holds up. What I checked:
The preview endpoint is properly gated. PARTITION_FILTER_MAPPING feature flag, @protect(), then security_manager.raise_for_editorship(dataset) → 403, then a per-user-per-dataset rate limit. Editorship rather than mere read access is the right bar, given the endpoint's job is to run a caller-supplied expression against the analytics database.
Preview doesn't bypass the save path's denylist. This was the thing I most wanted to rule out — a preview endpoint that evaluates transforms under weaker validation than save would be an unrestricted SQL-evaluation primitive for anyone with dataset edit rights. It isn't: preview_partition_mapping calls the same validate_partition_mapping and returns on the first issue before anything reaches the engine, so the Tier-1 checks (columns exist, no self-mapping, no Jinja, no NON_DETERMINISTIC_FUNCTIONS) apply identically to both paths. Sharing build_mirrored_predicates with the query path so preview can't drift from what a chart emits is the same instinct applied to correctness, and it's the right one.
One hardening note, not a blocker. _run_probe now appends str(ex) to the errors sink, and preview_partition_mapping surfaces errors[0] straight into the response:
_("The transform could not be evaluated against the database: %(reason)s", reason=errors[0])Raw DBAPI exception text is not always just a message — depending on driver it can carry the DSN, host, port, or internal paths. I don't think this is an escalation: the caller is already a dataset editor who can evaluate arbitrary transforms against that engine, so they have strictly more powerful primitives available. But this is the one place the codebase deliberately routes a driver exception to a UI string, and the reason the feature exists (a misspelled function name that sqlglot parses happily) is served just as well by a truncated or first-line-only message. Worth considering scrubbing it, or capping its length.
The _position_in_transform unwinding — subtracting the SELECT prefix and the per-placeholder :value/NULL length delta so reported positions match what the owner typed — is a nice detail, and the comment explaining that the drift is worst at the end of the string is the kind of thing that stops someone "simplifying" it later.
|
Nice, looks like the NULL-partition docs, the preview debounce, and the self-mapping catch all landed with tests since I last looked. Still stacked on #43759 though, so this can't merge till that one does. Thank you for stickin' with 'em :D |
| const transform = value ?? ''; | ||
| const isTemporal = Boolean(item?.is_dttm); | ||
|
|
||
| const { preview, loading } = usePartitionMappingPreview({ |
There was a problem hiding this comment.
In usePartitionMappingPreview.ts, neither the success handler (.then(), line 93) nor the early-return guard (lines 66–74) checks whether the in-flight request is still the current one, so the preview panel this returns can get stuck or show stale data. If transformCanPreview starts failing while a request is pending (for example the owner clears the transform), the pending request's .catch/.finally both skip setLoading(false) because controller.signal.aborted is already true, and the next effect run's early return never resets loading either — the spinner then stays on indefinitely. Separately, .then() doesn't check controller.signal.aborted, so if an older, now-superseded request resolves after a newer one — plausible since this hits a live warehouse query — it overwrites the current preview with stale data, including showing "Valid" for a transform the input no longer contains. Could both paths track whether their request is still the latest before touching state?
| const transform = value ?? ''; | ||
| const isTemporal = Boolean(item?.is_dttm); | ||
|
|
||
| const { preview, loading } = usePartitionMappingPreview({ |
There was a problem hiding this comment.
usePartitionMappingPreview.ts uses a literal NUL byte as an array delimiter (sampleValues.join('\0') at line 62, sampleKey.split('\0') at line 87). That's why git diff/GitHub render that file as "Binary files differ" instead of text — every future change to it will show the same way, hiding it from normal diff and blame tooling. Could the delimiter be something that isn't a valid string character in practice (or the round-trip through a string key be dropped in favor of the array itself)?
| {t( | ||
| 'Filters on this column are mirrored onto the partition column.', | ||
| )}{' '} | ||
| <Typography.Link |
There was a problem hiding this comment.
None of the four new Typography.Link action triggers this section introduces have an href — here, and also at line 171 and line 200 in this file, plus PartitionMappingSection.tsx:106. Ant Design's Typography.Link without href renders an <a> that's outside the natural tab order and doesn't respond to Enter/Space, so a keyboard-only user can't reach "Map a different column instead", "Customize the value transform", "Map a column", or "Move mapping to this column". Remove mapping a few lines below already uses a link-styled Button instead — could these four follow the same pattern?
| } | ||
| const mappedColumn = columns.find( | ||
| column => column.column_name === mappedColumnName, | ||
| ); |
There was a problem hiding this comment.
This treats any non-blank partition_value_transform as an active mapping, but the backend's own partition_filter_mapping_summary (models.py) requires is_transform_active() — parseable and passing the denylist — before calling a mapping active. PartitionColumnFields.tsx uses this frontend isActive to choose between the green "Filters on X will automatically apply..." message and the "No value transform is set" warning, so a transform that's non-blank but fails to parse gets the confident green message even though the backend won't actually mirror it. Should this call the same validation the backend uses (or read the mapping's actual computed active state) instead of just checking for non-blank text?
| properties: | ||
| valid: | ||
| type: boolean | ||
| sample_input: |
There was a problem hiding this comment.
The response schema documents sample_input, emitted_predicate, error, and valid, but not reason — even though every invalid result this endpoint returns now includes one of parse, validation, operator, engine, or unconfigured (see preview_partition_mapping in partition_mapping.py), and the frontend's PartitionMappingPreview type reads and branches on it. Generated OpenAPI clients have no typed way to see this field. Could reason be added to the response schema here?
| means "now" on Hive and Impala. The one-argument `unix_timestamp(:value)` is fine. | ||
|
|
||
| Session-dependent behaviour that Superset cannot detect is still your responsibility: | ||
| `unix_timestamp()` is timezone-dependent on Hive and Impala, so if the evaluating session and |
There was a problem hiding this comment.
This names the zero-argument unix_timestamp(), but the paragraph right above says that form is rejected at save time — the one that can actually be saved and used is unix_timestamp(:value), which is the one whose result actually depends on session timezone. Could the warning name unix_timestamp(:value) instead, so it's clear which usable transform needs care?
| operator=operator.value, | ||
| ), | ||
| } | ||
|
|
There was a problem hiding this comment.
mapping.mirrors(operator) only rejects TEMPORAL_RANGE when the transform is not declared monotonic. When is_monotonic=True, a TEMPORAL_RANGE preview passes this guard, then falls into value = sample_values[0] (a single scalar, since only IN takes the list branch) and reaches handle_comparison_filter(col, TEMPORAL_RANGE, value), which has no case for that operator and raises ValueError — a 500 with a valid transform and a monotonic declaration. Could the guard also reject TEMPORAL_RANGE here (or build the two-bound request build_mirrored_predicates actually needs for a range) regardless of monotonicity?
| return False | ||
| if contains_jinja(transform): | ||
| return False | ||
| return is_parseable(transform, engine) |
There was a problem hiding this comment.
This query-time gate checks blank/placeholder/Jinja/parseable but not non-deterministic functions, while is_transform_active() (used for the UI's active/inactive indicator) also runs that check. CreateDatasetCommand/import do not validate the mapping at all, so an imported or pre-existing dataset can carry a transform like rand() + 0*:value: the editor reports it inactive, but this function still lets it reach the probe, so a chart query mirrors a fresh random value every time and can silently exclude matching rows. Should this call the same validate_transform/non-deterministic check is_transform_active uses?
| len(row), | ||
| len(distinct), | ||
| ) | ||
| return None |
There was a problem hiding this comment.
Nothing here rejects a transform whose SELECT list has more than one expression (e.g. lower(:value), :value). For an IN filter with N distinct values, build_probe_sql compiles N pairs of columns into one row, but this only ever reads row.iloc[0..len(distinct)-1] — the first len(distinct) columns of the first value's own row, not one column per distinct value. For a 2-value IN filter that becomes both returned values coming from the first input, silently dropping the second value's partition from the mirrored predicate and excluding rows that should match. Should a transform be rejected at validation time unless it parses as exactly one SELECT-list expression?
| if backend.add(key, 1, timeout=PREVIEW_RATE_LIMIT_WINDOW): | ||
| # First request of a fresh window, and the only one that dates it. | ||
| return True | ||
| used = backend.inc(key) |
There was a problem hiding this comment.
add and inc aren't atomic together: if the key is about to expire, add can return False (key still present) but then expire before this inc runs. Redis's INCR on a now-missing key creates it fresh with no TTL, so the counter keeps incrementing but never expires again. Once it's past limit, _consume_preview_rate_limit returns False permanently for that user/dataset instead of resetting after PREVIEW_RATE_LIMIT_WINDOW — previews stay 429'd until the cache entry is evicted or manually cleared. Could inc re-apply the window TTL only when it creates the key (e.g. an atomic Lua INCR+EXPIRE NX, or falling back to add again on a None/1 result)?
| ``:value`` placeholder before it can be bound. | ||
| """ | ||
| selections = [] | ||
| for index, value in enumerate(values): |
There was a problem hiding this comment.
Only :value is bound as a parameter here — the rest of transform is raw SQL text that gets compiled and executed as-is, and nothing in validate_transform/validate_partition_mapping rejects a transform containing a subquery (only blank/Jinja/parseable/placeholder/non-determinism are checked). A user with dataset-editor access but no read access to another table could set a transform such as (SELECT secret FROM protected_table LIMIT 1) || :value and read the result back via this endpoint's sample_input/emitted_predicate. Note the save path (UpdateDatasetCommand._validate_partition_mapping) does run the transform through validate_stored_expression — the same subquery/RLS gate calculated columns get — but preview evaluates a not-yet-saved candidate transform without ever going through that gate. Could preview apply the same validate_stored_expression check before probing?
| $ref: '#/components/responses/401' | ||
| 404: | ||
| $ref: '#/components/responses/404' | ||
| 429: |
There was a problem hiding this comment.
The 429 response here points at #/components/responses/400 ("Bad request"), but a throttled caller gets a rate-limit response, not a bad-request one — and the endpoint's own editorship check can also return a 403, which isn't documented in this response list at all. A generated API client would show a throttled caller as having sent bad input, and wouldn't know a 403 is possible. Could the 429 reference the correct shared response and a 403 entry be added?
| export function sampleValuesFor( | ||
| column: PartitionMappingColumn | undefined, | ||
| ): string[] { | ||
| return column?.is_dttm ? ['2026-01-15 00:00:00'] : ['US', 'CA']; |
There was a problem hiding this comment.
Non-temporal columns always get sample values ['US', 'CA'] regardless of the mapped column's actual type. For an integer-typed mapped column with a transform like CAST(:value AS INTEGER), these string samples fail to evaluate and preview reports a transform error, even though a real IN (2025, 2026) filter on that column would mirror successfully. Could the sample values be derived from the column's declared type instead of a temporal/non-temporal binary?
| 'Filters on this column are mirrored onto the partition column.', | ||
| )}{' '} | ||
| <Typography.Link | ||
| onClick={() => onNavigateToColumn(mappedColumn)} |
There was a problem hiding this comment.
This navigates to mappedColumn — the column currently mapped — not a different one. When the effective mapped column is the implicit default datetime column and it also equals the partition column (the self-mapping state backend validation rejects), this link opens the partition column's own row, whose mapping section is defined to show nothing for the partition column itself. The one guided path meant to help an owner out of this state leads to a dead end with no visible way to actually pick a different column. Could this navigate to a column other than the currently-resolved mapped column, or surface the column picker directly, when the mapped column equals the partition column?
| // would otherwise open somewhere below the fold, which reads as the link | ||
| // having done nothing. | ||
| setColumnSearchTerm(columnName); | ||
| setColumnToReveal(columnName); |
There was a problem hiding this comment.
Clicking a "customize the value transform"-style link for the same column twice in a row (e.g. after manually collapsing that row) calls this with the same columnName both times. Nothing resets columnToReveal (or columnSearchTerm) to null when a row collapses, so the second call sets setColumnToReveal(columnName) to the value it already holds — React bails out of the state update, the consumer relying on expandedColumnName={columnToReveal} never sees a change, and the row does not re-expand. Could columnToReveal be reset (e.g. to null) on collapse, or could this force a re-expansion even when the target column is unchanged?
| # Configure and validate a mapping from a dataset's business column onto its | ||
| # physical partition column, so engines that require an explicit partition | ||
| # predicate can prune. For now this only stores and validates the mapping; | ||
| # no query consumer emits the mirrored predicate yet. |
There was a problem hiding this comment.
This says "no query consumer emits the mirrored predicate yet," but this PR wires resolve_partition_mapping/build_mirrored_predicates into the chart-query path (superset/models/helpers.py), so enabling the flag now does change query SQL, not just storage/validation. An operator enabling this flag on the strength of this description would be surprised that charts start mirroring filters immediately. Could the comment be updated to reflect that the query path is now wired up?
Fourth of four. Covers configuration, the operator matrix, and the parts a reader will reasonably assume the feature covers but it does not. Two sections carry most of the weight. "Transform preserves ordering" explains why the checkbox exists at all, with `hour()` as the worked example -- it is a perfectly reasonable partition transform and mirroring a range through it returns wrong numbers. And "The assumption this rests on" states the invariant plainly: Superset emits a predicate on the partition column standing in for one on the mapped column, which is only valid if the ETL keeps the two in step. Superset cannot verify that, and when it breaks the result is quietly wrong charts rather than an error, so the docs say so rather than letting people discover it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Fifth of the stack, and the one that makes the feature reachable: until now a
mapping could only be configured with a PUT, and the preview endpoint had no
caller. Implements wireframes 1a, 1b, 1c, 1g and 1h.
Two places where the spec and the merged backend disagreed, resolved rather
than papered over:
- The mockups have no monotonicity control, but the query path only mirrors
ranges when the transform is declared order-preserving -- so 1d/1e's own
example, a time range producing two `dt_epoch` bounds, was unreachable
through the UI. Adds the checkbox the shipped docs already describe.
- `unix_timestamp(:value)` is Hive syntax and the PRD asks for it as the
temporal default. Pre-filling it on Postgres or BigQuery would hand the
owner an expression that cannot parse, so the default moves to the engine
spec (`partition_value_transform_default`, set on Hive/Impala/Spark) and
engines without one offer no pre-fill at all.
The preview endpoint now takes `sample_values` plus an operator and builds its
predicate with `build_mirrored_predicates` -- the same function the query path
uses -- so what the panel shows is what a chart emits, `IN` included. It also
accepts a candidate `partition_column`: the editor previews a mapping the owner
has not saved yet, and a preview that requires saving first is not a preview.
Failed probes now carry the engine's own message through an opt-in `errors`
sink, because sqlglot parses unknown functions happily and a misspelled one is
otherwise reported as an unexplained blank.
Two read-path gaps this uncovered, both silent:
- `columns.partition_value_transform` and its monotonic flag were in the
model, the export fields and the PUT schema but not in `show_columns`, so
the editor reopened a saved mapping as if it had none -- and the next save
wrote that emptiness back. Related-model fields have to be listed in
`show_columns`, not only `show_select_columns`.
- `partition_value_transform_default` needed the same treatment to reach the
pre-fill.
Both are now pinned by tests in the serialization suite, whose whole premise is
that a field missing from any one layer is dropped without a sound.
`Field` gains an opt-in `passItemToControl`: the row-expand section keys off the
whole column record, not just the transform it edits, and handing an unknown
`item` prop to every TextControl and Select was not worth the convenience.
Verified against a partitioned table in Docker: the editor configures a mapping,
"View query" carries `dt_epoch >= ... AND dt_epoch < ...` alongside the
`event_time` bounds, a non-temporal `country -> region_key` mapping emits
`region_key IN ('us', 'ca')`, and with the flag off the controls disappear, the
preview endpoint 404s and no predicate is added.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three defects a second pass through the running editor turned up, none of
which unit tests could have caught -- they are all layout or heuristic.
The engine's own error text is the longest string this panel ever shows and its
length is not ours to control. Two things clipped it:
- An expanded antd row sizes to its content, so a long line widened the whole
table and pushed the alert and "Remove mapping" past the modal edge. A zero
max-width on the expanded cell is the standard fix.
- Alert descriptions are `white-space: nowrap` in this theme, so no amount of
width would have wrapped one; the message truncated mid-sentence at
"...stays inactive u". Overridden locally, along with `min-width: 0` on the
flex children, which otherwise refuse to shrink.
Separately, "Map a column →" navigated to whichever column sorted first, which
on the demo table was `revenue` -- inviting the owner to mirror a currency
metric onto a region key. It now prefers a temporal column, since a time range
is what the feature exists for, and falls back to the first non-partition
column only when there is no temporal one.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The page sent operators to the dataset editor's **Settings** tab. The controls are in the **Columns** tab, under Default Column Settings -- alongside the default datetime and currency code selects, which is also where wireframe 1a puts them. Someone following this would have clicked Settings and found nothing. Also says where the "Transform preserves ordering" checkbox is, which the page described without ever locating. Found by walking the page against the running editor rather than re-reading it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`SqlaTable` was imported but never referenced, failing ruff's F401 and with it the pre-commit job. Nothing in the module uses the name, including in string annotations. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two failures, two causes. oxfmt (frontend) failed on six files this branch touches. Master's copy of DatasourceEditor.tsx is already oxfmt-clean, so the formatting drift came from this branch's edits, not from upstream. custom rules (frontend) rejected the untranslated `placeholder` on the value transform input. Wrapped in t(): the rule does honour an `i18n/no-untranslated-string` disable, but nothing in the codebase uses one, so convention wins over being the first. This also repointed the partition migration's down_revision at 93d1b4a76c02, which a linear history has no room for: the migration already chains onto 95d8a99c822e, and master built that revision on top of 93d1b4a76c02, so repointing there would recreate the second Alembic head it was meant to remove. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…g editor The editor UI and preview endpoint added 44 translatable strings without a babel extraction run, so they could not reach any catalog and CI's babel-extract check failed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…iews Three review findings on the editor PR. The docs claimed partition keys on Hive and Impala are non-null by construction and that rows in a NULL partition were therefore accepted as lost. Both halves are wrong. A dynamic-partition insert parks rows whose key was NULL in `__HIVE_DEFAULT_PARTITION__`, which reads back as NULL, and the code has defended against it since the query rewrite landed -- the emitted clause is `(preds) OR partition_col IS NULL`. The page now describes what actually ships. While in there, the grain behaviour added on the query-rewrite branch is documented too: grained ranges mirror with widened bounds, grained `=` and `IN` do not, and operator-supplied grains do not. The NULL escape had one test, on the equality path. It now also pins the `IN` path, that the escape wraps the whole conjunction rather than sitting between two bounds -- `a AND (b OR p IS NULL)` would drop every NULL-partition row on `a` -- and that a mapping emitting no predicates emits no bare `IS NULL`, which would keep only the rows the escape exists to spare. The preview hook fired on every settled keystroke, including for transforms that cannot possibly work: no `:value`, a Jinja block, or a column mapped onto itself. Those spend the per-user preview budget that the throttle then denies to the transform the owner eventually finishes writing. `transformCanPreview` gates them out. It is deliberately a necessary condition and not a parser -- an unparseable transform still goes to the server, which stays the authority. Choosing a partition column that matched an existing explicit mapped column kept the override, producing a self-mapping the backend rejects as blocking -- reachable in one click, since the picker offers every column. The rule now lives in `nextMappedColumnOverride` next to the other mapping helpers, where it is named and directly testable rather than an inline ternary. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…itor-ui # Conflicts: # superset/connectors/sqla/partition_mapping.py # superset/datasets/schemas.py # tests/unit_tests/datasets/partition_mapping_preview_test.py
Review findings on the editor-UI PR. **The preview hook was a binary file.** It used a literal NUL byte as an array delimiter, so git classified it as binary -- the only binary file in the whole stack's diff -- and `git diff`, blame and GitHub's review view all showed "Binary files differ" instead of code. The delimiter existed to give the effect a stable dependency for an array that is rebuilt on every render; a `useMemo` keyed on the serialized form does that without leaving the file unreviewable. **The preview panel could stick or lie.** Clearing the transform while a request was in flight left the spinner on for good: the pending request's own handlers see the abort and stop short of clearing `loading`, and the next effect run returned early without clearing it either. And the success handler never asked whether its request was still the current one, so a superseded response could overwrite the live preview -- it reports "Valid" for text no longer in the box. Both now check a request id, claimed before the early return as well. **Four actions were mouse-only.** antd's `Typography.Link` with no `href` renders an `<a>` outside the tab order that ignores Enter, so "Map a different column instead", "Customize the value transform", "Map a column" and "Move mapping to this column" were unreachable by keyboard. They are link-styled `Button`s now, the pattern `Remove mapping` already used. **"Map a different column instead" could dead-end.** It navigates to the currently-mapped column, which is where the picker lives -- but when that column *is* the partition column (the self-mapping the backend rejects, reachable in one click because the picker offers every column) that row renders no mapping section at all. The one guided way out of the broken state led nowhere. It now offers a column that is not the partition column. **The green alert overstated the mapping.** `mappingIsActive` tested for non-blank text, while the backend's summary requires a transform that can actually mirror, so a transform with no `:value` to substitute -- or one carrying Jinja -- got "filters will automatically apply", telling an owner their queries prune when they do not. It now shares `transformCanPreview`'s conditions; parseability and the function denylist still need a SQL parser, so those stay the server's call and are reported at the field. **Preview samples ignored the column's type.** Every non-temporal column was evaluated at `'US'`, so a mapped integer column with `CAST(:value AS INTEGER)` came back as a transform error -- the preview reporting a fault in its own sample data for a mapping an `IN (2025, 2026)` filter would mirror fine. **A repeat click did nothing.** `columnToReveal` held a column name, so clicking the same link twice -- after collapsing the row by hand in between -- set the state to the value it already had, React bailed out of the render, and nothing downstream saw a change. It carries a nonce now, because the request is an event rather than a state. **TEMPORAL_RANGE could 500 the endpoint.** `mirrors()` admits it when the transform is declared monotonic, and the single sample value then reached the scalar comparison handler, which has no case for a range and raises. The query path never hits this because it decomposes a time range into two bounds first; the preview request carries sample values and has no range to decompose. It is out of `PREVIEWABLE_OPERATORS` and out of the request schema, and the editor never asked for it -- `previewOperatorFor` sends `>=`, `=` or `IN`. Also: `reason` is documented in the response schema (every invalid result carries one and the editor branches on it), and the timezone warning in the docs now names `unix_timestamp(:value)` rather than the zero-argument form the paragraph above it says is rejected at save time. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Closing in favour of #43870, which now carries the whole feature against Nothing is lost. The commits are unchanged and still in #43870's history, so this stage is still reviewable on its own, and the 22 unresolved comments from this PR are reproduced in an inventory comment there — each with a link back to the original thread and the commit that addressed it. They were all addressed in the review pass of 2026-10-01; they show as unresolved here only because the threads were never clicked shut. @sadpandajoe @rusackas — sorry for the churn. If you would rather keep reviewing stage by stage, say so and I will reopen; the branches are all still there. |
SUMMARY
Fourth of the partition filter mapping stack, and the PR that makes the feature reachable. Until now a mapping could only be configured with a
PUT /api/v1/dataset/<pk>, and the preview endpoint added in the previous PR had no caller — its own commit message says the visual controls "are not in this PR". This implements them: wireframes 1a, 1b, 1c, 1g, 1h.Includes the documentation (
docs/admin_docs/configuration/partition-filter-mapping.mdx, originally #43760, now closed). The two are combined deliberately: that page tells operators to pick a Partition column in the dataset editor and refers to "the editor's preview panel", so shipping it ahead of these controls would publish instructions for things that do not exist yet. Merging them together removes that window entirely.Stacked on
hughhhh/pfm-3-preview-and-editor. Review the compare against pfm-3 rather than the diff against master.What's new in the editor
partition_mapped_column ?? main_dttm_col, and a second select would let it drift from the default datetime column silently.PARTITIONtag, and defaultsIs filterable/Is dimensionoff — still manually togglable.Two places the spec and the merged backend disagreed
dt_epochbounds) was unreachable through the UI. This adds the Transform preserves ordering checkbox that the docs in pfm-4 already describe.unix_timestamp(:value)as the temporal default, but that's Hive syntax and would not parse on Postgres, Trino or BigQuery. The default moves to the engine spec (partition_value_transform_default, set on Hive/Impala/Spark); engines without one offer no pre-fill rather than a wrong one.Backend changes
sample_values+ anoperatorand builds its predicate withbuild_mirrored_predicates— the same function the query path uses — so what the panel shows is what a chart emits,INincluded. It also accepts a candidatepartition_column, because the editor previews a mapping the owner hasn't saved yet and a preview that requires saving first isn't a preview.errorssink (the hot query path passes nothing and stays silent). sqlglot parses unknown functions happily, so a misspelled one is an engine error and was previously reported as an unexplained blank.SELECTprefix and the:value→NULLsubstitution so it points at what the owner actually typed.Two silent read-path bugs this uncovered
Neither was reachable from unit tests; both needed the running app.
columns.partition_value_transformand its monotonic flag were in the model, the export fields and the PUT schema but not inshow_columns— so the editor reopened a saved mapping as if it had none, and the next save wrote that emptiness back. Related-model fields must be listed inshow_columns, not onlyshow_select_columns(columns.advanced_data_typeis in both for the same reason).partition_value_transform_defaultneeded the same treatment to reach the pre-fill.Both are now pinned by tests in
partition_mapping_serialization_test.py, whose whole premise is that a field missing from any one layer is dropped without a sound.One small shared change:
Fieldgains an opt-inpassItemToControl. The row-expand section keys off the whole column record, not just the transform it edits, and handing an unknownitemprop to everyTextControlandSelectwasn't worth the convenience.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Screenshots captured during validation; attaching separately.
1aPartition column + Maps to partition, and1bthe mutedPARTITIONrow1cRow expand with transform, ordering checkbox and a valid preview1cParse error state — only one of preview/error is ever visible1gPartition column set with nothing mapped1hNon-temporalcountry → region_keyTESTING INSTRUCTIONS
Automated:
1800backend unit tests and225frontend Datasource tests pass;tsc,ruff,ruff formatandoxlintare clean (oxlint warnings insrc/components/Datasourcego 32 → 30, since the duplicated column-name renderer was folded into one helper).Manually, against a real engine:
FEATURE_FLAGS = {"PARTITION_FILTER_MAPPING": True}.dt_epoch. Confirm Maps to partition showsevent_timetagged Default datetime column, and thatdt_epoch's row is muted with aPARTITIONtag and its toggles off.cast(extract(epoch from cast(:value as timestamp)) as bigint)and check Transform preserves ordering. The preview should readevent_time >= '2026-01-15 00:00:00'→dt_epoch >= 1768435200. Unchecking it drops the preview back to=.lower(:value))) → Can't parse transform with a position, and the preview panel disappears.region_key, move the mapping tocountry, setlower(:value). Preview showscountry IN ('US', 'CA')→region_key IN ('us', 'ca'), and a chart filtered oncountryemitsAND region_key IN ('us', 'ca').Known limitation, not introduced here: SQLAlchemy's
text()misparses Postgres::casts, so a transform written as:value::timestampleaves the placeholder unbound. This comes frombuild_probe_sqlin pfm-2 and is harmless on Hive/Impala, which have no::syntax — the ANSIcast(:value as timestamp)form works. Worth a follow-up for Postgres/Redshift users.ADDITIONAL INFORMATION
PARTITION_FILTER_MAPPING🤖 Generated with Claude Code
How Has This Been Tested?
Validated against the full stack under Docker (Flask + Celery worker + Postgres + Redis) serving this branch, driving the real browser. Two rounds: once during implementation, once after pushing — the second round found the three defects fixed in
8f873f3.Bring-up (non-default ports, since 8088/5432 are usually taken by another stack):
Fixture — a table where the partition key really is the transform of the business column, so a mirrored predicate is verifiably correct rather than merely present:
The walk (543 rows, 5 columns):
00-before-no-partition-column.png— Partition columnNone, no Maps to partition, all rows normaldt_epoch01-1a-1b-partition-column-selected.png— Maps to partition →event_timetagged Default datetime column;dt_epochrow muted withPARTITIONtag and its three toggles off, every other row untouched02-1c-row-expand-valid-preview.png— previewevent_time >= '2026-01-15 00:00:00'→dt_epoch >= 1768435200. Unticking drops it back to=lower(:value)))03-1c-parse-error.png— Can't parse transform, syntax error at position 14, preview hidden (only one of preview/error is ever visible)04-1g-partition-column-no-mapping.png—No mappingchip, Map a column →, and the scan-every-partition warningregion_key, move the mapping tocountry,lower(:value)05-1h-non-temporal-mapping.png— required asterisk,country IN ('US', 'CA')→region_key IN ('us', 'ca')Screenshots live in
.context/pfm-ui-screenshots/(gitignored) and are attached above.Non-visual proof. The generated SQL, via
/api/v1/chart/datawithresult_type: query— the same SQL the View query panel renders:1782864000is exactly2026-07-01T00:00:00Z, matching how the fixture populatesdt_epoch— so the pruning predicate selects the same rows rather than merely looking plausible.Negative case — with
PARTITION_FILTER_MAPPINGoff: the Partition column field, thePARTITIONtag and the muted row all disappear, the preview endpoint returns 404, and the same query emits noregion_keypredicate at all.Also verified the engine-specific default behaves: on Postgres
partition_value_transform_defaultisNone, so the editor offers no pre-fill rather than a Hive expression that would not parse.What the browser pass caught that tests did not
Worth calling out, since it's the argument for doing this at all:
show_columns, so reopening showed an empty transform and the next save persisted that emptiness. Fixed, and pinned by tests.8f873f3: the engine's error text clipped mid-sentence (expanded antd rows size to content, and alert descriptions arenowrapin this theme), and Map a column → suggestingrevenue— inviting an owner to mirror a currency metric onto a region key.Additionally verified (third pass)
GET /api/v1/explore/?datasource_type=table&datasource_id=…) carriesregion_key: {groupby: false, filterable: false}while every other column staystrue;dndControls.tsxbuilds the Dimensions options fromcolumns.filter(c => c.groupby)and the Filters options fromcolumns.filter(c => c.filterable). Both ends verified against the running app. I could not get the drag-and-drop popover itself to open under automation, so this rests on the payload plus Superset's existing filter rather than on my having seen the rendered list.region_keyfrom the physical table with the mapping live, then hit Sync columns from source: three toasts fire —Metadata has been synced,The partition filter mapping was cleared: its column is gone,Removed 1 column from the virtual dataset— the Columns badge goes 5 → 4, and Partition column resets toNonewith Maps to partition gone.06-sync-clears-dangling-mapping.pngcaptures the resulting state (the toasts auto-dismiss before a screenshot lands; the strings above are read straight from the DOM).Wireframe 1e in the real panel
View query shows the mirrored predicate as an ordinary
WHEREclause, exactly as 1e specifies — captured in07-1e-view-query-mirrored-predicate.png:Docs verified by building the site
yarn buildindocs/succeeds (EXIT=0) and emitsbuild/admin-docs/configuration/partition-filter-mapping/index.html. Served and walked in a browser: title, breadcrumb, sidebar placement under Configuration, the:::cautionadmonition, all three tables and the right-hand TOC render correctly (10-docs-page.png). The newPARTITION_FILTER_MAPPINGentry also surfaces on the Feature Flags page with its default and description, since that page readsstatic/feature-flags.json.This mattered:
superset-docs-verify.ymlrunsyarn buildon every PR, and this page carries an ASF license header as an HTML comment (<!-- -->), which MDX v3 does not accept as a comment. Only two otheradmin_docspages do the same and neither is on master, so nothing proved it was safe. It builds.One factual error the walk caught (fixed in
e51df8a): the page sent operators to the dataset editor's Settings tab. The controls are in the Columns tab under Default Column Settings — confirmed by tab-by-tab visibility checks in the running editor (visible under Columns and Calculated columns, not Settings), and it is where wireframe 1a puts them. Someone following the page would have clicked Settings and found nothing. The same commit says where the Transform preserves ordering checkbox lives, which the page described without ever locating.Known limitation (pre-existing, not introduced here)
SQLAlchemy's
text()misparses Postgres::casts, so a transform written:value::timestampleaves the placeholder unbound and the probe fails with "This text() construct doesn't define a bound parameter named 'value'". It comes frombuild_probe_sqlin pfm-2 and is harmless on Hive/Impala, which have no::syntax. The ANSI formcast(:value as timestamp)works and is what the walk above uses. Worth a follow-up for Postgres/Redshift.