Repository navigation
feat(semantic-layers): containment-aware query cache - #40221
betodealmeida wants to merge 13 commits into
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 #40221 +/- ##
==========================================
- Coverage 64.14% 63.43% -0.72%
==========================================
Files 2590 2592 +2
Lines 138084 138780 +696
Branches 32037 32235 +198
==========================================
- Hits 88578 88038 -540
- Misses 47985 49212 +1227
- Partials 1521 1530 +9
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:
|
|
Dropping some "findings" here in case they're helpful:
The concern is that these two checks happen in sequence, and the interaction between them should be well-tested. Specifically: what if an entry is evicted and would have been rejected as incomplete anyway? What if the only ROLLUP candidate gets evicted and there's no fallback? The good news is that |
| {t('Select all')}{' '} | ||
| {`(${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`} |
There was a problem hiding this comment.
Suggestion: The selectable count is rendered outside the translation string, so translators cannot reorder or localize the full label (text + number) correctly for languages with different grammar. Put the count inside a single t(...) message with a placeholder so the whole phrase is translatable. [code quality]
Severity Level: Major ⚠️
- ⚠️ Bulk select label poorly localized in non-English locales.
- ⚠️ Translators cannot reorder count relative to label text.Steps of Reproduction ✅
1. Open `superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx` and
locate the `bulkSelectComponent` `useMemo` defined near the bottom of the file; within
this JSX block, at diff lines 522–523, the label is rendered as `{t('Select all')}{' '}`
on one line and `{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`}` on
the next.
2. In the same file, at diff lines 552–565 (confirmed via BulkRead), `popupRender` passes
`selectAllEnabled ? bulkSelectComponent : undefined` into `dropDownRenderHelper`, so
whenever `selectAllEnabled` (computed earlier in this file around lines 11–23 of the
BulkRead snippet) is true, the dropdown renders this combined label to the user.
3. Run the frontend with a non-English locale enabled so that `t('Select all')` resolves
via the i18n catalogs; observe that translators only see and can translate the bare string
`"Select all"` because the numeric count and parentheses `(${...})` are added in code and
are not part of the translation key.
4. Observe in the UI that the rendered text always follows the hardcoded English-oriented
structure `"<translated Select all> (<count>)"`; translators cannot change the position of
the count, add language-specific glue words, or adapt parentheses because the count is
concatenated outside `t(...)`, demonstrating a localization defect tied directly to the
code at lines 522–523.Fix in Cursor | Fix in VSCode Claude
(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
**Line:** 522:523
**Comment:**
*Code Quality: The selectable count is rendered outside the translation string, so translators cannot reorder or localize the full label (text + number) correctly for languages with different grammar. Put the count inside a single `t(...)` message with a placeholder so the whole phrase is translatable.
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 fix| {t('Clear')}{' '} | ||
| {`(${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`} |
There was a problem hiding this comment.
Suggestion: The clear-action count is concatenated outside the i18n message, which prevents proper localization of the complete phrase in non-English locales. Use one translated string with an interpolation placeholder for the formatted count. [code quality]
Severity Level: Major ⚠️
- ⚠️ Bulk clear label not fully localizable in other languages.
- ⚠️ Translators constrained by hardcoded text-count concatenation.Steps of Reproduction ✅
1. In `superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx`,
within the same `bulkSelectComponent` `useMemo` block used for bulk actions, locate the
second button for the clear action; at diff lines 540–541 it renders `{t('Clear')}{' '}`
on one line and `{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`}` on
the next.
2. As confirmed by BulkRead, `popupRender` (diff lines 552–565) passes `selectAllEnabled ?
bulkSelectComponent : undefined` into `dropDownRenderHelper`, so whenever the bulk actions
footer is shown, this clear button (with its split label) is rendered in the dropdown UI.
3. Enable a non-English locale so that `t('Clear')` resolves via the i18n catalogs; note
that the translation system only sees `"Clear"` as the message key, while the deselectable
count and parentheses are added separately via `formatNumber('SMART_NUMBER',
bulkSelectCounts.deselectable)`.
4. Observe in the rendered UI that the clear action label always appears as `"<translated
Clear> (<count>)"`, and translators cannot move the count before the word, change the
punctuation, or integrate the number into the localized phrase because the count is not
part of the `t(...)` message, demonstrating the same localization limitation at lines
540–541.Fix in Cursor | Fix in VSCode Claude
(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
**Line:** 540:541
**Comment:**
*Code Quality: The clear-action count is concatenated outside the i18n message, which prevents proper localization of the complete phrase in non-English locales. Use one translated string with an interpolation placeholder for the formatted count.
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 fix| row_limit: int | None = None, | ||
| row_offset: int | None = None, | ||
| force_query: bool = False, | ||
| series_columns: list[Column] | None = None, |
There was a problem hiding this comment.
🟠 Architect Review — HIGH
QueryObject.to_dict() now includes the execution-control flag force_query, and cache_key() hashes that dict directly; this makes forced-refresh requests use a different cache key than identical non-forced requests, so a user-triggered refresh populates a separate cache entry while normal follow-up requests continue serving stale cached data under the old key.
Suggestion: Keep force_query as an execution-control flag but exclude it from cache key materialization (e.g., remove it from the dict inside cache_key() before hashing, or build the cache dict without it) so forced refreshes update the canonical cache entry shared with normal requests.
Fix in Cursor | Fix in VSCode Claude
(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖
This is an **Architect / Logical Review** comment left during a code review. These reviews are first-class, important findings — not optional suggestions. Do NOT dismiss this as a 'big architectural change' just because the title says architect review; most of these can be resolved with a small, localized fix once the intent is understood.
**Path:** superset/common/query_object.py
**Line:** 133:179
**Comment:**
*HIGH: QueryObject.to_dict() now includes the execution-control flag force_query, and cache_key() hashes that dict directly; this makes forced-refresh requests use a different cache key than identical non-forced requests, so a user-triggered refresh populates a separate cache entry while normal follow-up requests continue serving stale cached data under the old key.
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.
If a suggested approach is provided above, use it as the authoritative instruction. If no explicit code suggestion is given, you MUST still draft and apply your own minimal, localized fix — do not punt back with 'no suggestion provided, review manually'. Keep the change as small as possible: add a guard clause, gate on a loading state, reorder an await, wrap in a conditional, etc. Do not refactor surrounding code or expand scope beyond the finding.
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.
Verified real — cache_key() strips from_dttm/to_dttm but not force_query, so a forced refresh writes under a different key while ordinary requests keep reading the stale entry; affects every chart on the legacy path. Fix (one line + a key-equality regression test, validated to fail without it) opened into this branch as #41825.
There was a problem hiding this comment.
Code Review Agent Run #983322
Actionable Suggestions - 4
-
superset-frontend/src/features/semanticLayers/jsonFormsHelpers.tsx - 1
- Missing translation wrapper · Line 321-324
-
superset/semantic_layers/cache.py - 1
- Avoid catching blind exception · Line 204-204
-
superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx - 1
- Semantic duplication in diff · Line 32-39
-
superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.test.tsx - 1
- data-testid attribute mismatch · Line 44-44
Additional Suggestions - 9
-
superset-frontend/src/features/semanticViews/AddSemanticViewModal.tsx - 1
-
Race condition in auto-selection · Line 469-485Consider updating the `useEffect` hook to include `selectedLayerUuid` in its dependency array and add a guard inside the effect to ensure the available views correspond to the current layer before auto-selecting.
-
-
superset-frontend/src/features/semanticLayers/jsonFormsHelpers.tsx - 1
-
Missing test coverage · Line 288-348The new MultiEnumControl and multiEnumEntry have no test coverage. Existing tests only cover utility functions (areDependenciesSatisfied, sanitizeSchema, etc.). Per BITO.md rule [6262], tests should verify actual behavior rather than just confirming components render.
-
-
superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.test.tsx - 1
-
Missing test coverage · Line 40-49Test 'semantic cache' (lines 40-49) only tests `cacheSource="semantic"` with `cachedTimestamp`. There's no test for `cacheSource="semantic"` without `cachedTimestamp`, leaving the fallback path unverified. Per BITO.md rule 6262, tests should verify actual business logic, not just rendering.
Code suggestion
--- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.test.tsx (lines 40-49) --- 40: test('Rendering TooltipContent correctly - semantic cache', () => { 41: render( 42: <TooltipContent cacheSource="semantic" cachedTimestamp="01-01-2000" />, 43: ); 44: expect(screen.getByTestId('tooltip-content')?.textContent).toBe( 45: `Loaded from semantic smart cache ${extendedDayjs 46: .utc('01-01-2000') 47: .fromNow()}. Click to force-refresh`, 48: ); 49: }); 50: + 51: +test('Rendering TooltipContent correctly - semantic cache without timestamp', () => { 52: + render(<TooltipContent cacheSource="semantic" />); 53: + expect(screen.getByTestId('tooltip-content')?.textContent).toBe( 54: + 'Loaded from semantic smart cache. Click to force-refresh', 55: + ); 56: +});
-
-
superset/semantic_layers/mapper.py - 2
-
Missing string type coercion · Line 643-750The `_coerce_scalar_filter_value` function handles boolean, integer, floating, date, timestamp, and time types but lacks explicit handling for string types (`pa.utf8()`, `pa.large_string()`, `pa.string_view()`). String values fall through to the bare `return value` at line 750 without stripping whitespace or validation, inconsistent with coercion pattern for other types.
-
Function too complex with many branches · Line 643-643The `_coerce_scalar_filter_value` function is too complex with 30 branches and 51 statements (limits: 12 branches, 50 statements). Consider refactoring into smaller helper functions for each type coercion.
-
-
superset/semantic_layers/cache.py - 4
-
Function has too many return statements · Line 307-307The `can_satisfy` function has 14 return statements (limit is 6). Consider refactoring into smaller helper functions to improve readability.
-
Function has too many return statements · Line 486-486The `_implies` function has 26 return statements (limit is 6). Consider refactoring into smaller helper functions.
-
Function has too many return statements · Line 566-566The `_implies_range` function has 15 return statements (limit is 6). Consider refactoring into smaller helper functions.
-
Function has too many return statements · Line 717-717The `_mask_for` function has 14 return statements (limit is 6). Consider refactoring into smaller helper functions.
-
Filtered by Review Rules
Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
-
superset-frontend/src/explore/components/ExploreChartPanel/ExploreChartPanel.test.tsx - 1
- Incomplete test assertions · Line 171-186
-
tests/unit_tests/semantic_layers/cache_test.py - 2
- Incorrect pytest parametrize argument type · Line 476-476
- Incorrect pytest parametrize argument type · Line 137-137
Review Details
-
Files reviewed - 30 · Commit Range:
861ed4a..5581315- superset-core/src/superset_core/semantic_layers/types.py
- superset-frontend/.eslintrc.js
- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.test.tsx
- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx
- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/index.tsx
- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/types.ts
- superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
- superset-frontend/packages/superset-ui-core/src/query/types/QueryResponse.ts
- superset-frontend/playwright/tests/dashboard/clear-all-filters.spec.ts
- superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.test.ts
- superset-frontend/src/dashboard/util/getDashboardUrl.test.ts
- superset-frontend/src/explore/components/ChartPills.tsx
- superset-frontend/src/explore/components/ExploreChartPanel/ExploreChartPanel.test.tsx
- superset-frontend/src/explore/components/controls/CollectionControl/index.tsx
- superset-frontend/src/features/semanticLayers/jsonFormsHelpers.tsx
- superset-frontend/src/features/semanticViews/AddSemanticViewModal.tsx
- superset-frontend/src/middleware/loggerMiddleware.ts
- superset/charts/schemas.py
- superset/common/query_context_factory.py
- superset/common/query_context_processor.py
- superset/common/query_object.py
- superset/common/utils/query_cache_manager.py
- superset/models/helpers.py
- superset/semantic_layers/cache.py
- superset/semantic_layers/mapper.py
- superset/superset_typing.py
- tests/unit_tests/queries/query_object_test.py
- tests/unit_tests/semantic_layers/cache_integration_test.py
- tests/unit_tests/semantic_layers/cache_test.py
- tests/unit_tests/semantic_layers/mapper_test.py
-
Files skipped - 0
-
Tools
- Whispers (Secret Scanner) - ✔︎ Successful
- Detect-secrets (Secret Scanner) - ✔︎ Successful
- Eslint (Linter) - ✔︎ Successful
- MyPy (Static Code Analysis) - ✔︎ Successful
- Astral Ruff (Static Code Analysis) - ✔︎ Successful
Bito Usage Guide
Commands
Type the following command in the pull request comment and save the comment.
-
/review- Manually triggers a full AI review. -
/pause- Pauses automatic reviews on this pull request. -
/resume- Resumes automatic reviews. -
/resolve- Marks all Bito-posted review comments as resolved. -
/abort- Cancels all in-progress reviews.
Refer to the documentation for additional commands.
Configuration
This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].
Documentation & Help
| placeholder={ | ||
| (props.uischema?.options as Record<string, unknown>) | ||
| ?.placeholderText as string | undefined | ||
| } |
There was a problem hiding this comment.
Wrap the placeholderText from uischema options with the translation function t(), for example:
placeholder={
t((props.uischema?.options as Record<string, unknown>)?.placeholderText as string)
}Code Review Run #983322
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
| if len(entries) > MAX_ENTRIES_PER_VIEW: | ||
| entries = sorted(entries, key=lambda e: e.timestamp)[-MAX_ENTRIES_PER_VIEW:] | ||
| cache.set(idx_key, entries, timeout=timeout) | ||
| except Exception: # pragma: no cover - defensive |
There was a problem hiding this comment.
Replace the broad Exception catch with specific exception types to improve error handling. Similar issue exists at line 170.
Code suggestion
Check the AI-generated fix before applying
| except Exception: # pragma: no cover - defensive | |
| except (KeyError, ValueError, TypeError): # pragma: no cover - defensive |
Code Review Run #983322
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
| const loadedFromText = | ||
| cacheSource === 'semantic' | ||
| ? t('Loaded from semantic smart cache') | ||
| : t('Loaded data cached'); | ||
| const loadedFallbackText = | ||
| cacheSource === 'semantic' | ||
| ? t('Loaded from semantic smart cache') | ||
| : t('Loaded from cache'); |
There was a problem hiding this comment.
Lines 32-39 introduce semantic duplication: loadedFromText and loadedFallbackText contain nearly identical conditional logic checking cacheSource === 'semantic'. Both must be updated together if cache source logic changes, creating divergence risk. Consider consolidating into a single helper or inline ternary.
Code suggestion
Check the AI-generated fix before applying
--- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx (lines 32-39) ---
32: - const loadedFromText =
33: - cacheSource === 'semantic'
34: - ? t('Loaded from semantic smart cache')
35: - : t('Loaded data cached');
36: - const loadedFallbackText =
37: - cacheSource === 'semantic'
38: - ? t('Loaded from semantic smart cache')
39: - : t('Loaded from cache');
40: +
41: + const getLoadedText = (useFallback: boolean) => {
42: + if (cacheSource === 'semantic') {
43: + return t('Loaded from semantic smart cache');
44: + }
45: + return useFallback ? t('Loaded from cache') : t('Loaded data cached');
46: + };
47: +
48: const cachedText = cachedTimestamp ? (
49: <span>
50: - {loadedFromText}
51: + {getLoadedText(false)}
52: <b> {extendedDayjs.utc(cachedTimestamp).fromNow()}</b>
53: </span>
54: ) : (
55: - loadedFallbackText
56: + getLoadedText(true)
57: );
Code Review Run #983322
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
| render( | ||
| <TooltipContent cacheSource="semantic" cachedTimestamp="01-01-2000" />, | ||
| ); | ||
| expect(screen.getByTestId('tooltip-content')?.textContent).toBe( |
There was a problem hiding this comment.
The component uses data-test="tooltip-content" but getByTestId from React Testing Library searches for data-testid. This mismatch causes the test to fail at runtime — the query returns undefined instead of finding the element. All three test cases (lines 26, 33, 44) use this pattern and will fail.
Code suggestion
Check the AI-generated fix before applying
--- superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx
+++ superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx
@@ -48,7 +48,7 @@ export const TooltipContent: FC<Props> = ({
);
return (
- <span data-test="tooltip-content">
+ <span data-testid="tooltip-content">
{cachedText}. {t('Click to force-refresh')}
</span>
);
};
Code Review Run #983322
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
|
@betodealmeida Thank you for the PR. This cache is a good default for lightweight implementations, but it would be great to also provide an opt-out mechanism for semantic layers that have their own query optimizer, result cache, and data-aware invalidation (e.g. Minerva) — to avoid Superset serving stale data or producing incorrect re-aggregations from metrics that encode complex business logic. |
rusackas
left a comment
There was a problem hiding this comment.
Just noting that my botz say the store_result race condition is also still there, and index get/append/set isn't atomic, so concurrent writes for one view can clobber each other. Not sure how big of a risk that really is, but there ya have it.
|
@betodealmeida — I've opened #41824 into this branch addressing @rusackas's (via Claude) |
|
Triage of the seven open bot threads on this PR (verified where load-bearing, via Claude):
Separately: #41824 (also into this branch) fixes the twice-flagged |
|
Follow-up to the triage above — the review panel on #41825 surfaced two more findings in this branch, both now resolved or characterized:
|
|
Two more base-branch observations from the #41826 review panel, for this branch's backlog (neither introduced by the stacked PRs, neither urgent):
|
|
CI unblock for this branch and its stack: #41856. While validating the stacked PRs we found Writing those tests surfaced three things worth this thread's attention:
Positive note for confidence in the design: the full pairwise implication matrix (every |
|
Closing to prevent accidental merge: #42760 is the consolidated replacement under review and explicitly carries forward the still-valid work and attribution from this PR stack. This does not mean #42760 has been accepted for adoption yet; that decision remains pending. If the consolidation path changes, this PR can be reopened. |
|
Looks like this one slipped through when the rest of the stack closed out on 08-28. It's superseded by #42760, so closing now. Holler if that's off and you think we should reopen. |
SUMMARY
Adds a smart, containment-aware cache for the semantic-layer query path. The cache understands that one query's result can satisfy another query whose filters/limit/dimensions/metrics are narrower — and serves those subsequent requests from a locally post-processed
DataFrameinstead of hitting the warehouse.In dashboards and Explore the win is concrete: changing a filter range, shrinking a top-N, dropping a metric, or rolling up a dimension no longer round-trips to the database when a broader prior result is already cached.
A small UI affordance in Explore signals that a chart was served from the semantic-layer cache (distinct from the existing per-query result cache).
How it works
Cache layout
(view UUID, changed_on)—sv:idx:<uuid>:<changed_on_iso>. Holds a list ofCachedEntrydescriptors. Bumping the view'schanged_on(schema/definition change) invalidates the whole bucket atomically.sv:val:<uuid>:<changed_on_iso>:<query_digest>. Holds theSemanticResult(Arrow table + provenance).SemanticView.cache_timeoutfirst, then the globalDATA_CACHE_CONFIG.CACHE_DEFAULT_TIMEOUT.CachedEntryis a frozen dataclass that captures filters, dimension keys, metric IDs, limit/offset/order/group-limit, and the value key. It is the unit the lookup walks; the value is fetched lazily once a candidate is chosen.Reuse modes
When a query lands,
try_serve_from_cachewalks the bucket and askscan_satisfy(entry, query)for each entry. The check returns one of threeReuseModes:EXACTPROJECTROLLUPgroupbyre-aggregate the cachedDataFrameIn all three modes, cached metrics must be a non-strict superset of the new query's metrics.
ROLLUPadditionally requires the new metrics to use additive aggregations (SUM,COUNT,MIN,MAX).PROJECThas no additive constraint because row granularity is preserved — non-additive aggregates likeAVGsurvive unchanged.When multiple entries satisfy the query, we rank them
EXACT < PROJECT < ROLLUPand serve the cheapest. If the preferred entry's value has been evicted between index lookup and value fetch, we fall back to the next-best candidate.Filter containment
For
WHEREfilters, each cached predicate must be implied by some new predicate on the same column (cached cannot have hidden rows the new query needs). Conversely, new predicates not covered by the cache become "leftovers" and are reapplied to the cached DataFrame post-fetch, provided they reference columns that are still in the cached projection.The implication helpers cover ranges (
>,>=,<,<=),EQUALS,IN/NOT_IN,IS_NULL/IS_NOT_NULL, and exact-matchLIKE.HAVINGandADHOCfilters require exact-set equality — without parsing them, we cannot prove containment.Filter values are coerced against the dimension's pyarrow type (
_coerce_filter_value) before containment checks. This fixes a class of false-miss bugs where a UI sends"1984"as a string against an integer dimension and the cache fails to recognize thata >= 1984is a subset ofa >= 1982.Top-N safety
When a cached entry has a
limit, we only reuse it if the new query has the same order and a tighter limit (EXACT and PROJECT paths). ForROLLUP, we require the cached result to be known complete — ifpayload.results.num_rows < entry.limit, the source had fewer rows than the cap, so the rollup is over the whole population. Otherwise the cache is skipped (the index entry is preserved; only that reuse is blocked).Capacity & eviction
The per-view bucket caps at
MAX_ENTRIES_PER_VIEW = 128(oldest entries dropped first). Each value lives under its own Redis key with its own TTL, so Redis-level LRU and TTLs do the actual eviction; the index is kept consistent by pruning entries whose values are gone on every lookup.What is not cached
offset != 0: pagination beyond the first page is not reused (no efficient way to recover middle pages from a broader cached result).is_rowcountandforce_query=True: bypass the cache entirely.(view, changed_on).Provenance
Every served result records the cache hit in its
requestslist as aSemanticRequest(type="cache", definition=...)with a mode-specific note — useful for debugging and for the Explore indicator to show "semantic smart cache" provenance.Frontend
CachedLabeland its tooltip learn a newcacheSourceprop:"query"(legacy) or"semantic".ChartPillsin Explore passes"semantic"when the chart result was served from the semantic-layer cache, distinguishing it from the older per-query result cache.Future work
MAX_ENTRIES_PER_VIEWper-view via theSemanticViewschema.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
TESTING INSTRUCTIONS
tests/unit_tests/semantic_layers/cache_test.py— implication helpers, containment edge cases, mode selection, limit/order/offset behavior, and post-processing for eachReuseMode.tests/unit_tests/semantic_layers/cache_integration_test.py— end-to-end coverage viamapper.get_resultswith an in-memory cache fixture: narrower-filter reuse, projection rollup, metric-subset (PROJECT) hits, the EXACT-vs-ROLLUP preference, and the eviction fallback path.tests/unit_tests/semantic_layers/mapper_test.py— filter coercion regressions.ADDITIONAL INFORMATION