Skip to content

feat(semantic-layers): containment-aware query cache - #40221

Closed
betodealmeida wants to merge 13 commits into
masterfrom
sl-cache
Closed

betodealmeida wants to merge 13 commits into
masterfrom
sl-cache

Conversation

@betodealmeida

Copy link
Copy Markdown
Member

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 DataFrame instead 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
  • Index: one Redis key per (view UUID, changed_on) — sv:idx:<uuid>:<changed_on_iso>. Holds a list of CachedEntry descriptors. Bumping the view's changed_on (schema/definition change) invalidates the whole bucket atomically.
  • Value: one Redis key per canonicalized query — sv:val:<uuid>:<changed_on_iso>:<query_digest>. Holds the
    SemanticResult (Arrow table + provenance).
  • TTL: takes SemanticView.cache_timeout first, then the global DATA_CACHE_CONFIG.CACHE_DEFAULT_TIMEOUT.

CachedEntry is 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_cache walks the bucket and asks can_satisfy(entry, query) for each entry. The check returns one of three ReuseModes:

Mode When Post-processing
EXACT Same dims, same metrics Apply leftover filters / limit / order
PROJECT Same dims; cached metrics ⊃ new metrics Drop the unused metric columns
ROLLUP Cached dims ⊃ new dims groupby re-aggregate the cached DataFrame

In all three modes, cached metrics must be a non-strict superset of the new query's metrics. ROLLUP additionally requires the new metrics to use additive aggregations (SUM, COUNT, MIN, MAX). PROJECT has no additive constraint because row granularity is preserved — non-additive aggregates like AVG survive unchanged.

When multiple entries satisfy the query, we rank them EXACT < PROJECT < ROLLUP and 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 WHERE filters, 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-match LIKE. HAVING and ADHOC filters 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 that a >= 1984 is a subset of a >= 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). For ROLLUP, we require the cached result to be known complete — if payload.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_rowcount and force_query=True: bypass the cache entirely.
  • Cross-view queries: cache keys are scoped per (view, changed_on).
Provenance

Every served result records the cache hit in its requests list as a SemanticRequest(type="cache", definition=...) with a mode-specific note — useful for debugging and for the Explore indicator to show "semantic smart cache" provenance.

Frontend

CachedLabel and its tooltip learn a new cacheSource prop: "query" (legacy) or "semantic". ChartPills in 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

  • Surface a "smart-cache disabled" toggle in Explore for debugging.
  • Investigate raising MAX_ENTRIES_PER_VIEW per-view via the SemanticView schema.
  • Add metrics/telemetry for hit rate, mode breakdown, and post-processing latency so we can tune containment heuristics with real data.

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 each ReuseMode.
  • tests/unit_tests/semantic_layers/cache_integration_test.py — end-to-end coverage via mapper.get_results with 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

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@netlify

netlify Bot commented May 18, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 411d040
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a0b186c2b580d00084e95cc
😎 Deploy Preview https://deploy-preview-40221--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented May 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 19.93068% with 462 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.43%. Comparing base (64dae07) to head (5581315).
⚠️ Report is 1853 commits behind head on master.

Files with missing lines Patch % Lines
superset/semantic_layers/cache.py 18.00% 337 Missing ⚠️
superset/semantic_layers/mapper.py 7.14% 91 Missing ⚠️
...d/src/features/semanticLayers/jsonFormsHelpers.tsx 7.69% 24 Missing ⚠️
...rc/features/semanticViews/AddSemanticViewModal.tsx 33.33% 10 Missing ⚠️
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     
Flag Coverage Δ
hive 39.25% <16.24%> (-0.18%) ⬇️
javascript 67.00% <43.33%> (-0.01%) ⬇️
mysql 58.79% <17.21%> (-0.34%) ⬇️
postgres 58.87% <17.21%> (-0.34%) ⬇️
presto 40.93% <17.02%> (-0.19%) ⬇️
python 59.11% <17.21%> (-1.54%) ⬇️
sqlite 58.51% <17.21%> (-0.34%) ⬇️
unit ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@betodealmeida
betodealmeida marked this pull request as ready for review May 18, 2026 20:59
@dosubot dosubot Bot added change:backend Requires changing the backend change:frontend Requires changing the frontend infra:caching Infra setup and configuration related to caching labels May 18, 2026
@rusackas

Copy link
Copy Markdown
Member

Dropping some "findings" here in case they're helpful:

  1. Thread safety / race condition in store_result
    The store operation involves: (1) read the index, (2) append the new entry, (3) write the index back. This is a read-modify-write on a Redis key that is not atomic. Under concurrent writes for the same view, two workers could read the same index simultaneously, each append their entry, and one write would overwrite the other's addition. A Redis WATCH/MULTI/EXEC transaction or a Lua script would eliminate this race. Under normal Superset load with one worker per view, this is unlikely but not impossible — especially in a heavily concurrent dashboard load.

  2. Test coverage is critically low: 19.93% patch coverage

  3. The field import in from dataclasses import dataclass, field (line 44) — field doesn't appear to be used in CachedEntry. If unused, it should be removed.

  4. The _sql_like_to_regex function is listed in the symbol table — this is a non-trivial implementation. LIKE pattern → regex conversion has many edge cases (%, _, escaping). Make sure the test suite covers escaped wildcard characters (e.g., LIKE '100%'

  5. ROLLUP correctness: guarding against stale cache entries
    When the cache tries to serve a ROLLUP result, there are two reasons it might skip a candidate and move to the next one:

  • The value was evicted from Redis — Redis may have deleted the cached data (due to TTL or memory pressure) between when the code found it in the index and when it tried to fetch it. If that happens, the code correctly skips it.
  • The cached result is incomplete — If a cached query had a row limit and that limit was fully reached, we can't safely roll up those rows to answer a different grouping (because we're only seeing the "top N" rows of the original query, not the full dataset). So the code also skips those.

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 test_serve_falls_back_to_rollup_when_exact_value_evicted in the integration test does cover the eviction fallback path, which addresses the main worry. This is more of a "make sure the test coverage keeps up with the edge cases" note than a definitive bug.

Comment on lines +522 to +523
{t('Select all')}{' '}
{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
👍 | 👎

Comment on lines +540 to +541
{t('Clear')}{' '}
{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 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 fix

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bito-code-review bito-code-review Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #983322

Actionable Suggestions - 4
  • superset-frontend/src/features/semanticLayers/jsonFormsHelpers.tsx - 1
  • superset/semantic_layers/cache.py - 1
  • superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.tsx - 1
  • superset-frontend/packages/superset-ui-core/src/components/CachedLabel/TooltipContent.test.tsx - 1
Additional Suggestions - 9
  • superset-frontend/src/features/semanticViews/AddSemanticViewModal.tsx - 1
    • Race condition in auto-selection · Line 469-485
      Consider 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-348
      The 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-49
      Test '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-750
      The `_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-643
      The `_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-307
      The `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-486
      The `_implies` function has 26 return statements (limit is 6). Consider refactoring into smaller helper functions.
    • Function has too many return statements · Line 566-566
      The `_implies_range` function has 15 return statements (limit is 6). Consider refactoring into smaller helper functions.
    • Function has too many return statements · Line 717-717
      The `_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
  • tests/unit_tests/semantic_layers/cache_test.py - 2
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

AI Code Review powered by Bito Logo

Comment on lines +321 to +324
placeholder={
(props.uischema?.options as Record<string, unknown>)
?.placeholderText as string | undefined
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing translation wrapper

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid catching blind exception

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
Suggested change
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

Comment on lines +32 to +39
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');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semantic duplication in diff

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data-testid attribute mismatch

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

@michael-s-molina

Copy link
Copy Markdown
Member

@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 rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mikebridge

mikebridge commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

@betodealmeida — I've opened #41824 into this branch addressing @rusackas's store_result race finding (twice-flagged above): the index read-modify-write (and the eviction prune, which has the same shape) now go through a short cache-level lock via cache.add, with the invariant that the index is only written while holding it. Notes on why the suggested WATCH/Lua route doesn't fit (pickled payloads + the Flask-Caching abstraction) are in that PR, along with a deterministic two-thread regression test that reproduces the clobber on the current code every run and passes with the fix.

(via Claude)

@mikebridge

Copy link
Copy Markdown
Member

Triage of the seven open bot threads on this PR (verified where load-bearing, via Claude):

  1. query_object.py — codeant "Architect HIGH" on force_query in the cache key: VERIFIED REAL and fixed in fix(query-object): exclude force_query from the chart cache key #41825 (into this branch). A forced refresh was writing its fresh result under a different cache key while ordinary requests kept serving the stale entry — affects every chart on the legacy path, not just semantic layers. One-line fix + regression test.
  2. TooltipContent.test.tsx — bito's data-testid mismatch: FALSE POSITIVE. The repo's single jest config covers packages/ (testRegex) and loads spec/helpers/setup.ts, which sets testIdAttribute: 'data-test' — so getByTestId matches data-test attributes correctly. Safe to resolve.
  3. cache.py broad-except suggestions (bito): the blanket catches are the file's deliberate defensive pattern (housekeeping must never fail a request) and carry pragma annotations; also reviewed as intentional in the fix(semantic-cache): serialise index bucket writers under a cache-level lock #41824 review rounds. Safe to resolve as by-design.
  4. Select.tsx ×2 (counts concatenated outside t()) and the JSON Forms placeholderText translation: legitimate minor i18n nits — worth a small cleanup commit but not blocking.
  5. TooltipContent.tsx duplication (two near-identical cacheSource conditionals): fair nit, one small helper.

Separately: #41824 (also into this branch) fixes the twice-flagged store_result index race, hardened through three review rounds + live-Redis validation — details in that PR's comment thread.

@mikebridge

Copy link
Copy Markdown
Member

Follow-up to the triage above — the review panel on #41825 surfaced two more findings in this branch, both now resolved or characterized:

  1. Forced refresh never replaced the stale semantic-cache entry (verified): _make_cached_dispatch returned the raw dispatcher on force_query, bypassing both the read and store_result — so other requests' containment lookups kept serving the stale entry until TTL. Fixed in fix(semantic-cache): forced queries store their fresh result #41826 (into this branch): forced queries now skip only the read and store their fresh result, with the force test rewritten to pin the full contract (validated to fail against the pre-fix mapper). Together with fix(query-object): exclude force_query from the chart cache key #41825 this makes force-refresh fully effective across both cache layers.
  2. force_query also enters cache_values via the contribution-totals merge (query_context_processor.py:346, {**cached_query, **query.to_dict()}). Verified consequence is narrower than it first looks: nothing rebuilds a QueryContext from cache_values (no permanent-bypass path), but QueryContext.cache_key() (the qc- payload key) hashes cache_values — so on contribution charts, a forced request's payload caches under a divergent qc- key. Same bug family, low impact; the clean fix would strip execution-control keys from that merge or in QueryContext.cache_key(). Left for this branch's owner to place — happy to do a fourth micro-PR if wanted.

@mikebridge

Copy link
Copy Markdown
Member

Two more base-branch observations from the #41826 review panel, for this branch's backlog (neither introduced by the stacked PRs, neither urgent):

  1. Forward-looking cache-key design note: the semantic cache's keys carry no user/RLS/impersonation context — correct today because semantic-view execution is user-agnostic, but it means every store path becomes a cross-user leak if semantic-layer engines ever gain per-user execution context (engine impersonation, per-user RLS in the underlying semantic platform). Core Superset handles this by folding RLS ids into cache keys. Worth a comment in cache.py documenting the user-agnostic assumption, so the constraint is visible when per-user execution is considered.
  2. Provenance gap on the cheapest hit path: _apply_post_processing early-returns the cached payload as-is for EXACT-mode / no-leftovers / no-limit hits, skipping the SemanticRequest(type="cache") note — so is_cached reads False for exactly the most common cache hit, and the Explore "semantic smart cache" indicator won't show. One-line fix (append the provenance record before the early return).

@mikebridge

Copy link
Copy Markdown
Member

CI unblock for this branch and its stack: #41856. While validating the stacked PRs we found sl-cache's own unit-tests (current) is red on the workflow's 100% coverage gate for superset/semantic_layers/ (the branch sits at 86.44%), and every stacked PR inherits that red. #41856 (into this branch) closes the gap to 100.00% — 499 tests, mostly table-driven over the untested implication/mask/coercion edges — after which this branch's job and #41824/#41825/#41826 all go green.

Writing those tests surfaced three things worth this thread's attention:

  1. Real bug, fixed in fix(semantic-cache): NULL semantics in leftover masks + close the 100% coverage gap #41856: negative leftover masks (NOT_EQUALS/NOT_IN/NOT_LIKE) kept NULL rows — pandas NaN != x is True, SQL three-valued logic excludes it — so cache-served results could contain rows the warehouse would have dropped.
  2. Semantics divergence, flagged: _sql_like_to_regex has no escape support — LIKE '100\%' wildcards the %, unlike e.g. PostgreSQL's default backslash escape — so leftover LIKE masks can diverge from warehouse behavior for escaped patterns. (This is the concrete version of the earlier _sql_like_to_regex review note.)
  3. Dead code: two fallthrough return False lines in _implies_range are unreachable (both same-direction range-op combinations are exhaustively enumerated above them) — pragma'd with justification in fix(semantic-cache): NULL semantics in leftover masks + close the 100% coverage gap #41856; deleting them is equally fine.

Positive note for confidence in the design: the full pairwise implication matrix (every IS_NULL/EQUALS/IN/NOT_IN/range cross-combination) passed against SQL semantics on the first run — the containment logic's core is sound; the gaps were at the mask/NULL boundary.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Aug 1, 2026
@mikebridge

Copy link
Copy Markdown
Member

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.

@mikebridge

Copy link
Copy Markdown
Member

Closing: superseded by #42760 (consolidated semantic-cache), per the supersession notes posted across this stack on 08-06. The rest of the stack (#41824/#41825/#41826/#41856) was closed 08-28; this one was missed.

@rusackas

rusackas commented Sep 8, 2026

Copy link
Copy Markdown
Member

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.

@rusackas rusackas closed this Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend change:frontend Requires changing the frontend infra:caching Infra setup and configuration related to caching packages plugins requires:rebase Requires rebasing on top of current master size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants