Skip to content

fix(semantic-layers): cap and time-bound bulk semantic view creation - #45532

Merged
aminghadersohi merged 7 commits into
apache:masterfrom
mikebridge:sc-127447-bulk-create-limits
Oct 22, 2026
Merged

aminghadersohi merged 7 commits into
apache:masterfrom
mikebridge:sc-127447-bulk-create-limits

Conversation

@mikebridge

Copy link
Copy Markdown
Member

SUMMARY

Adding semantic views in bulk asks the semantic layer to look up each view before saving it (#45287). Nothing limited how many views one request could contain or how long those lookups could run in total, so one request could keep a web worker busy for as long as the provider took, multiplied by the number of views.

This change adds two limits to POST /api/v1/semantic_view/:

  • Batch size. SEMANTIC_VIEW_BULK_CREATE_MAX_VIEWS (default 100). Larger requests get a 400 with a message naming both numbers, before any lookup runs. A views value that is not a list of objects is also refused with a 400; before this change, some of those payloads caused a 500.
  • Time budget. SEMANTIC_VIEW_BULK_CREATE_TIMEOUT (default 30 seconds). The budget is checked before each view's lookup. Once it has run out, each remaining view is reported as {"name", "error", "error_type": "TIMEOUT"} without a lookup, and a warning is logged. Views added before that point stay added, which matches the existing partial-success behaviour (201 if anything was added, 422 otherwise).

Design notes:

  • The budget is checked between lookups only. A lookup that is already running is limited by the semantic layer's own timeouts; this change does not cancel provider calls. The worst case is therefore the budget plus one lookup. The default is kept well below the default 60 s web server timeout so that the per-view results reach the client.
  • The lookup still runs before the duplicate-name check, as in fix(semantic-layer): validate views before creation #45287.
  • error_type is a new, optional key. Existing clients that read only name and error are unaffected.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable (API only).

TESTING INSTRUCTIONS

  • pytest tests/unit_tests/semantic_layers/api_test.py -k post_semantic_view
  • Manually, with SEMANTIC_LAYERS enabled: POST more than SEMANTIC_VIEW_BULK_CREATE_MAX_VIEWS views to /api/v1/semantic_view/ and expect a 400 with no provider calls. Set SEMANTIC_VIEW_BULK_CREATE_TIMEOUT = 0 and expect every view to come back with error_type: "TIMEOUT" and status 422.

ADDITIONAL INFORMATION

  • Has associated 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

Follow-up to #45287. The Add Semantic View modal sends every selected view in one request; with more than 100 selected it shows its generic error. Showing the server's message, or splitting the request, is left for a follow-up that can build on #45524.

mikebridge and others added 2 commits October 20, 2026 11:53
Bulk creation does one semantic layer lookup per view. Refuse requests
with more than SEMANTIC_VIEW_BULK_CREATE_MAX_VIEWS views (default 100)
before any lookup, and stop starting new lookups once
SEMANTIC_VIEW_BULK_CREATE_TIMEOUT seconds (default 60) have passed:
remaining views are reported with error_type TIMEOUT and can be retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refuse non-object view items before any lookup, default the time budget
to 30 s so it stays under the default web timeout, log when the budget
runs out, translate the empty-batch message and note the cap in
UPDATING.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added i18n Namespace | Anything related to localization api Related to the REST API doc Namespace | Anything related to documentation labels Oct 20, 2026
@netlify

netlify Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 496dfd8
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ad8e9ec4081a2219638ac6f
😎 Deploy Preview https://deploy-preview-45532--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 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 84.07%. Comparing base (cdc9430) to head (496dfd8).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #45532   +/-   ##
=======================================
  Coverage   84.07%   84.07%           
=======================================
  Files        3056     3056           
  Lines      201163   201189   +26     
  Branches    47040    47045    +5     
=======================================
+ Hits       169122   169146   +24     
- Misses      28796    28797    +1     
- Partials     3245     3246    +1     
Flag Coverage Δ
hive 34.91% <27.58%> (-0.01%) ⬇️
mysql 52.84% <27.58%> (-0.01%) ⬇️
postgres 52.85% <27.58%> (-0.01%) ⬇️
presto 36.63% <27.58%> (-0.01%) ⬇️
python 87.32% <100.00%> (+<0.01%) ⬆️
sqlite 52.61% <27.58%> (-0.01%) ⬇️
unit 81.58% <100.00%> (+<0.01%) ⬆️

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.

@mikebridge
mikebridge marked this pull request as ready for review October 20, 2026 22:40
)
timed_out = 0
for view_data in views_data:
if time.monotonic() >= deadline:

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: Because get_semantic_view() has no enforced timeout in the provider contract, a blocking provider can keep the worker past this deadline indefinitely; remaining TIMEOUT results cannot be returned until it finishes.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/semantic_layers/api.py
**Line:** 431:431
**Comment:**
	*Api Mismatch: Because `get_semantic_view()` has no enforced timeout in the provider contract, a blocking provider can keep the worker past this deadline indefinitely; remaining `TIMEOUT` results cannot be returned until it finishes.

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

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.

