Skip to content

fix(dataset): bump changed_on on column refresh so chart cache invalidates - #43921

Merged
rusackas merged 3 commits into
apache:masterfrom
gps23:fix-dataset-refresh-cache
Sep 23, 2026
Merged

rusackas merged 3 commits into
apache:masterfrom
gps23:fix-dataset-refresh-cache

Conversation

@gps23

@gps23 gps23 commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

SUMMARY

Refreshing dataset columns from the source (fetch_metadata / "Refresh columns") mutated child TableColumn rows without writing any parent tables column, so SQLAlchemy never fired changed_on onupdate. Chart query_cache_key() includes datasource.changed_on, so a previously cached result computed against the old column type/expression could keep being served after a schema change.

This force-bumps SqlaTable.changed_on when fetch_metadata() reports added, modified (type or physical expression), or dropped physical columns — the same cache-invalidation signal DatasetDAO.update() already applies on PUT /dataset. No-op refreshes and leftover calculated columns do not bump the timestamp.

Fixes #43918.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A (backend cache-key invalidation)

TESTING INSTRUCTIONS

  • pytest tests/unit_tests/connectors/sqla/models_test.py -k fetch_metadata
  • pytest tests/integration_tests/datasets/api_tests.py -k test_dataset_item_refresh
  • In the UI: change a physical column type in the source table, click Refresh columns on the dataset, then reload a chart that uses that column and confirm the result is not served from the pre-refresh cache.

ADDITIONAL INFORMATION

Made with Cursor

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #20d433

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: ef4c137..ef4c137
    • superset/connectors/sqla/models.py
    • tests/integration_tests/datasets/api_tests.py
    • tests/unit_tests/connectors/sqla/models_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment thread superset/connectors/sqla/models.py Outdated
Comment on lines +2363 to +2364
leftover_columns = list(old_columns_by_name.values())
columns.extend([col for col in leftover_columns if col.expression])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: When a dropped physical column has an expression, this keeps its stale TableColumn row and fails to bump changed_on, so cached charts can use removed schema metadata. [stale reference]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/connectors/sqla/models.py
**Line:** 2363:2364
**Comment:**
	*Stale Reference: When a dropped physical column has an expression, this keeps its stale `TableColumn` row and fails to bump `changed_on`, so cached charts can use removed schema metadata.

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
👍 | 👎

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 39418fa.

Calculated columns with an expression are still kept on purpose (that is not schema drift for chart cache). Nested physical ROW fields also have an expression (e.g. metadata.uuid); if the source drops them we now treat those leftovers as physical: they are not re-added, delete-orphan removes the TableColumn row, and changed_on is bumped.

Plain physical columns without an expression were already left out of self.columns and orphan-deleted; changed_on already bumped for those.

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. When a physical column is dropped, the TableColumn row remains in the database because it is not explicitly removed, and the SqlaTable.changed_on timestamp is not updated, causing cached charts to rely on stale schema metadata.

The provided PR diff already implements a fix for this in superset/connectors/sqla/models.py by forcing a changed_on update when physical columns are dropped:

        # Child TableColumn rows own the FK, so mutating them (and reassigning
        # ``self.columns``) does not emit an UPDATE on this tables row.
        # AuditMixinNullable.changed_on onupdate therefore never fires, and
        # query_cache_key() keeps serving results computed against the previous
        # column definitions. Force the same bump DatasetDAO.update() applies
        # when columns are saved. See #43918.
        dropped_physical_columns = any(not col.expression for col in leftover_columns)
        if results.added or results.modified or dropped_physical_columns:
            self.changed_on = datetime.now()

This change ensures that any schema drift—whether additions, modifications, or deletions of physical columns—correctly invalidates the cache by updating the changed_on timestamp.

superset/connectors/sqla/models.py

dropped_physical_columns = any(not col.expression for col in leftover_columns)
        if results.added or results.modified or dropped_physical_columns:
            self.changed_on = datetime.now()

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #92cc2f

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/connectors/sqla/models.py - 1
    • Dotted-name heuristic edge case · Line 155-166
      `_is_calculated_column` treats any dotted-name column with an expression as physical. But `DatasetColumnsPutSchema.column_name` only enforces `Length(1, 255)` (schemas.py:82), so a user-defined calculated column named e.g. `foo.bar` would be misclassified, dropped on the next `fetch_metadata()`, and bump `changed_on`. Consider matching Trino's quoted-path expression pattern instead of a bare dot check.
Review Details
  • Files reviewed - 2 · Commit Range: ef4c137..39418fa
    • superset/connectors/sqla/models.py
    • tests/unit_tests/connectors/sqla/models_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@gabotorresruiz gabotorresruiz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this fix and the thorough writeup, the mechanism is real and well diagnosed. I verified it empirically: on master a refresh that restores a dropped column leaves changed_on untouched (your new integration assertion fails there) and bumps it on this branch, 5 of the 7 new unit tests fail against master so they genuinely pin the fix, and the no-op-refresh test confirms an unchanged schema does not invalidate every chart's cache. Nice catch that the old test_dataset_item_refresh only queued the column deletion for teardown, so it never actually exercised drift.

One blocking issue inline. Two smaller things: CI was cancelled wholesale on this PR and never re-ran, so no checks have actually executed (a rebase push or a re-trigger sorts it), and the linked issue #43918 404s for me; could you re-check the reference or inline the repro steps? One observation, not a blocker: since the dataset row now receives an UPDATE, changed_by flips to the refreshing user when there is drift (verified). That matches PUT /dataset semantics, so I think it is right, just noting it as intentional.

