Skip to content

fix(semantic-layer): validate views before creation - #45287

Merged
aminghadersohi merged 8 commits into
apache:masterfrom
mikebridge:sc-126722-view-create-validate
Oct 19, 2026
Merged

aminghadersohi merged 8 commits into
apache:masterfrom
mikebridge:sc-126722-view-create-validate

Conversation

@mikebridge

@mikebridge mikebridge commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

TL;DR: Validate a semantic view through the same provider lookup used by saved views before adding it.

Background: Add Semantic View discovers available views using the selected layer and runtime configuration.

Problem: The create command checked access and duplicate names but could save a view that the provider no longer offered. The problem surfaced only when someone tried to use that saved view.

What this changes:

  • Look up the submitted name and configuration before checking for duplicates or saving.
  • If lookup fails or returns no view, return one translated 422 message: "Couldn't validate this semantic view: it may not exist, or the semantic layer is unreachable."
  • Keep duplicate errors separate and bulk requests' per-item results, so valid siblings can still be created.
  • Log the layer UUID and view name when lookup produces no view; for provider exceptions, log only the exception type, without its message or traceback.

The detailed design follows.

JSON-string configurations accepted by the command are decoded for both lookup and uniqueness checks. The lookup is get_semantic_view(name, configuration), matching persisted-view resolution and preserving providers' legacy/default configurations. Providers that construct views without a live request do not gain a connectivity probe. Cross-API identity consolidation is outside this bounded fix.

Known limitation: There is one lookup per item, and the metadata read connection remains held during that lookup, as with the discovery endpoint. This is accepted for this bounded change; there is no session-lifetime redesign, per-request discovery cache, or SDK/provider error-contract change. Lookup precedes uniqueness so no remote call widens the check-to-insert window. Providers need not distinguish a nonexistent view from an unreachable layer, hence the single honest validation message.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable: backend validation only.

TESTING INSTRUCTIONS

With SEMANTIC_LAYERS enabled and an existing provider-backed layer:

  1. Add a discovered view with its runtime configuration; it is created.
  2. Submit an unavailable view name to POST /api/v1/semantic_view/; the item reports the honest validation message and no record is created (422 when no items succeed).
  3. Make provider lookup fail; the item reports the same validation message, is not saved, and provider exception text is absent from responses and logs.
  4. Submit an already-added valid view; the duplicate error remains distinct.

Regression tests cover lookup-before-uniqueness ordering, default and JSON-string configuration compatibility, exact missing/failure versus duplicate messages, HTTP 422 responses, and absence of provider secrets from responses and logs. All 12 new regression cases failed before this follow-up.

Local validation: 155 focused tests passed; changed-file pre-commit hooks, including MyPy, passed. The translation template matches fresh extraction. Full service-free unit suite at 234d189fce: 27,283 passed, 11 failed, 49 skipped, 2 xfailed. All eleven failed-test IDs exactly match the accepted baseline; no additional failures. Independent Claude delta review approved the exact tree (no blocker/high/medium findings).

Unexecuted/known: Live-provider and browser checks were not run; CI remains pending. Three failures match the documented local ARM longdouble/PATH baseline. The other eight MCP dateutil/DST failures reproduced identically on base 0ce9b6ca46 in the same environment and were accepted as baseline for this branch. No failing files are changed here.

ADDITIONAL INFORMATION

  • Has associated public issue
  • Required feature flags: SEMANTIC_LAYERS
  • 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

Implementation and local review assisted by Codex.

@github-actions github-actions Bot added api Related to the REST API doc Namespace | Anything related to documentation labels Oct 14, 2026
@netlify

netlify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 98db6df
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ad66c49e21f5c2ab127d4ee
😎 Deploy Preview https://deploy-preview-45287--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 Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.57%. Comparing base (99ecfe5) to head (98db6df).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #45287      +/-   ##
==========================================
+ Coverage   83.56%   83.57%   +0.01%     
==========================================
  Files        3048     3049       +1     
  Lines      199836   200001     +165     
  Branches    46613    46652      +39     
==========================================
+ Hits       166984   167149     +165     
  Misses      29610    29610              
  Partials     3242     3242              
