Skip to content

feat(datasets): add partition mapping preview endpoint and editor plumbing - #43759

Closed
hughhhh wants to merge 8 commits into
hughhhh/pfm-2-query-rewritefrom
hughhhh/pfm-3-preview-and-editor
Closed

hughhhh wants to merge 8 commits into
hughhhh/pfm-2-query-rewritefrom
hughhhh/pfm-3-preview-and-editor

Conversation

@hughhhh

@hughhhh hughhhh commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

Stack (review bottom-up):

  1. feat(datasets): add partition filter mapping model, migration and validation #43757 — model, migration, serialization, validation
  2. feat(datasets): mirror filters onto the partition column at query time #43758 — query rewrite + evaluator
  3. feat(datasets): add partition mapping preview endpoint and editor plumbing #43759 — preview endpoint + editor plumbing
  4. docs: document partition filter mapping #43760 — docs

SUMMARY

Third of four. Adds the server-side half of the dataset editor experience, plus the frontend types and save-payload wiring the editor UI will need.

The preview endpoint shows an owner the predicate their transform would emit:

POST /api/v1/dataset/<pk>/partition_mapping/preview/
  { "mapped_column": "event_time",
    "value_transform": "unix_timestamp(:value)",
    "sample_value": "2026-01-15 00:00:00" }
→ { "valid": true, "emitted_predicate": "dt_epoch >= 1768435200" }

It fires a real warehouse query from a text input, so the order of its guards is the point:

  1. Validate first, probe second. Parse and denylist checks run before anything reaches the engine, so a half-typed transform — by definition unparseable, and most of what a text input produces — costs zero queries.
  2. Shared cache. Same evaluator and probe cache as the query path, so preview and runtime cannot drift and a previewed transform warms the chart path for free.
  3. Server-side rate limit, per user and dataset. Debouncing on the client is a courtesy, not a guard: a held keydown, or a few owners with the editor open, is sustained load on a production cluster.

Guarded by @protect() plus per-object raise_for_editorship, and gated on the feature flag.

Frontend — plumbing, not UI:

  • partition_column / partition_mapped_column in the dataset save payload, and partition_value_transform / partition_transform_is_monotonic in the per-column whitelist. Anything outside that whitelist is silently dropped on save, so this is load-bearing.
  • clearDanglingPartitionMapping, applied after a metadata sync. The backend clears a dangling mapping too on the authoritative override_columns path (PR 1); this keeps the editor's own state honest in between, so an owner is never looking at a mapping pointing at a column the table no longer has.
  • A test pinning down that a sync preserves a hand-written transform — the failure the whitelist and the merge logic could each cause quietly.

The visual editor controls — the partition column select, the PARTITION tag, the row-expand section with the transform input and "Transform preserves ordering" checkbox — are not in this PR.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — no rendered UI in this PR.

TESTING INSTRUCTIONS

pytest tests/unit_tests/datasets/partition_mapping_preview_test.py
cd superset-frontend && npx jest src/components/Datasource

The preview tests assert the guard ordering, not just the outcomes: several stub the probe with side_effect=AssertionError("probe must not run"), so they fail if validation ever stops short-circuiting ahead of the engine call.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: PARTITION_FILTER_MAPPING (off by default)
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
  • Introduces new feature or API
  • Removes existing feature or API

@bito-code-review

bito-code-review Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped - Branch Excluded

Bito didn't auto-review because the source or target branch is excluded from automatic reviews.
No action is needed if you didn't intend for the agent to review it. Otherwise, to manually trigger a review, type /review in a comment and save.
You can change the branch exclusion settings here, or contact your Bito workspace admin at [email protected].

@codecov

codecov Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.25000% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.74%. Comparing base (74564b9) to head (fb1ba20).

Files with missing lines Patch % Lines
superset/datasets/api.py 85.00% 5 Missing and 1 partial ⚠️
...e/components/DatasourceEditor/DatasourceEditor.tsx 40.00% 3 Missing ⚠️
superset/connectors/sqla/partition_mapping.py 87.50% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@                     Coverage Diff                      @@
##           hughhhh/pfm-2-query-rewrite   #43759   +/-   ##
============================================================
  Coverage                        81.74%   81.74%           
============================================================
  Files                             2979     2979           
  Lines                           182029   182109   +80     
  Branches                         42066    42084   +18     
============================================================
+ Hits                            148794   148860   +66     
- Misses                           30500    30512   +12     
- Partials                          2735     2737    +2     
Flag Coverage Δ
hive 36.61% <29.50%> (-0.01%) ⬇️
javascript 77.12% <84.21%> (-0.01%) ⬇️
mysql 55.69% <29.50%> (-0.02%) ⬇️
postgres 55.69% <29.50%> (-0.03%) ⬇️
presto 38.52% <29.50%> (-0.01%) ⬇️
python 85.92% <86.88%> (+<0.01%) ⬆️
sqlite 55.42% <29.50%> (-0.02%) ⬇️
unit 78.89% <86.88%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@netlify

