Repository navigation
feat(semantic-layer): invalidate metadata caches on configuration save - #45100
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #45100 +/- ##
==========================================
+ Coverage 82.83% 82.89% +0.06%
==========================================
Files 3017 3022 +5
Lines 192698 193701 +1003
Branches 44914 45008 +94
==========================================
+ Hits 159624 160578 +954
- Misses 30040 30081 +41
- Partials 3034 3042 +8
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:
|
EnxDev
left a comment
There was a problem hiding this comment.
Read through this one and the core mechanism holds up. The atomic SQL increment, the per-session capture, the clear route's authz (route permission, guest check, raise_for_access, modify check) and the annotation key following the saved query context all line up with how execution works. Migration chains cleanly off the current head, and the semantic_layers + query context processor unit tests pass locally on 047d5d9 (823 passed).
One question inline, about Save bumping the generation on a rename.
| self._properties["configuration"] | ||
| ) | ||
| if "configuration" in self._properties: | ||
| self._model.clear_metadata_cache() |
There was a problem hiding this comment.
The modal's Save always sends configuration (SemanticLayerModal.tsx:303), so renaming a connection in the UI also bumps cache_version and cold-starts every chart cache on that layer. The "description-only edits don't increment" case only happens through the API.
Now that Reload metadata covers the explicit case, would it make sense to bump only when the unmasked configuration actually differs from what's stored? If bumping on every Save is intentional, ignore this.
There was a problem hiding this comment.
You're right: a rename through this modal still submits configuration, so it also invalidates the layer's caches. That's intentional in the Save contract: submitting configuration is an invalidation point even when the unmasked values match. A partial API update that omits configuration leaves the version unchanged, and the existing regression covers both cases. "Reload metadata" is the separate, explicit action. I'd keep it as is, since checking configuration equality would change that policy, but happy to discuss.
|
@sadpandajoe @EnxDev @aminghadersohi this is ready for review. It replaces the closed #44835/#44849/#44851 stack with a simpler approach: saving a semantic layer's configuration bumps a per-layer cache version (stored in the metadata DB, in the same transaction), and every metadata, result, compatibility and column-value cache key includes it, so an ordinary reload reads fresh metadata. A small "Reload metadata" action does the same for upstream-only changes. There's no snapshot store, leases or revalidation. It also removes the unused, unreleased refresh contract from #44834, keeping The one red job ( |
CodeAnt PR Risk: Medium Risk
Assessed commit: |
EnxDev
left a comment
There was a problem hiding this comment.
Follow-up to my earlier pass on 047d5d9.
The new head is only the master merge: the PR's own diff is unchanged, and the only overlap is the QueryObjectValidationError tweak in mapper.py from master. The migration still sits on the current head with nothing else revising 00fab727cd0a. Semantic layers, query context processor and datasource unit tests pass locally on c2b08f4 (867 passed). The latest sharded-jest-tests (5) job on this head is green too, FiltersConfigModal included.
Thanks for the explanation on the rename bump. Treating any submitted configuration as an invalidation point is a fair contract, so I'm fine leaving it.
One note inline on the bot's get_bind().engine finding, which I don't think holds.
…m the provider token `metadata_cache_token` meant two things: on the SDK view it is the token a provider echoes back, and on the host ORM it is the generation that keys host caches. Use one term for the host side, "metadata generation": - ORM `SemanticLayer.metadata_generation` (was `metadata_cache_token`) and `SemanticView.metadata_generation`, used by every host cache key, the provider factory, annotation sources, value suggestions and compatibility. - ORM `SemanticView.metadata_cache_token` stays as a documented alias so the containment integration (apache#42760) keeps reading the host value. - The SDK contract (`SemanticView.metadata_cache_token`, `from_configuration_with_cache_token(cache_token=)`) is unchanged; its docstrings now say it is the provider's echo and never keys host caches. Cache key payloads are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eneration naming Review follow-up. Say when the ORM `SemanticView.metadata_cache_token` alias can go (once the containment cache reads `metadata_generation`), word `forget` in terms of the `cache_version` counter, rename three tests to the generation vocabulary, drop two stale S105 suppressions and reflow the cache-clear doc paragraphs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
fitzee
left a comment
There was a problem hiding this comment.
Verdict: approve. The generation is an atomic SQL increment in the same transaction as Save. It is in every host cache key that serves semantic metadata or results, and the clear route has the same authority as Save. The findings below are non-blocking.
What I checked at c2b08f4:
- Host caches covered. These are the only host caches that hold semantic metadata or results: chart results via
get_extra_cache_keys(models.py:829), chart-backed annotation sources (query_context_processor.py:473-517), column-value suggestions (datasource/api.py:243) and compatibility (datasource/api.py:589)./views,/structure,/schema/runtimeand Explore's datasource payload have no server-side cache. Async read-back, time offsets andasync_queries.py:339all go throughquery_cache_key, so the token reaches them too. - Transactions.
UPDATE ... SET cache_version = cache_version + 1runs inside@transaction, andcache_versionis expired so a later ORM flush can't write a stale value. A failed save rolls back both the configuration and the version. Two concurrent Saves each increment. - Token lifetime. The per-session memo is reset per request (Flask teardown), per Celery task (
task_postrun→session.remove()) and per MCP worker (_worker_context). - Migration. It is the single alembic head and master has added no migrations since the base. It adds one non-null column with
server_default="0", which is a metadata-only change on PG11+/MySQL 8. Downgrade usesdrop_columns. - Removed code. The deleted
superset_core.semantic_layers.metadatacontract was added in #44834 the day before and has no host callers, so removing it causes no regression. - Concerns from #44835 that this PR closes. Annotation keys now take the source's token from the saved query context, matching
get_viz_annotation_data. Column-value suggestions are now keyed on the version.DatasourceNotFoundand similar errors from the annotation lookup are caught instead of failing the whole request. - Tests.
tests/unit_tests/semantic_layers,common/test_query_context_processor.pyandtests/unit_tests/datasource: 867 passed. - Mutations. Each of these fails at least one test: removing the result-key token,
source_versions, eithermetadata_versionkey, the Save bump, the sessionforget, the per-viewforget_metadata, the guest/can_write/modify checks, or the query-context source lookup. - CI is green on this head (the earlier
sharded-jest-tests (5)failure passed on rerun).
Non-blocking
-
Every chart with an annotation layer gets new cache keys on upgrade, not only semantic charts (
superset/common/query_context_processor.py:516).annotation_contextis built wheneverquery_obj.annotation_layersis non-empty. It now always contains"source_versions": {}, andQueryObject.cache_keyhashes all ofextra(query_object.py:614).- So a plain SQL-dataset chart with a NATIVE/FORMULA/event annotation misses its cache once after deploy. Table-backed chart-reference annotations whose saved query context names a different datasource also change key (the RLS-source change).
UPDATING.md:29says only "existing semantic chart caches become cold once". Either addsource_versionsonly when it is non-empty, or widen that sentence.
-
Nothing tests that the metadata host is part of the default scope (
superset/semantic_layers/models.py:206). Deletingurl.host,from the identity list leaves all 867 tests green.- This is the case the scope exists for: a metadata DB cloned or restored to another host (e.g. staging from prod) keeps its layer UUIDs and
cache_version. If the clone shares the data cache backend, it reads the original's entries. test_web_and_task_share_metadata_keys_despite_local_credentialsalready checks which URL parts are ignored. A matching assertion that a different host, port or database gives a different token would pin which parts must count.
- This is the case the scope exists for: a metadata DB cloned or restored to another host (e.g. staging from prod) keeps its layer UUIDs and
-
The success toast overstates what happened for providers that don't override the cache-token hook (
SemanticLayerModal.tsx:257,api.py:996).- With a provider that hasn't overridden
from_configuration_with_cache_token, the host caches rotate but the provider's process-local catalog doesn't. "Cache cleared; reload to fetch metadata" then leads the user to reload and still see the old members. - No in-tree provider exists today, so this is wording only. Something like "Superset caches cleared" would match the documented scope (
semantic-layer-cache-clear.md).
- With a provider that hasn't overridden
|
|
Pushed a small naming follow-up.
No behavior or cache-key change: the generation string and the key payloads are byte-identical. The semantic-layer suite still meets the 100% coverage gate. |
| from superset.migrations.shared.utils import add_columns, drop_columns | ||
|
|
||
| revision: str = "c179af013f48" | ||
| down_revision: str = "00fab727cd0a" |
There was a problem hiding this comment.
00fab727cd0a is no longer master's tip: e4a7c2b9d1f3 (add_run_as_and_report_config) also has down_revision = "00fab727cd0a", so merging this leaves two Alembic heads and superset db upgrade fails with a multiple-heads error until someone writes a merge migration. Should down_revision be rebased onto e4a7c2b9d1f3?
There was a problem hiding this comment.
Good catch, thanks. c179af013f48 now revises e4a7c2b9d1f3 (ed8d265), so the branch has a single Alembic head again. superset db heads reports only c179af013f48, and the single-head migration tests pass. The upgrade and downgrade bodies are unchanged; only the parent revision and its docstring moved.
| return_value=chart, | ||
| ), | ||
| patch( | ||
| "superset.daos.datasource.DatasourceDAO.get_datasource", |
There was a problem hiding this comment.
This patch returns view for any get_datasource call and the test never asserts what it was called with, so it would still pass if _annotation_cache_context resolved the chart's own datasource instead of the one in the saved query context ({"type": "semantic_view", "id": 17}), the exact behaviour this PR changes. Could you capture the mock and assert get_datasource.assert_called_once_with("semantic_view", 17)?
There was a problem hiding this comment.
Agreed, the test could not tell the two datasources apart. It now captures the patched get_datasource and asserts it was called with ("semantic_view", 17) (737b40e). _annotation_cache_context runs twice in that test (before and after the generation bump), so it checks the full call list ([call("semantic_view", 17)] * 2) rather than assert_called_once_with. I checked that it fails when the code resolves the chart's own datasource instead of the one in the saved query context.
…datasource
Capture the patched DatasourceDAO.get_datasource and assert it is called
with the saved query context's ("semantic_view", 17), so the test fails if
the annotation key resolves the chart's own datasource instead.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep both UPDATING entries; master's configuration-schema write gate merges cleanly beside the cache-clear endpoint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep both UPDATING.md entries: the semantic-layer cache generation note from this branch and the preferred_temporal_dimension note from master. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| configuration: Record<string, unknown>; | ||
| } | null>(null); | ||
| const clearRequestRef = useRef(0); | ||
| const dirty = |
There was a problem hiding this comment.
dirty compares the live form data with the raw saved configuration, but ReadOnlyControl/ConstControl in jsonFormsHelpers.tsx call handleChange on mount to inject the schema default/const when the stored value differs. For a layer whose stored configuration lacks such a field (created through the API, or a provider that later added a read-only field with a default), opening the editor and touching nothing makes formData differ from savedForm.configuration, so Reload metadata stays disabled and the only way to clear is a Save. Should the baseline be normalized the same way (or edits tracked separately from schema backfill) so an untouched editor isn't treated as dirty?
There was a problem hiding this comment.
Good catch, thanks. In 7031d27, the dirty check now compares against the saved configuration normalized with the same const and read-only default values the controls inject on mount. That's a small change in SemanticLayerModal.tsx only.
A new test opens the editor for a stored configuration that lacks a defaulted read-only field. Without touching anything, Reload metadata stays enabled. A real configuration edit still marks the form dirty and disables it.
Joe's review found that read-only defaults and const values injected when the editor mounts made an untouched layer appear dirty. Compare against a saved baseline with those same schema values so Reload metadata remains available while real edits still disable it.
| raise TypeError( | ||
| "SEMANTIC_LAYER_CACHE_NAMESPACE must resolve to a string" | ||
| ) | ||
| url: sa.engine.URL = session.get_bind(mapper=SemanticLayer).engine.url |
There was a problem hiding this comment.
The default scope here is built from this process's metadata-DB URL (drivername/host/port/database), and it becomes part of query_cache_key for semantic-view charts. For async chart data, the web process computes the submit-time task_key and the Celery worker writes the DATA cache under its own query_cache_key; the follow-up force_cached read on web only hits if those two keys are byte-identical. If web reaches the metadata DB through a pooler or alias (say pgbouncer:6432) and workers connect directly (postgres, or host:5432 vs. bare host), the scopes differ, so the worker's cached result is never read back: web raises the cache-load miss, resubmits, and returns 202 again. Reports and alerts would split their cache the same way. Before this change the semantic-view key had no process-dependent component.
The docs do say to set SEMANTIC_LAYER_CACHE_NAMESPACE for different host aliases, but with the default empty value nothing fails fast, it just loops. Since the key already carries the datasource uid and the layer UUID, does it need the DB address digest at all by default, or should this require an explicit namespace when GLOBAL_ASYNC_QUERIES is enabled?
There was a problem hiding this comment.
Confirmed: the default scope differs when web and workers use different metadata-DB URL representations, so their semantic cache keys diverge. Different hosts are not required; an omitted versus explicit default port also reproduces it. The cached-read/resubmit path can then keep returning 202. I verified the key mismatch and traced that path, but did not reproduce a live Celery loop.
I'm keeping this open for a follow-up. Removing the database identity also changes isolation for deployments sharing caches with copied layer UUIDs, so it needs a separate design decision. The existing mitigation is to set the same SEMANTIC_LAYER_CACHE_NAMESPACE across web, Celery and MCP for a workspace, and distinct namespaces for isolated workspaces. I don't have live deployment evidence to quantify how common differing connection addresses are.
Codex analysis; follow-up disposition independently reviewed by Claude.
There was a problem hiding this comment.
Understood on keeping the fix for a follow-up. As merged, though, the default (empty namespace) configuration still keys async semantic-view charts on the process's DB address, so any deployment where web and workers reach the metadata DB differently will loop on 202 with nothing in the logs pointing at the cause. Could this PR at least add a startup warning or a prominent UPDATING.md note for GLOBAL_ASYNC_QUERIES deployments until the follow-up lands?
| )) { | ||
| if (typeof property !== 'object' || property === null) continue; | ||
| const backfilledValue = | ||
| property.const ?? (property.readOnly ? property.default : undefined); |
There was a problem hiding this comment.
property.const ?? ... treats a const: null as absent, but ConstControl does inject null for that field on mount (constValue !== undefined). For a saved configuration that lacks an optional { type: 'null', const: null } field, the untouched editor ends up with formData containing the field while this baseline does not, so dirty stays true and Reload metadata stays disabled until the user saves — the same trap the backfill normalization was added to remove. The new backfill test only covers non-null values, so this case is unprotected.
Should the baseline test 'const' in property (and use property.const whenever present) so it mirrors what ConstControl injects, with a test for a null const?
| assert view.get_extra_cache_keys({}) != first_result | ||
| assert _column_values_cache_key(view, {"col": "category"}) != first_values | ||
| assert processor._annotation_cache_context(query) != first_annotation | ||
| provider.assert_not_called() |
There was a problem hiding this comment.
provider is a Mock registered as the layer type, so provider.assert_not_called() only proves nobody invoked the registry entry itself. Production builds the implementation through provider.from_configuration_with_cache_token(...), which is a child mock and isn't covered by this assertion. If cache-key computation started constructing the implementation (and so triggering provider discovery before a cache lookup), this test would stay green while cached reads began depending on upstream availability.
Could this assert provider.from_configuration_with_cache_token.assert_not_called() (and provider.from_configuration too), or give those a side effect that raises?
SUMMARY
Saving semantic-layer configuration invalidates its metadata caches so a subsequent page reload can fetch upstream changes. A small Reload metadata action also clears caches for upstream-only changes: it confirms the clear and closes the editor, then the user reloads the affected Explore or dashboard tab.
The host atomically increments a per-layer
cache_versionin the metadata database, in the same transaction as a configuration Save. Description-only edits do not increment it. The UUID-addressedclear_cacheendpoint accepts{}, requires connection-write, layer-access and connection-modification authority, and performs no provider discovery. Captured workspace/layer/version tokens partition result, annotation, compatibility and column-value caches while retaining their existing authorization and query dimensions.Annotation cache keys follow the datasource named by the chart's saved query context, matching annotation execution. This also changes RLS-key sourcing for table-backed annotation charts; malformed contexts still fail at execution.
The scope excludes passwords, query options and process secrets. Operators can supply a stable, globally unique workspace namespace shared by web, Celery and MCP when connection routing differs. Old entries expire normally. Concurrent reads can still finish using old metadata; this is best-effort invalidation with no coordinated refresh, snapshot store, leases or fencing.
The shared catalog store from #44835, refresh/inspection operations from #44849 and sync-state UI from #44851 are replaced by a database generation, one authorized clear endpoint and ordinary page reloads.
This replaces the coordinated-refresh design for SC-121047 and supersedes #44835, #44849 and #44851. Those PRs remain open pending the owner's decision.
A separate commit removes the unused, unreleased refresh/snapshot interfaces from #44834 (16 additions / 951 deletions). The existing SDK
SemanticView.metadata_cache_token: str | Nonecontract is preserved. An optionalfrom_configuration_with_cache_tokenhook keeps legacy providers compatible. Complete invalidation also requires providers with local metadata caches to adopt this token before cache lookup/eager discovery; host deployment alone cannot clear those dictionaries. #42760 must include the host ORM view token in containment keys, even when the provider token isNone.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Before: saving connection configuration did not rotate the host metadata cache generation, and the editor had no upstream-only clear action.
After: configuration Save invalidates automatically. A saved, unmodified editor exposes Reload metadata; success displays “Cache cleared; reload to fetch metadata” and closes the editor. Dirty/pending forms disable the action. No browser walkthrough or screenshot is claimed; the interaction is covered by Jest.
TESTING INSTRUCTIONS
SEMANTIC_LAYERS, open an existing layer, change its configuration and Save. Reload the affected Explore/dashboard tab and verify it reads with the new cache generation.SemanticLayerModal.test.tsx.Local validation at
047d5d9045acdf3ce0829585726c6944eebfc27a: semantic-layer 742 passed / 100% coverage; SQL 2,304 passed / 100% coverage; modal Jest 7 passed. Whole suite: 22,320 passed, 40 skipped, 2 xfailed, 2 failed in 785.05s underTZ=UTC. The only failures are the known macOS ARMnp.longdoublenumeric-serialization cases (dataframe_test.py::test_df_to_records_preserves_finite_longdouble_and_nulls_nonfiniteandcommon/test_query_context_processor.py::test_get_data_json_preserves_browser_numeric_contract); those tests and numeric methods are unchanged from master. The process lingered after the complete summary and was stopped; this is a baseline-exception result, not a zero-failure run. Red-first cache-scope and UI regressions are recorded. SQLite tests cover upgrade/backfill/downgrade, transactional rollback and successive stale-writer increments; PostgreSQL/MySQL migration execution and live providers remain for CI/downstream verification.Changed-file formatting/lint/MyPy hooks pass. The normal frontend type hook hits stale declarations; the authorized declaration refresh fails with TS2742 portability errors through this machine's shared dependency symlink. The strict source-resolved affected-file type check passes. POT extraction and OpenAPI generation leave their checked-in outputs unchanged.
ADDITIONAL INFORMATION
SEMANTIC_LAYERSDuring a rolling deployment, old application instances cannot increment the new generation; repeat Reload metadata after rollout if configuration was saved by an old instance. Each clear can cold-start provider caches; it does not clear vendor warehouse caches or automatically execute charts.
🤖 Generated with Claude Code