Flag Coverage Δ
hive 34.92% <11.11%> (-0.03%) ⬇️
mysql 52.92% <11.11%> (-0.06%) ⬇️
postgres 52.92% <11.11%> (-0.06%) ⬇️
presto 36.67% <11.11%> (-0.04%) ⬇️
python 87.11% <100.00%> (+0.02%) ⬆️
sqlite 52.68% <11.11%> (-0.06%) ⬇️
unit 81.19% <100.00%> (+0.03%) ⬆️

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.

@github-actions github-actions Bot added the i18n Namespace | Anything related to localization label Oct 14, 2026
@mikebridge
mikebridge marked this pull request as ready for review October 15, 2026 00:32
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Medium Risk

  • The PR needs attention before merging because falsy non-object configurations bypass the new object check.
  • In create.py, configuration or {} converts values such as false and [] to {} before validation, so they are checked as empty configurations instead of rejected.

Assessed commit: 98db6df016aa

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 15, 2026
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 15, 2026
A serialized configuration that isn't a JSON object raised JSONDecodeError
from validate(), which surfaced as a generic create failure. Return the
per-view SemanticViewInvalidError instead, before the provider lookup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mikebridge

Copy link
Copy Markdown
Member Author

Re CodeAnt's risk note on json.loads: addressed in b4f6d70. A serialized configuration that is not a JSON object (malformed, an array or a scalar) now raises SemanticViewInvalidError ("The view configuration must be a JSON object."), before the provider lookup. The batch endpoint reports that per view and carries on with the rest.

Before this change it didn't abort the request: the JSONDecodeError became a generic per-view create failure through the @transaction handler. It also can't arise from the batch API, whose schema loads configuration as a dict. It can still arise from a direct command caller, so the error is now the right one. New test: test_create_semantic_view_malformed_configuration, red first.

@aminghadersohi aminghadersohi 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.

Not ready to merge.

Please remove the private tracker IDs from the PR body and commit messages before merge.

Comment on lines +67 to +68
Superset reports that the view may not exist or the semantic layer may be
unreachable, and does not add it. Other valid views in the same request can still

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.

The Add Semantic View dialog replaces 422 responses with a generic toast and shows only names on partial success, so users never see this reason. Limit this claim to the API response.

Suggested change
Superset reports that the view may not exist or the semantic layer may be
unreachable, and does not add it. Other valid views in the same request can still
the API reports that the view may not exist or the semantic layer may be
unreachable, and does not add it. Other valid views in the same request can still

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Updated in d93a8e4: the docs now explicitly say “the API reports”. The modal still uses a generic toast for a 422 and names only on partial success. I’ve proposed a separate follow-up to surface result.errors[].error in both paths; no UI behavior changes in this PR.

@gabotorresruiz gabotorresruiz 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.

Hi @mikebridge, thanks for this one. No defect found on my side: I ran the semantic layer suites and drove every failure path against a stub provider, and nothing from the layer configuration or the provider exception reaches the response or the logs on any of them. Three non-blocking comments inline.

Holding off on a formal approval only because unit-tests (current), the docker builds and the postgres suites are still running on b4f6d704 (pre-commit, babel-extract and Analyze (python) have passed), and because @aminghadersohi's docs comment is still open.

name, configuration
)
except Exception as ex: # pylint: disable=broad-except
logger.warning("Semantic view lookup failed: %s", type(ex).__name__)

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.

Not a blocker. The type does separate a ConnectionError from a provider-side AttributeError, which is good, but there is no layer uuid and no view name on this line, so a burst of these doesn't say which layer is down. The same provider call on the discovery path (superset/semantic_layers/api.py:898) logs str(ex) with exc_info=True, so provider exception text already reaches the logs on the request the Add dialog makes right before this one. Could we add the identifiers here? Both are already echoed in the response, so neither is new exposure.

Suggested change
logger.warning("Semantic view lookup failed: %s", type(ex).__name__)
logger.warning(
"Semantic view lookup failed for layer %s, view %s: %s",
layer_uuid,
name,
type(ex).__name__,
)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added the layer UUID and view name in d93a8e4, while keeping only the exception type and no provider traceback. The regression test asserts the exact warning and retains the checks that provider exception text does not appear in logs or responses.

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.

Confirmed, thanks. On d93a8e4c65 the line comes out as Semantic view lookup failed for layer <uuid>, view orders: ConnectionError, where b4f6d7048e gave only Semantic view lookup failed: ConnectionError. The exact equality assertion on caplog.messages is the right shape too: swapping type(ex).__name__ for ex fails the test, so the secret free form is pinned rather than just sampled.

_("The view configuration must be a JSON object.")
)
try:
view: SemanticViewABC | None = layer.implementation.get_semantic_view(

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.

More a question about the bulk shape than a blocker. views is only checked for non-empty at superset/semantic_layers/api.py:379, and each item now pays its own provider round trip, so the request time scales with the item count. I couldn't find a timeout on get_semantic_view anywhere under superset/semantic_layers/, so a hung provider holds the worker and the metadata connection for as long as the provider's own socket waits, once per item. The known limitation note compares this to the discovery endpoint, but that one is a single call per request.

Also, because the lookup deliberately runs before the uniqueness check, re-submitting an already added view now pays the round trip too. Both of those feel like the right trade for the fix, so mostly I'm asking whether views is worth bounding here or whether that belongs in its own change.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed: this is one lookup per item, so the discovery-endpoint comparison does not capture the bulk multiplier. Lookup stays before uniqueness to avoid putting a remote round trip between the uniqueness check and insert; an already-added view therefore also pays that lookup. This PR accepts that latency and metadata-connection hold. I’ve proposed a separate follow-up to bound views and define an enforceable provider lookup timeout, including retry/partial-success behavior. A host-side wait timeout alone would not necessarily cancel the provider operation or release its resources, so I’m leaving request handling unchanged here.

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.

That reasoning holds for me, in particular that a host side wait would not necessarily cancel the provider's work or release its resources. Happy to take the views bound and an enforceable lookup timeout as their own change.


When adding a semantic view, Superset asks the provider to look up its name with
the submitted configuration before saving it. If lookup fails or returns no view,
Superset reports that the view may not exist or the semantic layer may be

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.

Agreed with @aminghadersohi here, and one more data point for it: when nothing is created the response is 422, parseResponse rejects on !response.ok, and AddSemanticViewModal.tsx:650 falls into the generic An error occurred while adding semantic views toast. So this reason isn't rendered in either shape today, not only on partial success where the toast carries just the names. Worth surfacing result.errors[].error in the modal as a follow-up so the new string reaches someone?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for tracing both paths. The docs are limited to the API response in d93a8e4. I’ve proposed a follow-up for the modal to render result.errors[].error for both all-failed 422 responses and partial-success responses, with a fallback when the response has no usable per-item error. That follow-up is a local proposal, not an additional change in this PR.

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.

Reads right to me now. I checked the paragraph against both shapes again and "the API reports" is accurate: the partial success 201 body carries result.errors[].error per item, and the all failed case returns the same string in a 422. parseResponse.ts:42 still rejects before the modal can read either, so no UI surface renders it. Good with the modal change being its own follow-up.

@gabotorresruiz gabotorresruiz 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.

Hi @mikebridge, the delta does exactly what the threads asked for, so this is an approve. I re-drove all four lookup paths against a stub provider at DEBUG and the new warning stays clean: nothing from the layer configuration or the provider exception reaches the responses or the logs. CI is green on d93a8e4c65, including the two test jobs that were still running when I held off last time. My approval is on the code; I'm leaving the PR body cleanup @aminghadersohi raised to his thread. One non-blocking question inline.

type(ex).__name__,
)
view = None
if view is 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.

Not a blocker, and this could ride along with the follow-up you already have planned. The warning above only covers the raising half: a provider that handles its own connection error and returns None lands here instead, and neither the command nor the SemanticViewInvalidError handler at api.py:399 logs anything on that path, so the 422 goes out with no line naming the layer. Worth a matching logger.info here, or do you see the two cases as different enough that the silence is right?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added in 5842d57: the no-view rejection logs an INFO message with the layer UUID and view name, including when the provider returns None. The exception path keeps its type-only warning and also emits that INFO message. The red-first test_create_semantic_view_lookup_failure[None] pins the exact INFO message and level; the exception cases pin both messages and still check that provider exception text and tracebacks are absent. No request or persistence behavior changed.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 17, 2026
@aminghadersohi
aminghadersohi merged commit 98d5fa5 into apache:master Oct 19, 2026
72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API doc Namespace | Anything related to documentation i18n Namespace | Anything related to localization requires:rebase Requires rebasing on top of current master size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants