Skip to content

Commit d526ee4

Browse files
authored
feat(semantic): add optional metadata refresh SDK contract (apache#44834)
Signed-off-by: Mike Bridge <michael.bridge@preset.io>
1 parent 388a10e commit d526ee4

6 files changed

Lines changed: 1106 additions & 0 deletions

File tree

‎docs/developer_docs/extensions/contribution-types.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,9 @@ See [MCP Integration](./mcp.md) for implementation details.
245245

246246
### Semantic Layers
247247

248+
For optional catalog acquisition and host publication, see the
249+
[semantic provider metadata contract](../semantic-metadata-contract.md).
250+
248251
Extensions can register custom semantic layer implementations that allow Superset to connect to external data modeling frameworks. Each semantic layer defines how to authenticate, discover semantic views (tables/metrics/dimensions), and execute queries against the external system.
249252

250253
```python
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
---
2+
title: Semantic provider metadata contract
3+
---
4+
5+
<!--
6+
Licensed to the Apache Software Foundation (ASF) under one
7+
or more contributor license agreements. See the NOTICE file
8+
distributed with this work for additional information
9+
regarding copyright ownership. The ASF licenses this file
10+
to you under the Apache License, Version 2.0 (the
11+
"License"); you may not use this file except in compliance
12+
with the License. You may obtain a copy of the License at
13+
14+
http://www.apache.org/licenses/LICENSE-2.0
15+
16+
Unless required by applicable law or agreed to in writing,
17+
software distributed under the License is distributed on an
18+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19+
KIND, either express or implied. See the License for the
20+
specific language governing permissions and limitations
21+
under the License.
22+
-->
23+
24+
# Semantic provider metadata contract
25+
26+
The optional interfaces in `superset_core.semantic_layers.metadata` let a provider
27+
use a host-owned catalog store. This SDK defines the boundary; it does not supply
28+
storage, authorization, endpoints or a refresh UI. Existing providers need no new
29+
overrides.
30+
31+
## Opting in
32+
33+
`SemanticLayer.supports_metadata_refresh(configuration)` defaults to `False`.
34+
Overrides must determine support without construction, network requests or cache
35+
writes. `SemanticLayer.metadata_refresh` defaults to `None`; an opted-in provider
36+
returns a `MetadataRefreshAdapter`. The property must return the same instance
37+
for the layer's lifetime; views and runtime-schema discovery use that bound
38+
instance. If support is declared but the instance is absent, an enabled host must
39+
reject the configuration rather than silently using legacy cache keys.
40+
41+
The host authorizes and resolves the stored connection before constructing the
42+
provider. It calls `adapter.bind(store, deadline=deadline)` once, before discovery. Rebinding raises
43+
`MetadataRefreshError("configuration")`; an unbound refresh raises
44+
`MetadataRefreshError("unsupported")`. Invalid or exhausted bind deadlines raise
45+
`MetadataRefreshError("deadline")` before binding and leave the adapter unbound.
46+
47+
Full and custom views use the bound store. The adapter's instance
48+
`get_runtime_schema(runtime_data=None)` returns the existing schema shape using
49+
that same store, avoiding the legacy classmethod's unbound construction path.
50+
Unsaved configuration previews cannot publish into a stored connection namespace.
51+
A bound store failure must not silently fall back to provider-local caching.
52+
Existing unbound preview/classmethod discovery remains a provider responsibility;
53+
it never publishes into the stored connection namespace. The in-memory example
54+
below demonstrates the bound path, not a complete preview implementation.
55+
56+
One bound scope contains one catalog covering that connection's supported runtime
57+
configurations. A provider needing different catalogs per runtime database/schema
58+
must not opt in until its scope can satisfy that requirement.
59+
60+
Discovery must be identical for every user of that connection scope. Providers
61+
whose discovery depends on per-user OAuth credentials, impersonation or another
62+
user-specific identity must not declare `supports_metadata_refresh`; the shared
63+
catalog has no per-user dimension. Query authorization and result-cache user/RLS
64+
identity remain separate host responsibilities.
65+
66+
## Data exchanged
67+
68+
| Type | Fields / signature | Meaning |
69+
| --- | --- | --- |
70+
| `CatalogLoader` | `Callable[[float], str]` | Acquisition within a host-supplied absolute monotonic deadline returning provider-validated canonical JSON; valid empty data is allowed |
71+
| `CatalogSnapshot` | `payload: str`, `cache_token: str`, `observed_at: str` | Immutable observation and its captured scope-qualified identity |
72+
| `MetadataRefreshResult` | `status: Literal["changed", "unchanged"]`, `snapshot: CatalogSnapshot` | Confirmed publication, not just completed acquisition |
73+
| `MetadataSnapshotStore.read` | `(fetch: CatalogLoader, *, deadline: float) -> CatalogSnapshot` | Valid observation or bounded coordinated acquisition |
74+
| `MetadataRefreshAdapter.bind` | `(store: MetadataSnapshotStore, *, deadline: float) -> None` | Bind once and capture the host operation's discovery deadline |
75+
| `MetadataRefreshAdapter.refresh` | `(*, deadline: float) -> MetadataRefreshResult` | Pass the caller's budget to the bound store |
76+
| `MetadataSnapshotStore.refresh` | `(fetch: CatalogLoader, *, deadline: float) -> MetadataRefreshResult` | Bypass a hit and confirm a fresh publication |
77+
78+
The provider validates and interprets its payload. The host owns scope, expiry,
79+
authorization and publication. These records do not validate vendor JSON or
80+
implement coordination. `observed_at` is a UTC RFC3339 source-observation time,
81+
not entry creation, expiry or an ordering authority. `CatalogSnapshot` rejects
82+
non-string fields and empty tokens/timestamps with fixed messages that do not echo
83+
input. Timestamp syntax remains the producer's responsibility; this SDK record
84+
does not parse RFC3339 or validate canonical JSON.
85+
86+
Every successful publication gets a new nonempty opaque `cache_token`, including
87+
unchanged discovery. Cache hits retain the captured token. Equal discovery data
88+
cannot prove equal metric definitions if the upstream selector omits complete
89+
query semantics. `changed` includes installation without a prior observation.
90+
91+
`SemanticView.metadata_cache_token` defaults to `None` for legacy views. A bound
92+
opted-in view returns the token captured with its parsed members. Hosts reject
93+
missing tokens in that mode and include the captured token in metadata-dependent
94+
compatibility and result-cache keys, preserving view/query/access identities.
95+
An old result must never be labelled with a token fetched later. Host/provider
96+
implementations must enforce and test these obligations.
97+
98+
## Failures and concurrency
99+
100+
`MetadataRefreshErrorCategory` is the typed set accepted by `MetadataRefreshError`:
101+
`unsupported`, `configuration`, `in_progress`, `configuration_changed`, `upstream`,
102+
`invalid_payload`, `deadline`, `unavailable` and `indeterminate`. Producers pass
103+
these categories, not raw vendor messages or credentials; the constructor rejects
104+
unknown values with a fixed error that does not echo them. Hosts must not expose
105+
exception cause chains. Providers translating sensitive vendor errors should use
106+
`raise MetadataRefreshError("upstream") from None`. HTTP status codes and
107+
localized text belong to the host.
108+
109+
- `configuration_changed`: the authorized connection scope/configuration changed during the operation; discard the candidate rather than publish under obsolete authority.
110+
- `invalid_payload`: acquisition or a stored observation cannot satisfy the provider's catalog schema; never publish partial metadata or an error as an empty catalog.
111+
- `unavailable`: host-owned metadata storage or coordination cannot be reached or used; `upstream` instead identifies failure to acquire metadata from the provider's remote service.
112+
113+
The host establishes one finite absolute `float` deadline using
114+
`time.monotonic()` in the calling process before waiting or acquisition. It passes
115+
that value explicitly to `adapter.bind(store, deadline=deadline)`,
116+
`adapter.refresh(deadline=deadline)`,
117+
`store.read(fetch, deadline=deadline)` and `store.refresh(fetch, deadline=deadline)`.
118+
The adapter forwards it to the store, and the store passes it to `fetch(deadline)`
119+
unchanged. Multiple calls within the same operation share this deadline through
120+
publication; neither the store nor nested acquisition may mint a new budget.
121+
Implementations use `remaining_budget` to reject non-finite, expired or
122+
implausibly large deadlines before I/O, including cache reads. The protocol
123+
signatures do not execute these checks on behalf of implementations.
124+
The provider checks
125+
the remaining time before each upstream operation and uses the tighter of that
126+
budget and its own transport limit. Exhaustion raises
127+
`MetadataRefreshError("deadline")` before further I/O; nested calls must not restart
128+
the budget. Checking only after an unbounded request is insufficient. Actual
129+
transport and publication budget enforcement require host/provider tests.
130+
131+
The existing layer/view and runtime-schema discovery signatures stay compatible.
132+
Ordinary `from_configuration(configuration)` construction remains deadline-free.
133+
The host hands the operation's deadline to `bind`; the adapter captures it for
134+
full/custom-view and runtime-schema discovery, passing it unchanged to store
135+
reads. A new operation requires a fresh provider/adapter instance and a new bind,
136+
not rebinding or renewing an existing instance's discovery budget. The explicit
137+
store/refresh parameters remain required. The example exercises normal provider
138+
construction followed by this bind-time handoff.
139+
140+
Use `remaining_budget(deadline)` before I/O and publication. It returns the
141+
positive remaining seconds and raises `MetadataRefreshError("deadline")` for
142+
non-finite, expired or implausibly large budgets. The SDK ceiling
143+
`MAX_METADATA_BUDGET_SECONDS = 300.0` permits slow metadata discovery while
144+
catching common `time.time()`/monotonic clock confusion; it is not a default or a
145+
reason to extend the caller's budget. Longer requests must be split into bounded
146+
operations. Hosts/providers may use tighter limits. For a host with an injected
147+
monotonic clock, `remaining_budget(deadline, now=clock())` uses that same clock
148+
without introducing host types into the SDK.
149+
150+
This value is neither a duration nor a UTC timestamp. Do not serialize it across
151+
processes, use it as cache expiry, or use it to order publications. A deadline
152+
cannot cancel arbitrary synchronous code and never replaces a publication fence.
153+
154+
An active explicit refresh can report `in_progress`. Cold readers wait/re-read
155+
within a finite deadline or fail safely. A delayed writer cannot replace a later
156+
accepted observation. Failure never installs an error as an empty catalog or
157+
renews freshness. Unconfirmed publication reports `indeterminate`; a timeout proves
158+
neither success nor rollback. These guarantees require real host backend tests.
159+
160+
## Separate host cache controls and diagnostics
161+
162+
Catalog invalidation, independent compatibility invalidation, selected-query
163+
result refresh and read-only cache inspection are host responsibilities. No extra
164+
provider methods are required. Catalog invalidation retires both older writer
165+
authority and derived-cache validity. Compatibility-only invalidation need not
166+
fetch metadata; result refresh does not imply catalog refresh.
167+
168+
Inspection reports recorded entry creation and expiry separately from source
169+
observation. It must not fetch, fill or renew entries. Missing legacy timestamps
170+
remain unknown. Cache payloads, credentials and raw keys are not diagnostic
171+
fields. Storage instrumentation, access enforcement and UI presentation are not
172+
functionality supplied by these SDK records.
173+
174+
## Compatibility and verification
175+
176+
No new abstract methods are added to the existing layer or view bases. Providers
177+
importing this API must require a released SDK containing it: a disabled feature
178+
cannot make a missing import safe. Fleet-wide freshness requires a compatible
179+
host/provider fleet and a coordinated store. Upstream query-version pinning and
180+
vendor-cache clearing are not promised.
181+
182+
`tests/unit_tests/semantic_layers/metadata_contract_test.py` contains a minimal legacy
183+
provider and an opted-in in-memory example. It checks captured observations,
184+
duplicate-label/raw-ID preservation, immutable records, field validation, explicit shared deadlines, error categories and
185+
imports without host dependencies in a fresh isolated subprocess. The test file
186+
is collected by the standard unit-test CI lane. The sequential example does not establish
187+
multiworker or backend correctness.

‎superset-core/src/superset_core/semantic_layers/layer.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from pydantic import BaseModel
2424

25+
from superset_core.semantic_layers.metadata import MetadataRefreshAdapter
2526
from superset_core.semantic_layers.view import SemanticView
2627

2728
ConfigT = TypeVar("ConfigT", bound=BaseModel)
@@ -35,6 +36,20 @@ class SemanticLayer(ABC, Generic[ConfigT, SemanticViewT]):
3536

3637
configuration_class: type[BaseModel]
3738

39+
@classmethod
40+
def supports_metadata_refresh(cls, configuration: dict[str, Any]) -> bool:
41+
"""Declare opt-in support without construction, discovery or other I/O."""
42+
return False
43+
44+
@property
45+
def metadata_refresh(self) -> MetadataRefreshAdapter | None:
46+
"""Return a stable adapter instance, or None for legacy metadata behavior.
47+
48+
An opted-in layer returns the same adapter for its lifetime. Its views
49+
and runtime schema use the instance bound by the host.
50+
"""
51+
return None
52+
3853
@classmethod
3954
@abstractmethod
4055
def from_configuration(

0 commit comments

Comments
 (0)