Repository navigation
feat(semantic-layers): add safe containment result cache - #42760
Conversation
|
Bito Automatic Review Skipped - Large PR |
✅ 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 #42760 +/- ##
==========================================
+ Coverage 83.09% 83.20% +0.11%
==========================================
Files 3028 3041 +13
Lines 196572 198327 +1755
Branches 45912 46080 +168
==========================================
+ Hits 163332 165026 +1694
- Misses 30016 30076 +60
- Partials 3224 3225 +1
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:
|
fa1d7fa to
f143574
Compare
Manual local testingThe clearest manual test uses two different semantic queries where the first No built-in production semantic provider opts into this cache yet, so this test 1. Start Redisdocker run --rm --name superset-semantic-redis \
-p 6379:6379 redis:7-alpine2. Configure SupersetAdd the following to FEATURE_FLAGS = {
"SEMANTIC_LAYERS": True,
"SEMANTIC_LAYER_CONTAINMENT_CACHE": True,
}
DATA_CACHE_CONFIG = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "127.0.0.1",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 1,
"CACHE_DEFAULT_TIMEOUT": 300,
}
DISTRIBUTED_COORDINATION_CONFIG = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_HOST": "127.0.0.1",
"CACHE_REDIS_PORT": 6379,
"CACHE_REDIS_DB": 2,
"CACHE_REDIS_PASSWORD": "",
}When Superset runs in Docker, use the Redis service/container hostname instead 3. Opt in the semantic providerThe provider needs the equivalent of: from superset_core.semantic_layers.layer import (
SemanticCacheCapabilities,
SemanticCacheIdentityMaterial,
SemanticCacheResponsibility,
SemanticCacheScope,
)
semantic_cache_responsibility = SemanticCacheResponsibility.SUPERSET
semantic_cache_scope = SemanticCacheScope.EXECUTION_CONTEXT
semantic_cache_capabilities = SemanticCacheCapabilities(
comparisons=True,
membership=True,
nulls=True,
pattern_escape="\\",
)
def get_semantic_cache_provider_identity(self):
return SemanticCacheIdentityMaterial(
{"provider_version": "local-test-v1", "catalog": self.config.catalog}
)
def get_semantic_cache_context_identity(self, context):
return SemanticCacheIdentityMaterial({"tenant": "local-test"})4. Exercise containment
The second query differs from the first, but the first result contains enough 5. Verify the resultInspect the chart-data response in browser developer tools. The response header should make the cache outcome immediately visible: The first request should report {
"semantic_cache_hit": true
}The cache pill tooltip should say Loaded from semantic cache. Provider logs 6. Negative controls
The same behavior has a quick non-UI smoke test: source ~/venv/superset/bin/activate
pytest -q tests/unit_tests/semantic_layers/cache_integration_test.py |
c2135da to
8237cc9
Compare
|
Update in |
…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]>
# Conflicts: # superset-core/src/superset_core/semantic_layers/layer.py # superset/semantic_layers/mapper.py # tests/unit_tests/semantic_layers/mapper_test.py
|
Pushed f90b19e, which brings in master and fixes one cache-identity gap.
Still on hold until the metadata-cache invalidation work lands; containment composes with its generation token. One docs-only conflict with master remains in |
|
Merged latest master in Validation passed: 1,459 focused Python tests, 12 cache-pill Jest tests, changed-file pre-commit hooks, and the normal push coverage gate. GitHub reports this head as mergeable. The Merge prepared by Codex, with an independent Claude review of the exact merged tree. That review found no new issues; previously tracked deferred findings remain unchanged. |
|
Merged latest master in Validation: 1,502 focused Python tests passed; the extra query-context run had 143 passes and one known Mac-only The previous two failed checks were Merge prepared by Codex and independently reviewed by Claude on the exact committed tree; no blocking review findings. No ready-state or label changes were made. |
|
Merged the latest master into this branch at f7595d8. The mapper resolution preserves both the per-request filter metadata and semantic cache provenance; all changed test fixtures were reviewed for compatibility. Validation: 1,518 focused Python tests and 47 frontend tests passed. The incoming-file Python run had 2,379 passes and one previously documented local Europe/Dublin timezone failure. Branch-file hooks and the normal pre-push checks, including coverage gates, passed. Codex prepared and validated the merge; an independent Claude review approved the exact committed tree with that documented baseline exception. GitHub now reports MERGEABLE. CI is still running, and |
|
Merged master again after #45061 and #44028. The release-note conflict retains both entries; the runtime semantic-layer gates, dashboard layout changes, cache provenance and initialization changes coexist in the merged tree. OpenAPI regeneration matches the checked-in specification. Validation: 1,543 focused Python tests and 18 frontend tests passed. Tests in the incoming changed Python files had 778 passes and two documented local Europe/Dublin timezone failures. Branch-file hooks passed. Codex prepared and validated the merge; an independent Claude review covered the cache/runtime-gate interactions, changed fixtures and full branch Python annotations. Pushed af6c876; GitHub reports MERGEABLE. Normal pre-push checks, including coverage gates, passed. CI is running; labels and readiness were left unchanged. The independent review identified one non-blocking follow-up: containment still evaluates its parent |
SUMMARY
Adds an experimental, default-off containment cache for semantic-layer results.
A containment cache reuses a previously cached semantic-query result when that
result is proven to contain everything needed to answer a new query. For example,
a result grouped by country and city can answer a later country-only query by
rolling up the cached rows, avoiding another provider query while preserving
equivalent results.
Superset can reuse exact, projected, filtered, or additive-rollup results only when
the provider explicitly delegates cache responsibility and declares compatible
semantics. Identities include the semantic definition, provider material, and
either a global declaration or typed request security context.
Changes from the original PR
This replacement keeps the containment-reuse idea from #40221, but changes its
safety and architecture substantially:
SEMANTIC_LAYERSwas enabled. This PR adds a separate, default-offSEMANTIC_LAYER_CONTAINMENT_CACHErollout flag and requires each provider toexplicitly delegate cache responsibility to Superset.
execution-context scoped, supply secret-free result-affecting identity material,
and opt into only the comparison, membership, NULL, and pattern semantics they
can guarantee.
provider material. Context-scoped identity also incorporates a hash of the
principal, roles, guest-token claims, and RLS cache key.
module. This version separates application orchestration, host adaptation,
identity, containment policy, result transformation, repository storage, shared
types, and distributed coordination.
leases and atomic compare-and-delete release, with direct Redis and Sentinel
coverage. This replaces the original non-atomic descriptor-index updates.
provider queries available. Invalid or unsupported deployment configuration
disables containment rather than semantic queries.
force_querybypasses containment reads without changingordinary result identity, and a successful forced provider result is stored under
the canonical identity.
ordinary query-cache hits so the UI can explain which cache supplied the result.
unsupported-backend warnings, canary guidance, restart convergence, and rollback
instructions are included.
negative-control tests, a pinned real Redis/Sentinel CI path, and 100% statement
and branch coverage for the semantic-layer package.
The implementation also incorporates the still-valid fixes from #41824, #41825,
#41826, and #41856 while avoiding unrelated files from the original branch.
force_queryexcluded from ordinary result identityShortcut: SC-106828.
Rebase note (2026-09-14)
Rebased onto master. The one non-trivial resolution: master renamed
superset/async_events/cache_backend.pytosuperset/coordination/cache_backend.pyand introduced
RedisCommandsMixin(a superset of the coordination primitives).This branch's owner-token lease methods (
acquire_owner_token/release_owner_token,and now the fenced
compare_owner_and_set) were folded into that mixin, reusingmaster's
_COMPARE_AND_DELETE_LUAand dropping the branch's duplicate_OwnerTokenCacheMixin; the staleasync_events.cache_backendimports and thechange-detector CI pattern were repointed to the new module path. No behavior change.
Review follow-ups (sadpandajoe)
when value and lease share one Redis client, non-atomic immediate recheck otherwise
(ab42028).
from
SEMANTIC_CACHE_COORDINATION_WAIT_SECONDS; hung I/O falls back best-effort andstill returns the provider result (ab42028).
and the rollout guide lists the exact
semantic_cache.containment.*counter names(c25fcfa).
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
The existing cached pill remains visually unchanged. For containment hits it is labelled “Semantic cache” and its tooltip says “Loaded from semantic cache”; ordinary result-cache hits retain the existing cached label and tooltip.
QA ENABLEMENT
This feature is default-off and requires an opted-in semantic provider. In the QA environment, add both flags to the existing
FEATURE_FLAGSmapping insuperset_config.py:Configure a shared Redis-backed data cache and distributed-coordination cache. Separate Redis databases are recommended:
Use the QA Redis hostname and credentials rather than the example values. Restart every Superset web and worker process after changing configuration. The semantic provider used for QA must explicitly delegate cache responsibility to Superset and declare its scope, identity material, and supported containment capabilities; enabling the flags alone does not opt a provider in.
After restart, run a broad semantic query followed by a safely contained query. In the chart-data responses, expect
X-Superset-Semantic-Cache: MISSfollowed byHIT. To roll back, disableSEMANTIC_LAYER_CONTAINMENT_CACHE, restart every web and worker process, and confirm subsequent responses reportMISS.TESTING INSTRUCTIONS
Run the focused CachedLabel and ChartPills Jest tests, the chart-data API tests, frontend type checking, targeted Python/frontend pre-commit hooks, and changed-file
pre-commit run --files <branch-changed-files>as recorded in the linked verification artifact. For synchronous JSON chart-data responses, verifyX-Superset-Semantic-Cache: the initial provider request reportsMISS, a contained reuse reportsHIT, and a multi-query response with both outcomes reportsMIXED. The dedicated CI job also exercisespinned Redis and Sentinel services with expiry, stale-release, concurrent writer,
prune/store, parity, descriptor-bound, and lock-free healthy-read assertions.
Rollout requires both
SEMANTIC_LAYERSandSEMANTIC_LAYER_CONTAINMENT_CACHE, plus supported distributed coordination.Canary one worker cohort after capturing latency/error/cache-health baselines and
observe one normal traffic cycle. Roll back by disabling the dedicated flag and
restarting every web/worker process; confirm an enabled gauge of zero and normal
provider success.
ADDITIONAL INFORMATION
SEMANTIC_LAYERS,SEMANTIC_LAYER_CONTAINMENT_CACHEValidation follow-up (independently reviewed)
comparisons=Trueassumes binary/codepoint string ordering and equality;pattern_escapeassumes case-sensitive LIKE. Providers on case-insensitive collations must not opt into these capabilities.IN (1)andIN (True)without relying on Python bool/int equality. The scalar guard is not a claim that collection identity was redesigned.Keep
hold!until Mike accepts: the grained-axis correctness fix and regressions, green exact-head CI includingtest-semantic-cache-coordination(Redis/Sentinel), and a flag-on soak on a real opted-in provider exercising non-atomic writes under concurrent forced refreshes and narrowed time ranges. Local unit coverage alone does not satisfy these gates.