Repository navigation
fix(dataset): bump changed_on on column refresh so chart cache invalidates - #43921
Conversation
Code Review Agent Run #20d433Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
| leftover_columns = list(old_columns_by_name.values()) | ||
| columns.extend([col for col in leftover_columns if col.expression]) |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
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.
|
The flagged issue is correct. When a physical column is dropped, the The provided PR diff already implements a fix for this in # 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 superset/connectors/sqla/models.py |
Code Review Agent Run #92cc2fActionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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.
| """ | ||
| if not column.expression: | ||
| return False | ||
| return "." not in (column.column_name or "") |
There was a problem hiding this comment.
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_pathCould 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
left a comment
There was a problem hiding this comment.
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).
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Code Review Agent Run #04affaActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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 on39418fa, whererevenue.usdis gone fromtable.columns, and passes here. It pins the regression rather than restating existing behaviour.- 5 of the 8 new
fetch_metadataunit tests fail on the branch base3b49223, and so does the new assertion intest_dataset_item_refresh, withchanged_onidentical 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 backis_cached=True, then ranRefreshDatasetCommandwith genuine drift (a dropped column the refresh restores). The key moved from2399c4fa...toc1f75255...and the next call was a miss. On3b49223the key never moves and the stale result keeps being served. A no-op refresh leaves bothchanged_onand the key untouched, so the cache stays warm. - Blast radius is exactly as advertised.
datasource.changed_onreaches the key only throughquery_cache_key(superset/common/query_context_processor.py:422), so one refresh invalidates the charts on that dataset and nothing wider. Thumbnails are untouched, sinceget_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
expressionwas empty bumps once, with a second identical refresh reportingmodified == []. So this cannot defeat caching continuously. ruff checkandruff format --checkare 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.
…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]>
3172d02 to
3f0dc9b
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
|
Bito Automatic Review Skipped – PR Already Merged |
…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)
SUMMARY
Refreshing dataset columns from the source (
fetch_metadata/ "Refresh columns") mutated childTableColumnrows without writing any parenttablescolumn, so SQLAlchemy never firedchanged_ononupdate. Chartquery_cache_key()includesdatasource.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_onwhenfetch_metadata()reports added, modified (type or physical expression), or dropped physical columns — the same cache-invalidation signalDatasetDAO.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_metadatapytest tests/integration_tests/datasets/api_tests.py -k test_dataset_item_refreshADDITIONAL INFORMATION
Made with Cursor