Comment thread superset/connectors/sqla/models.py Outdated
"""
if not column.expression:
return False
return "." not in (column.column_name or "")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This block worries me a bit: the dot heuristic classifies by column name, but users can legally create a calculated column with a dot in its name (DatasetColumnsPutSchema.column_name only enforces Length(1, 255)). I verified on this branch that an existing calculated column named revenue.usd with expression revenue * fx_rate is dropped from self.columns by fetch_metadata(), and since the relationship has cascade="all, delete-orphan", the row is deleted: the user's column is silently destroyed on every refresh. It survives on master. The Bito bot hinted at this edge too.

Trino is the only engine spec that emits expression in metadata, and for expanded ROW fields it is always the quoted dotted path of the column's own name (trino.py::_expand_columns). Matching that signature instead of a bare dot keeps the drop behavior for genuinely removed nested fields while sparing user columns:

def _is_calculated_column(column: TableColumn) -> bool:
    if not column.expression:
        return False
    name = column.column_name or ""
    quoted_path = ".".join(f'"{piece}"' for piece in name.split("."))
    return column.expression != quoted_path

Could you also add a unit test alongside the new ones, e.g. test_fetch_metadata_keeps_dotted_calculated_column, asserting a revenue.usd calculated column survives the refresh? It fails on the current head. Happy to dig in if the Trino-signature approach misses a case I am not seeing.

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Request changes: the root-cause diagnosis is correct and the core mechanism is sound — datetime.now() matches the naive changed_on onupdate convention (superset/models/helpers.py:1261) and DatasetDAO.update (superset/daos/dataset.py:435); the explicit set + db.session.merge on a session-attached instance under @transaction reliably emits the parent UPDATE; query_cache_key really does consume datasource.changed_on (superset/common/query_context_processor.py:422); the unit tests pass. But there's one confirmed data-loss regression to fix before merge.

🔴 High — "Refresh columns" silently deletes calculated columns whose name contains a dot
_is_calculated_column (superset/connectors/sqla/models.py:155-166) classifies a column as physical whenever its column_name contains ., regardless of a user-authored expression. In fetch_metadata, a leftover column (in the dataset but absent from the source) is re-added only when _is_calculated_column is True; otherwise it's dropped from self.columns and, because the relationship is cascade="all, delete-orphan" (models.py:1523), its TableColumn row is deleted on commit. So a user calculated column named e.g. revenue.margin (expression revenue - cost) is silently destroyed on the next refresh (and spuriously bumps changed_on that once). This is a regression: master's if col.expression kept it. The dotted name is reachable — DatasetColumnsPutSchema.column_name only length-validates (superset/datasets/schemas.py:82), and UpdateDatasetCommand._validate_columns checks only duplicates/uniqueness — and a normal PUT save preserves such a column, so only refresh loses it, which makes the loss surprising and easy to miss.

Fix: don't discriminate physical vs. virtual by punctuation in the name. Prefer an explicit signal — e.g. only exclude dotted-name-with-expression columns on engines whose spec actually expands nested ROW fields (self.database.db_engine_spec), or persist/derive a physical marker — so genuine calculated columns are never dropped on refresh.

🟢 Low — Test blind spot hides the regression above
The kept-virtual test (tests/unit_tests/connectors/sqla/models_test.py:1110) uses the dotless name profit, and the only dotted-name tests (:1030, :1059) assert a Trino-style physical field is dropped — the intended path. No test covers a dotted-name user calculated column that must survive, so CI stays green despite the bug. Fix: add a variant of the kept-virtual test with name profit.margin and expression revenue - cost asserting it's retained (it fails today) — it will pin whatever fix you choose for the High finding.

🟢 Low — Fixes #43918 points at a non-existent issue
The PR body and the new code comments reference #43918, but that number 404s on both the GraphQL and REST APIs — it's neither an issue nor a PR in this repo. As written, Fixes #43918 won't auto-close anything and reviewers can't find the context. Fix: correct the issue number, or drop the reference.

🟢 Low — Unit tests don't exercise delete-orphan / the emitted UPDATE
The fixture mocks the whole session (models_test.py:959), so db.session.merge is a no-op and delete-orphan never runs; the changed_on assertions are valid but only cover the in-memory attribute. This is adequately mitigated by the updated integration test test_dataset_item_refresh (tests/integration_tests/datasets/api_tests.py), which drives the real refresh endpoint and asserts changed_on advanced — worth confirming it runs green in CI, since it exercises the real delete-orphan path.

Also checked and cleared (not blocking): the datetime.now() vs UTC question (naive local is the correct, consistent convention here), the merge + explicit-changed_on persistence, freeze_time/timedelta imports (both present), and the dropped_physical_columns vs results.removed split (correctly uses the separate boolean, since results.removed includes retained calculated columns).

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 19, 2026
@netlify

netlify Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 3f0dc9b
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ab42ee825975700087b5aac
😎 Deploy Preview https://deploy-preview-43921--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.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #04affa

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 39418fa..3172d02
    • superset/connectors/sqla/models.py
    • tests/unit_tests/connectors/sqla/models_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@gabotorresruiz gabotorresruiz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for turning this around, and thanks @rusackas for pushing the fix.

My blocking finding is addressed. _is_calculated_column (superset/connectors/sqla/models.py:155-173) now matches Trino's quoted-path signature instead of a bare dot, which is exactly what _expand_columns writes (superset/db_engine_specs/trino.py:643 and :652).

What I verified on 3172d021

  • test_fetch_metadata_keeps_dotted_calculated_column (tests/unit_tests/connectors/sqla/models_test.py:1137) fails on 39418fa, where revenue.usd is gone from table.columns, and passes here. It pins the regression rather than restating existing behaviour.
  • 5 of the 8 new fetch_metadata unit tests fail on the branch base 3b49223, and so does the new assertion in test_dataset_item_refresh, with changed_on identical before and after the refresh.
  • End to end against a real Redis data cache: I primed a chart-data query through get_df_payload, confirmed the second call came back is_cached=True, then ran RefreshDatasetCommand with genuine drift (a dropped column the refresh restores). The key moved from 2399c4fa... to c1f75255... and the next call was a miss. On 3b49223 the key never moves and the stale result keeps being served. A no-op refresh leaves both changed_on and the key untouched, so the cache stays warm.
  • Blast radius is exactly as advertised. datasource.changed_on reaches the key only through query_cache_key (superset/common/query_context_processor.py:422), so one refresh invalidates the charts on that dataset and nothing wider. Thumbnails are untouched, since get_chart_digest (superset/thumbnails/digest.py:147) does not read it.
  • Two edge cases I poked at: a reorder-only refresh reports no drift and does not bump, and a Trino nested field whose stored expression was empty bumps once, with a second identical refresh reporting modified == []. So this cannot defeat caching continuously.
  • ruff check and ruff format --check are clean on all three files.

Still open from my earlier review

Not a blocker on the code, but worth doing before merge: CI has still never executed on this PR. The only checks on 3172d021 are labeler, the Netlify docs preview and a skipped Showtime step. My read is that GitHub never built the merge ref, because the branch conflicts with master: git merge-tree reports exactly one conflict, the import block of tests/unit_tests/connectors/sqla/models_test.py, where from freezegun import freeze_time collides with from jinja2.exceptions import UndefinedError on master. Keeping both lines resolves it.

I merged master in locally with that resolution and tests/unit_tests/connectors, tests/unit_tests/datasets and tests/unit_tests/commands/dataset are green (342 passed), so catching the branch up should be uneventful, and it should finally give this PR a real CI run.

#43918 resolves fine for me now, so that one is moot.

Approving to clear my change request.

@rebenitez1802 rebenitez1802 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

gps23 and others added 3 commits September 23, 2026 12:54
…dates

Refresh columns mutates child TableColumn rows without updating the
parent tables row, so query_cache_key kept serving results computed
against the previous schema. See apache#43918.
Trino-style nested ROW fields store an expression, so they were kept
like calculated columns when the source dropped them and changed_on
did not bump. Treat dotted-name leftovers as physical. See apache#43918.
… path

_is_calculated_column previously used a bare dot in the column name to
distinguish Trino's expanded nested ROW fields (physical) from
user-defined calculated columns (virtual). A calculated column named
with a dot (e.g. revenue.usd) was misclassified as physical and
silently deleted by fetch_metadata()'s delete-orphan cascade on every
refresh.

Match Trino's actual expression signature for expanded ROW fields
(the column's own dotted name, quoted per-part) instead of the bare
dot, so only genuine nested-field leftovers are dropped and
user-authored calculated columns survive a refresh. See apache#43918.

Co-Authored-By: Evan Rusackas <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
@rusackas
rusackas force-pushed the fix-dataset-refresh-cache branch from 3172d02 to 3f0dc9b Compare September 23, 2026 19:56
@rusackas rusackas removed the requires:rebase Requires rebasing on top of current master label Sep 23, 2026
@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.06%. Comparing base (d7a918b) to head (3f0dc9b).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #43921   +/-   ##
=======================================
  Coverage   81.06%   81.06%           
=======================================
  Files        2955     2955           
  Lines      178300   178310   +10     
  Branches    41307    41309    +2     
=======================================
+ Hits       144533   144543   +10     
  Misses      31056    31056           
  Partials     2711     2711           
Flag Coverage Δ
hive 36.80% <15.38%> (-0.01%) ⬇️
mysql 55.97% <100.00%> (+<0.01%) ⬆️
postgres 55.97% <100.00%> (+<0.01%) ⬆️
presto 38.70% <46.15%> (-0.03%) ⬇️
python 85.36% <100.00%> (+<0.01%) ⬆️
sqlite 55.69% <100.00%> (+<0.01%) ⬆️
unit 77.63% <100.00%> (+<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.

@rusackas
rusackas merged commit 298aa2f into apache:master Sep 23, 2026
80 checks passed
@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped – PR Already Merged

Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.
No action is needed if you didn't intend to review it. To get a review, you can type /review in a comment and save it

villebro pushed a commit that referenced this pull request Sep 30, 2026
…dates (#43921)

Co-authored-by: rusackas <[email protected]>
Co-authored-by: Evan Rusackas <[email protected]>
Co-authored-by: Claude Sonnet 5 <[email protected]>
(cherry picked from commit 298aa2f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dataset 'Refresh columns' (fetch_metadata) doesn't bump changed_on, so chart cache key stays stale after a schema change

4 participants