netlify Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit ffa098b
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6abf0174b496de000849729b
😎 Deploy Preview https://deploy-preview-43759--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 3, 2026
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 3d7615a to 3c96ebe Compare September 4, 2026 21:02
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from c7a6548 to a45d99f Compare September 4, 2026 21:03
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 3c96ebe to 218eec5 Compare September 4, 2026 21:13
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from a45d99f to 0b835a9 Compare September 4, 2026 21:13
@github-actions github-actions Bot added doc Namespace | Anything related to documentation and removed requires:rebase Requires rebasing on top of current master labels Sep 4, 2026
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 218eec5 to 0927c4a Compare September 5, 2026 02:48
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from 0b835a9 to a2d7cb3 Compare September 5, 2026 02:48
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 0927c4a to 7ad9986 Compare September 5, 2026 03:06
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from a2d7cb3 to 44d5539 Compare September 5, 2026 03:06
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 7ad9986 to d33754b Compare September 5, 2026 03:17
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from 44d5539 to 1da5aa6 Compare September 5, 2026 03:17
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from d33754b to 9c5b4a6 Compare September 5, 2026 16:10
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from 1da5aa6 to dd8b41e Compare September 5, 2026 16:10
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from 9c5b4a6 to e14aad3 Compare September 5, 2026 18:08
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from dd8b41e to 9062521 Compare September 5, 2026 18:08
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from e14aad3 to c90781e Compare September 5, 2026 18:20
@hughhhh
hughhhh force-pushed the hughhhh/pfm-3-preview-and-editor branch from 9062521 to 935ac3b Compare September 5, 2026 18:20
@hughhhh
hughhhh force-pushed the hughhhh/pfm-2-query-rewrite branch from c90781e to 21693ee Compare September 5, 2026 20:23
ever have been right for strings.
"""
return str(
sa.literal(value).compile(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A successful integer probe returns a NumPy scalar from the pandas row, but sa.literal() cannot infer its SQL type, so the canonical epoch transform raises CompileError here and preview returns 500. Could the probed scalar be normalized or rendered with an explicit type, with coverage through a real DataFrame result rather than a mocked Python int?

is_active: column.is_active,
is_dttm: column.is_dttm,
python_date_format: column.python_date_format || null,
partition_value_transform: column.partition_value_transform || null,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Dataset List editor loads /api/v1/dataset/{id}, whose column response omits both transform fields, so an unrelated save now sends null/false and overwrites an existing mapping, silently disabling pruning. Could those fields be included in the GET response and the GET→edit→PUT round trip be covered?

):
return {"valid": False, "error": str(issue.message)}

evaluated = evaluate_transform(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A dataset editor without SQL Lab can submit a scalar subquery as the unsaved transform and receive its warehouse result in emitted_predicate; this path never applies the subquery/RLS checks used for stored expressions. Could the shared SQL policy and row-level-security validation run before the probe, so preview cannot read rows the editor is not authorized to retrieve?

Comment thread superset/datasets/api.py
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the Redis key expires after add() returns false but before inc(), INCR recreates it without a TTL. That counter then never resets, so this user eventually gets permanent 429s for the dataset; could creation/increment/expiry be atomic or missing expiry be repaired?

hughhhh and others added 8 commits October 1, 2026 09:23
…mbing

Third of four. Adds the server-side half of the dataset editor experience: an
endpoint that shows an owner the predicate their transform would emit, plus the
frontend types and save-payload wiring the editor UI will need.

The preview endpoint fires a real warehouse query from a text input, so the
order of its guards is the point. Parse and denylist checks run before anything
reaches the engine, which means a half-typed transform -- by definition
unparseable, and most of what a text input produces -- costs zero queries. Behind
that sits the same evaluator and cache the query path uses, so preview and
runtime cannot drift and a previewed transform warms the chart path for free.
A per-user, per-dataset rate limit backs it up: debouncing on the client is a
courtesy, not a guard, and a held keydown or a few owners with the editor open
is sustained load on a production cluster.

On the frontend, this is the plumbing rather than the UI:

  - `partition_column` / `partition_mapped_column` in the dataset save payload
    and `partition_value_transform` / `partition_transform_is_monotonic` in the
    per-column whitelist. Anything outside that whitelist is silently dropped
    on save.
  - `clearDanglingPartitionMapping`, applied after a metadata sync. The backend
    clears a dangling mapping too on the authoritative `override_columns` path;
    this keeps the editor's own state honest in between, so an owner is never
    looking at a mapping that points at a column the table no longer has.
  - A test pinning down that a sync *preserves* a hand-written transform, which
    is the failure the whitelist and the merge logic could each cause quietly.

The visual editor controls (the partition column select, the PARTITION tag, the
row-expand section) are not in this PR.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ndow

Three review findings on the preview endpoint, all in the same few lines.

The throttle counted with a read-then-write pair, so concurrent previews could
each read the same sub-limit value and all reach the warehouse -- the burst the
guard exists to stop was the one case it let through. It also re-stamped the
key's expiry on every increment, making it a sliding window despite the
docstring promising a fixed one: sustained typing could keep the budget spent
indefinitely instead of recovering a minute after the burst began.

`add` then `inc` fixes both. On Redis those compile to SETNX and INCR, so the
count is atomic and INCR leaves the TTL alone -- only `add` ever dates the key.
Both calls go to the cachelib backend rather than the Flask-Caching wrapper,
which proxies `add` but not `inc`; routing `inc` through the wrapper raises
AttributeError, which the fall-open handler would have swallowed into no
throttling at all. A backend that cannot count still falls open, because
unenforceable is not the same as spent.

The preview request schema had no length bounds, so an owner could hand the
parser and the warehouse arbitrarily large input. `value_transform` is capped
at 1024 -- the stored column is Text, so this bounds the request rather than
the feature -- and the two column-ish fields at 250, matching their storage.

`_render_literal` formatted probed values by hand: quote-doubling for strings
and `str()` for everything else, so a NULL rendered as the Python repr `None`
and a date came out unquoted. Neither is SQL. It now compiles through the
dialect, the same mechanism `build_probe_sql` already uses. The partition
column is quoted with `quote_identifier` while it is being interpolated, so a
column whose name needs quoting no longer renders as invalid SQL either.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The preview endpoint and the editor plumbing introduce five user-facing
strings. On the merge-based stack they reached the catalogs inside the
`origin/master` and pfm-2 merge commits, which a linear history has no
room for, so they travel in their own commit instead -- otherwise this
branch's own babel-extract job runs against a `.pot` that lacks them.

Additions only: the five msgids propagated into all 30 catalogs, no
POT-Creation-Date churn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Four review findings on the preview PR.

**Preview skipped the stored-expression policy.** `build_probe_sql` binds
`:value` and splices the rest of the transform in as SQL text, and preview
evaluates a candidate transform that has not been saved -- so the subquery, RLS
and function-denylist gate that `UpdateDatasetCommand` applies to the *stored*
expression had a door around it. A dataset editor with no SQL Lab access could
submit `(SELECT secret FROM protected_table LIMIT 1) || :value` and read the
answer out of `emitted_predicate`. `validate_stored_expression` now runs before
the probe, inside `preview_partition_mapping` rather than at the route, so a
second caller cannot forget it.

**A probed value could not be rendered.** The probe reads its results out of a
pandas frame, so the canonical epoch transform returns a `numpy.int64` and a
temporal one a `pandas.Timestamp`. SQLAlchemy has a literal renderer for
neither: `sa.literal` infers `NullType` and raises `CompileError`, a 500 for the
most ordinary mapping there is. Normalized at the probe boundary, so the query
path gets the same treatment, with pandas' missing-value sentinels folded into
`None` -- `NaT` has no renderer either, and a transform returning nothing for an
input it cannot convert is the NULL case the mirror already admits. The tests
patch `Database.get_df` rather than `evaluate_transform`; stubbing the evaluator
hands back a plain `int` and never touches a frame, which is why this was green.

**The fixed window was not fixed.** It now comes from the key -- one bucket per
window -- rather than from the entry's lifetime, because the TTL could not carry
that promise on either backend. cachelib's generic `inc` is a read-modify-write
whose `set` restamps `CACHE_DEFAULT_TIMEOUT`, a day by default, so on SimpleCache
retrying after the budget was spent kept renewing a day-long lockout. On Redis
`INCR` leaves the TTL alone, but a key expiring between a losing `add` and the
`inc` is recreated with no TTL at all, and the owner was then 429'd permanently.
A counter that outlives its bucket is now simply never read again.

**Two API-surface fixes.** `partition_mapping_preview` was missing from
`method_permission_name`, so `@protect()` demanded a bespoke
`can_partition_mapping_preview` permission: a custom role with `can_write` could
store a mapping and not preview it. And the `429` pointed at the shared "Bad
request" response while the `403` from `raise_for_editorship` was undocumented,
so a generated client read a throttled caller as having sent bad input.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…hema

The preview request repeated the literal the typed column field and the import
schema enforce through `MAX_TRANSFORM_LENGTH`. Three copies of one number is
one rule stated three times, free to drift.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@hughhhh hughhhh mentioned this pull request Oct 2, 2026
7 of 9 tasks
@hughhhh

hughhhh commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

Closing in favour of #43870, which now carries the whole feature against master rather than the five-PR stack this was the preview endpoint and editor plumbing of.

Nothing is lost. The commits are unchanged and still in #43870's history, so this stage is still reviewable on its own, and the 6 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API doc Namespace | Anything related to documentation i18n:brazilian i18n:chinese Translation related to Chinese language i18n:czech i18n:dutch i18n:french Translation related to French language i18n:italian Translation related to Italian language i18n:japanese Translation related to Japanese language i18n:korean Translation related to Korean language i18n:latvian i18n:persian i18n:portuguese i18n:russian Translation related to Russian language i18n:slovak i18n:spanish Translation related to Spanish language i18n:traditional-chinese i18n:ukrainian i18n Namespace | Anything related to localization packages size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants