Repository navigation
feat(semantic-layer): coordinate metadata snapshots and cache identity - #44835
mikebridge wants to merge 52 commits into
Conversation
Signed-off-by: Mike Bridge <[email protected]>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #44835 +/- ##
==========================================
+ Coverage 82.56% 82.67% +0.11%
==========================================
Files 3005 3012 +7
Lines 186616 187918 +1302
Branches 43240 43424 +184
==========================================
+ Hits 154076 155368 +1292
Misses 29778 29778
- Partials 2762 2772 +10
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:
|
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
@aminghadersohi @rusackas this is the second piece of the #44808 split, now ready for review: the host-side store and cache identity for the SDK contract in #44834. It is stacked on #44834, so please review only the commits after |
| ) -> SemanticLayerABC[Any, SemanticViewABC]: | ||
| if metadata_binding.participates(self): | ||
| # Read authorization belongs to callers with full request context. | ||
| return metadata_binding.layer_implementation(self) |
There was a problem hiding this comment.
For an opted-in stored layer, /schema/runtime still calls the provider's legacy classmethod rather than the bound adapter, so it can return stale or empty runtime choices while view discovery uses the refreshed snapshot. Could that endpoint use the bound adapter's get_runtime_schema() for participating layers, with an endpoint-level test asserting the refreshed choices?
There was a problem hiding this comment.
Addressed in 74a6043: participating layers use the bound adapter for runtime schema. The endpoint regression first returned the legacy schema, then passed with refreshed choices. Denied callers do not construct a provider or backend. The API layer retains its typed error responses when this is merged forward.
|
The proposed approach aligns with the metadata contract introduced in this PR. The contract specifies that for opted-in providers, the |
| layer.implementation.metadata_refresh | ||
| ) | ||
| if adapter is None: | ||
| raise MetadataRefreshError("configuration") |
There was a problem hiding this comment.
When shared metadata storage is down or discovery runs out of time, this path raises a typed MetadataRefreshError, but the broad except Exception just below turns it into HTTP 400 with only unavailable/deadline as the message. The same happens in /compatible, where the typed error falls through @safe to a generic 500. Clients get none of the 503/504 mapping or localized messages from metadata_errors.py, and the docs say storage failures are 503 and deadline expiry is 504. Should metadata_api_errors (or an explicit except MetadataRefreshError) be applied to these REST endpoints in this PR, or is that deliberately left for a follow-up?
There was a problem hiding this comment.
Fixed in fd44ff9. Runtime schema and compatibility now use the shared typed-error mapper, and runtime schema rethrows the typed error through its broad exception boundary. Real authorized discovery regressions verify localized 503/504 responses instead of 400/500.
| ) | ||
| return {"user_id": get_user_id(), "source_rls": source_rls} | ||
| metadata_datasource: Datasource | None = ( | ||
| chart.resolved_datasource if chart else None |
There was a problem hiding this comment.
The annotation part of the cache key takes its metadata token from chart.resolved_datasource, while the capture above and the annotation executor use chart.get_query_context().datasource. If a chart's datasource was changed through the API and its saved query context was left pointing at the old view, annotation data fetched from view B gets cached under view A's token (or no token if A doesn't participate), so a refresh of B never invalidates it. Should the key use the same view the annotation query actually runs against?
There was a problem hiding this comment.
Fixed in fd44ff9. The annotation key uses the datasource recorded in the saved query context, matching capture and execution. Resolving that identity does not build the query or run discovery. Regressions cover mismatched advertised/saved sources, cache invalidation, and discovery-free key construction.
| else superset_app.app_context() | ||
| ): | ||
| with ( | ||
| metadata_operation() |
There was a problem hiding this comment.
This gives each Celery task a single metadata budget that starts when the task starts. A task like the dashboard Excel export runs every chart in one task, so if earlier charts' warehouse queries take longer than the budget, a later chart on a semantic view fails with a deadline error on its first metadata access, even with a warm snapshot and healthy Redis, and its sheet is dropped. Would it make sense to capture the views a task needs up front, or scope the budget to each chart's metadata acquisition?
There was a problem hiding this comment.
Fixed in c56ac0a. The background dashboard export task and async chart queries now give each chart a fresh metadata acquisition scope before its query is built, so earlier task work or a slow preceding chart can't use up its budget. Nested metadata work, annotations and contribution totals share that chart's deadline and captured observations. Regressions cover sequential export charts, delayed task setup, async deserialization, nested deadlines and cleanup on failure.
Two scope notes: the inline HTTP export still shares the request's budget across charts (by design), and the cache warm-up task gets the same per-chart scope in the next push.
There was a problem hiding this comment.
The per-chart scope covers the Celery task and async chart queries, but the inline export path still runs every chart under the one request deadline: chart_metadata_operation() returns immediately when has_request_context() is true, and _export_xlsx_inline calls build_workbook inside the request. Once cumulative chart time passes 30 seconds, each later chart whose view is not yet captured raises a deadline error, which build_workbook records as a general error. The download is a 200 workbook silently missing those charts. Should the inline path give each chart its own acquisition scope, or should the row budget also limit how long the inline export can run?
There was a problem hiding this comment.
Fixed in 435ccd6b68. Each inline workbook chart now gets its own metadata acquisition scope, and nested work shares that chart's budget. The regression covers both the inline and worker paths after earlier task time has elapsed.
| return context, query | ||
|
|
||
|
|
||
| def test_same_name_and_discovery_after_refresh_cannot_reuse_old_query_result( |
There was a problem hiding this comment.
view_cache_token mixes the view's stored configuration into the cache key, but the view_for fixture here pins configuration="{}" (and uuid/name) for every view, so nothing exercises it. If someone dropped the configuration from that hash, two views that share a catalog token and name but have different configurations would share compatibility and query-result cache entries and all of these tests would still pass. Could you add a case with two views differing only in configuration, with the same selection and changed_on, asserting the second one gets its own compatibility answer and an uncached query result?
There was a problem hiding this comment.
Added both regressions in fd44ff9: views differing only in stored configuration get separate compatibility answers and uncached query results, with catalog token, name, selection and changed_on held constant. Removing configuration from the key makes both tests fail; production hashing already included it.
| ) | ||
| metadata_token: str | None = cast( | ||
| SemanticView, datasource | ||
| ).metadata_cache_token |
There was a problem hiding this comment.
With metadata refresh on and a participating view, this property can raise MetadataRefreshError (shared store down, discovery budget exhausted) before the cache lookup, and get_column_values is not wrapped by metadata_api_errors. @safe then returns a generic 500 instead of the mapped 503/504 that compatible and runtime-schema return. The /views and /structure routes in semantic_layers/api.py have the same gap: their broad except Exception turns the same typed failure into a 400 "check the layer configuration" or a 422. Should these routes use the shared mapper and re-raise typed errors the way runtime-schema now does?
There was a problem hiding this comment.
Fixed in 435ccd6b68. The shared typed-error mapper now wraps column values, layer views and view structure, so authorized discovery failures return the typed error instead of a raw 500. The API branch keeps its additional database-error mapper alongside it.
| # Discovery on a miss can capture a newer annotation | ||
| # snapshot than the lookup peek. Store only under the | ||
| # identity actually used by that annotation query. | ||
| cache_key, cacheable = self._query_cache_key(query_obj) |
There was a problem hiding this comment.
This re-key re-runs datasource.get_extra_cache_keys() after the query has executed, not just the annotation part. For a SQL dataset that re-renders the parent's Jinja, so a cache_key_wrapper(...) value such as latest_partition() can differ after a long-running query. The rows fetched under partition P0 would then be stored under P1's key, and later P1 requests would get stale data. Could the parent's key material captured at lookup be kept, with only the annotation identity recomputed?
There was a problem hiding this comment.
Fixed in 435ccd6b68. The parent cache-key material is captured once at lookup and reused for the post-query re-key, which now recomputes only the annotation identity. The regression changes the extra-key result on a second read and asserts that read never happens.
| except json.JSONDecodeError: | ||
| # Match get_query_context's missing-context fallback. | ||
| return self.resolved_datasource | ||
| return DatasourceDAO.get_datasource( |
There was a problem hiding this comment.
This now resolves the annotation chart's saved datasource while the cache key is being built, before the try in get_df_payload_result. If that datasource was deleted, DatasourceNotFound propagates out of the whole request, even with metadata refresh off. Before this change the lookup happened during annotation execution, where a SupersetException becomes a failed-query payload for that annotation. Should a missing saved datasource fall back to resolved_datasource, or be translated into the same validation error?
There was a problem hiding this comment.
Fixed in 435ccd6b68. When the annotation chart's saved datasource has been deleted, resolution falls back to the resolved datasource instead of failing the healthy parent request. The regression covers the missing saved datasource.
| def _operation(*, require_budget: bool = True) -> MetadataOperation: | ||
| state: MetadataOperation | None = _current_operation() | ||
| if state is None or not math.isfinite(state.deadline): | ||
| raise MetadataRefreshError("configuration") |
There was a problem hiding this comment.
_operation() raises MetadataRefreshError("configuration") whenever no operation is active, and the docs say other synchronous callers must enter metadata_operation(). The in-tree MCP semantic-layer tools (mcp_service/semantic_layer/tool/get_table.py, get_compatible_metrics.py, list_metrics.py) read view.implementation outside a request hook and outside metadata_operation(), and catch only JSONDecodeError. With the flag on and a participating layer, would those tools now fail with an unhandled error? Should they enter metadata_operation() or map the typed error?
There was a problem hiding this comment.
Fixed in 435ccd6b68. The three named MCP tools now run inside a metadata operation when refresh is enabled, and the tool regressions verify a deadline is in place at implementation access. This establishes the operation scope; enabling async Redis and provider support remains a separate rollout gate.
| ) | ||
| try: | ||
| assert started.wait(10) | ||
| store.invalidate_catalog() |
There was a problem hiding this comment.
This does not exercise owner fencing against a replacement writer. The successor finishes publishing before the paused writer resumes, so no lease exists and the old writer is rejected by the lease-existence check. The test would still pass if the Lua owner comparison were removed. Could it have writer A invalidated, writer B acquire a lease and pause, then A resume, asserting A gets configuration_changed and B's lease survives A's publish and cleanup so B can still publish?
There was a problem hiding this comment.
Fixed in 435ccd6b68. The test now has B holding a live replacement lease when the invalidated A resumes, and asserts A is refused, B's lease survives and B then publishes. Against a real Redis, a mutant that skips the owner comparison fails this test and the restored code passes. The test is opt-in via SEMANTIC_METADATA_TEST_REDIS_URL, so it does not run in default CI.
| raise MetadataRefreshError("configuration_changed") | ||
| session: Session | ||
| try: | ||
| with Session( |
There was a problem hiding this comment.
Revalidation opens a fresh Session on the metastore engine while the request's db.session still holds its connection, and the checkout isn't bounded by the metadata deadline. With a small pool (for example pool_size=1, max_overflow=0) or a burst of cold-catalog requests, this waits for a connection the caller itself is holding until the pool timeout, so publication fails and the catalog stays cold. Could this reuse the caller's connection, or check out under the remaining budget?
There was a problem hiding this comment.
Confirmed — the fresh revalidation Session needed a second checkout, which deadlocks a one-connection pool. 673d4c8fd2 keeps the host publication check on the caller's connection instead, and only publishes when it can prove the read is fresh and free of the caller's own writes:
- the live isolation level is READ COMMITTED;
- PostgreSQL 10+ reports no assigned transaction ID for the caller (
pg_current_xact_id_if_assigned()/txid_current_if_assigned()), so ordinary permissionEXISTS/countqueries are fine but any write is not; - there are no pending ORM changes.
Anything else — other isolation levels, MySQL and SQLite metadata databases, unknown evidence — fails closed with a 503-style "Semantic metadata is unavailable" response (logged with the specific reason), not a silent cold read.
The scope read bypasses the identity map and autoflush and runs inside a connection-level SAVEPOINT, so a failed read rolls back only its own scope and never commits, rolls back, or closes the caller's transaction. Tests use a real Session with a one-slot pool and a request-shaped permission query; native PostgreSQL behaviour is modelled rather than run in CI. The API management commands' separate authority Sessions are unchanged by this host-store fix.
| payload: str = fetch(self._deadline) | ||
| except MetadataRefreshError: | ||
| raise | ||
| except Exception: # pylint: disable=broad-except |
There was a problem hiding this comment.
SoftTimeLimitExceeded subclasses Exception, so this converts it into MetadataRefreshError("upstream") when the soft limit fires inside a provider fetch. The Excel export loop re-raises SoftTimeLimitExceeded specifically but swallows other exceptions, so the chart is logged as skipped and the export keeps running until the hard limit kills the worker. Should this let SoftTimeLimitExceeded propagate?
There was a problem hiding this comment.
737bd30e54, retained in 673d4c8fd2, lets SoftTimeLimitExceeded escape provider acquisition unchanged. The cold-read and explicit-refresh regressions verify exception identity, lease cleanup and no publication, and a workbook regression confirms cancellation stops the export before the next chart. Ordinary provider failures still use the sanitized upstream error.
| self._generation_key, uuid4().hex, self._snapshot_ttl_seconds | ||
| ).decode() | ||
| except RedisError: | ||
| raise MetadataRefreshError("unavailable") from None |
There was a problem hiding this comment.
When the metadata deadline lapses while Redis is mid-command, the resulting RedisTimeoutError is reported here as unavailable, unlike _read and _refresh, which recheck the remaining budget first and report deadline. /compatible initializes its generation through this method, so a stalled Redis surfaces as a 503 storage outage instead of the documented 504, and peek_compatibility_generation has the same shape. Should these handlers call self._remaining() before raising unavailable, as the other handlers do?
There was a problem hiding this comment.
Confirmed. The generation read paths recheck the shared deadline when Redis raises, so an exhausted budget retains the typed deadline response while a failure with time remaining stays unavailable. The two elapsed-budget regressions fail before the change and pass in commit 34f90b5244; no mutation retry behavior changed.
|
@sadpandajoe thanks for the depth of review on this stack. We've decided to narrow it to the configuration-edit workflow, and the replacement is up as a draft: #45100. Saving a semantic layer's configuration now changes the layer's cache version in the same transaction, so ordinary reloads read under the new version. A small "Reload metadata" action does the same for upstream-only changes. We're removing the coordinated refresh/store machinery, including its session revalidation and the execution-boundary changes, and accepting the documented race where an in-flight fetch can repopulate one stale entry (clearing again fixes it). Authorization, scoped cache keys and readable errors stay. That means your open threads here and on #44849/#44851 about caller writes, revalidation and the MCP refresh boundary (r4213840179, r4213703710, r4213849660) are moot rather than fixed; we're not claiming the existing findings are resolved in this stack. The readable-errors point and Amin's r4214038035 carry over to #45100's UI. This replaces the current design (about 1k lines instead of about 20k), so we'd value your eyes on #45100 when it's out of draft. |
|
Closing as superseded by #45100, which narrows SC-121047's refresh work to the configuration-edit workflow: saving a semantic layer bumps a per-layer cache version, plus a small Reload metadata action for upstream-only changes, with no coordinated refresh/store machinery. See the context in #44835 (comment). Thanks to everyone who reviewed this stack; several of the lessons and tests carried over. |
Why
When someone adds or changes a metric or dimension in their semantic layer (for example in dbt/MetricFlow), Superset keeps using what it has cached:
Today the only way to see the change is to wait for those caches to expire. This stack lets an authorized user clear the semantic-layer caches on demand, with a "Sync metadata" button in the semantic view editor. The new definitions show up right away, and results cached under the old definitions are never served afterwards.
It's split into four PRs so each can be reviewed on its own. Everything is default-off.
SUMMARY
Second PR in the stack replacing #44808 (semantic-view metadata refresh). It's stacked on #44834, so until that merges this diff includes #44834's commit. Please review only the store layer's changes. It's default-off, and there's no user-facing action yet; the refresh command/API and UI come in the next two PRs.
This is the host side of the SDK contract:
TESTING INSTRUCTIONS
pytest tests/unit_tests/semantic_layers/ tests/unit_tests/coordination/test_deadline_backend.py: 865 passed locally, with 100% line and branch coverage on the semantic-layer package.ADDITIONAL INFORMATION
Includes the one-line CodeQL
initv4.38.2 pin (identical to Dependabot #44860) to unbreak the Analyze checks after master bumpedanalyze. It disappears once #44860 merges.docs/developer_docs/semantic-metadata-store.md)Stack dependencies:
bind/read/refreshtake the caller's deadline).