That's correct, and it is a deliberate limit of this change rather than a gap in it. The budget is checked between lookups, so a lookup that is already running finishes on the provider's own timeouts before the remaining views are reported as TIMEOUT. The worst case is the budget plus one lookup, not an unbounded wait across the batch.

This is stated in the SEMANTIC_VIEW_BULK_CREATE_TIMEOUT comment in superset/config.py, in the semantic layer connections docs, and in the PR description. The default is 30 seconds so that this extra lookup still fits under the default 60 second web server timeout.

Interrupting the call itself would need either threads around a synchronous provider call, which would leave the provider's work running anyway, or a timeout in the provider contract that reaches its transport. The second option is the right fix, and it is separate work on the provider HTTP transport, so I'm leaving this as is 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.

✅ Customized review instruction saved!

Instruction:

Do not flag the bulk-create deadline for failing to interrupt an in-flight provider lookup; it is checked between lookups, while individual provider calls are bounded by provider transport timeouts.

Applied to:

  • superset/semantic_layers/api.py

💡 To manage or update this instruction, visit: CodeAnt AI Settings

@codeant-ai-for-open-source

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

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Medium Risk

  • The PR needs attention before merging.
  • The bulk deadline is checked only between provider lookups, so a stalled lookup can exceed the configured budget and delay timeout results.

Assessed commit: 496dfd85281c

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

Nothing blocking; one retry problem worth fixing. The cap and the budget are enforced on the server, run before any lookup, and are tested. One retry problem should be fixed here or in the follow-up: when the first request runs out of time, retrying the same request (which the modal does) can fail to add anything more.

Should fix (here or in the #45524 follow-up)

1. Retrying after a timeout can make no progress, because duplicates still cost a lookup. superset/commands/semantic_layer/create.py:130 calls the provider before the uniqueness check at :154. So every view that already exists still spends one lookup from the shared budget before it fails as a duplicate. The Add Semantic View modal makes this the normal retry path. After a partial success it keeps the dialog open, does not refresh already_added (AddSemanticViewModal.tsx:605-606, :625-649), and clicking Add again sends the full selection.

Example: 100 views at about 0.5 s per lookup, with the 30 s default budget.

  • First request: about 60 created, 40 TIMEOUT, status 201.
  • Retry from the modal: the 60 duplicates use the whole budget, 0 are created, the same 40 come back TIMEOUT, status 422.
  • Every further retry gives the same result.

Before this PR, the retry would at least have added the remaining views, or hit the gateway timeout. The new "retry timed-out views" guidance (UPDATING.md, docs) works only for clients that resend just the TIMEOUT names. Possible fixes:

  • Run a cheap validate_uniqueness check before the lookup as well, and keep the existing check after the lookup. That keeps the narrow check-to-insert window that #45287 wanted.
  • Or have the modal refetch the available views (or drop the created names) after a partial success.

Nits

  1. A JSON body that is not an object still returns 500. superset/semantic_layers/api.py:416: request.json or {} followed by .get raises on a top-level array. I checked it: POST [{"name": "x"}] → 500 'list' object has no attribute 'get'. The PR's new check refuses a views value that is not a list of objects but stops one level short. The cause existed before this PR, but it is the same kind of input-shape problem, and the fix is one isinstance(body, dict) check.

  2. The config values have no meaning for None or negatives. api.py:100-101 / :426-428.

    • SEMANTIC_VIEW_BULK_CREATE_MAX_VIEWS = None → 500 on every POST. I checked it: '>' not supported between 'int' and 'NoneType'.
    • MAX_VIEWS = 0 refuses every non-empty request.
    • SEMANTIC_VIEW_BULK_CREATE_TIMEOUT set to 0 or a negative number times out every view.
    • TIMEOUT = None → 500.

    Both settings are typed, so this is minor. Either say in config.py that there is no "unlimited" value, or treat None as unlimited.

  3. The boundary of the deadline comparison is not tested. In mutation testing, changing >= to > at api.py:431 still passes all 19 post_semantic_view tests. The mocked-clock test jumps from 0 to 11 against a deadline of 10, and the TIMEOUT = 0 test relies on the real monotonic() having moved on. Make slow_lookup advance the clock by exactly 10.0 to pin >=.

  4. Timeout entries are identified only by name. api.py:435. Uniqueness is on (name, layer, configuration), so an API client that sends the same name for two configurations cannot tell which one timed out. The modal is not affected because it sends one configuration per request. Adding the request index, or echoing semantic_layer_uuid, would make retries unambiguous. This is optional.

Checked, no issues

  • Where the cap is enforced. It is checked on the server, before the loop and before any CreateSemanticViewCommand or DB work. The boundary is > (exactly at the cap is accepted), and both sides are tested. Mutation testing confirms this: >= and removing the check both fail tests. The REST endpoint is the only bulk path; there is no MCP tool and no import path that creates semantic views.
  • How the deadline works. It uses time.monotonic() and is checked between views, with no signals or threads. That makes it safe under gunicorn sync and gevent workers, and no lookup is interrupted mid-call. So it leaves no transaction or connection open beyond what the existing per-view @transaction already holds. The extra wait of one lookup is documented.
  • Atomicity. Each view commits on its own (@transaction per command). Partial success stays committed, and the response lists both created and TIMEOUT names. Status codes are 201 when anything was created and 422 otherwise, the same as before.
  • Timeout errors. The TIMEOUT error text is a fixed translated string with no provider details. The warning log contains only counts and the budget.
  • Malformed views values. A dict, a list containing non-objects, and null all return 400 before any lookup.
  • Mutation testing. Ignoring the configured timeout, removing the deadline check, and removing the per-item dict check each fail 1-2 tests.

mikebridge and others added 3 commits October 21, 2026 10:17
…okup

Bulk creation shares one time budget across lookups. A view that already
exists still spent a lookup before failing the uniqueness check, so
resending a batch after a timeout could use the whole budget on views
added by the first request and add nothing. Check uniqueness before the
lookup as well as just before the insert.

Also pin the deadline comparison at its boundary in the timeout test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pin the second uniqueness check with its own test, assert which views a
retry refuses, and note that the re-check is best effort.

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

Copy link
Copy Markdown
Member Author

@fitzee thanks for the review, and for the worked example on retries.

1. Retrying after a timeout. Fixed in 1668b63, with an extra test for the second check in 496dfd8. CreateSemanticViewCommand now checks uniqueness before the provider lookup, and checks again just before the insert so the check-to-insert window stays as short as it was in #45287. A view that already exists is refused without a lookup, so resending the whole batch spends the budget only on the views that are still missing. The new test test_post_semantic_view_retry_after_timeout_adds_remaining_views runs the real command against a fake clock: the first request adds two views and times out on the third, and the retry adds the third with one lookup. It fails on the previous head with a 422. The command tests that pinned the old lookup-then-check order were updated, and the docs now say that resending the whole request is safe. I also merged master, which brings in #45524: the modal marks created views as added and drops them from the selection after a partial success, so the modal no longer resends them either. The server-side fix still matters for other API clients.

4. Deadline boundary. Done in the same commit. The mocked lookup now advances the clock by exactly the budget, so changing >= to > fails the test. I checked that mutation locally.

2. Top-level JSON array returns 500. You're right that the handler raises on it. I tried the one-line isinstance(body, dict) guard, but the request still returns 500: the shared event logger then fails in collect_request_payload (superset/utils/log.py:141, payload.update(json_payload)), which raises ValueError: dictionary update sequence element #0 has length 1; 2 is required. That affects every endpoint that receives a top-level array, so I'd rather fix both in a separate PR than make this one touch shared logging.

3. None or negative config values. I've left these as they are. Both settings are typed as numbers, and 0 behaves as documented: MAX_VIEWS = 0 refuses every batch and TIMEOUT = 0 times out every view, which is how the tests run the all-timed-out case. I'd rather not add an "unlimited" None, because removing the bound is what this PR is trying to prevent.

5. Identifying timed-out views. Agreed that it's ambiguous for a client that sends one name with two configurations. I've left it for now because the modal sends one configuration per request. Echoing the request index would be a small follow-up if an API client needs it.

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

LGTM

@aminghadersohi
aminghadersohi merged commit aabddf5 into apache:master Oct 22, 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 size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants