codeant-ai-for-open-source[bot] commented on code in PR #40434:
URL: https://github.com/apache/superset/pull/40434#discussion_r3303525531


##########
superset-frontend/src/extensions/ExtensionsStartup.tsx:
##########
@@ -102,7 +129,10 @@ const ExtensionsStartup: React.FC<{ children?: 
React.ReactNode }> = ({
     }
 
     return () => {
-      window.removeEventListener('unhandledrejection', 
handleUnhandledRejection);
+      window.removeEventListener(
+        'unhandledrejection',
+        handleUnhandledRejection,
+      );
     };

Review Comment:
   **Suggestion:** The `unhandledrejection` listener is removed right after 
startup because this effect reruns when `initialized` flips to `true`; React 
runs the previous cleanup before rerunning, so extension rejection isolation 
stops almost immediately. Keep the listener in a one-time effect (or avoid 
depending on `initialized`) so it remains registered for the app lifetime. 
[logic error]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Extension promise failures crash or leak instead of being isolated.
   - โš ๏ธ Host app stability depends on third-party extension error handling.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Load the main frontend app so that `App` in 
`superset-frontend/src/views/App.tsx:13-58`
   renders `<ExtensionsStartup>` around the router and routes, ensuring a 
logged-in user so
   `userId` in `ExtensionsStartup`
   (`superset-frontend/src/extensions/ExtensionsStartup.tsx:70-72`) is defined.
   
   2. On the first render, the effect at `ExtensionsStartup.tsx:82-137` runs 
with
   `initialized === false`; it sets up `window.superset` (lines 91-106), defines
   `handleUnhandledRejection` (lines 112-118), calls
   `window.addEventListener('unhandledrejection', handleUnhandledRejection)` 
(line 120), and
   then calls `setInitialized(true)` (line 125).
   
   3. React re-renders `ExtensionsStartup` with `initialized === true`, which 
triggers the
   effect to re-run; before running the new effect, React invokes the previous 
cleanup
   function returned at `ExtensionsStartup.tsx:131-136`, which executes
   `window.removeEventListener('unhandledrejection', handleUnhandledRejection)` 
and
   unregisters the global listener.
   
   4. On the second effect run with `initialized === true`, the guard at
   `ExtensionsStartup.tsx:83` (`if (initialized) return;`) causes the effect to 
exit early
   without re-registering the listener, so for the rest of the app lifetime 
there is no
   `unhandledrejection` handler. Any unhandled promise rejection originating 
from an
   extension bundle loaded by 
`ExtensionsLoader.getInstance().initializeExtensions()` (called
   at `ExtensionsStartup.tsx:127-129`) now surfaces as an uncaught global error 
instead of
   being caught and `event.preventDefault()`-ed by `handleUnhandledRejection`.
   ```
   </details>
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=dd0edb00c39546109632b190e73c67e2&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 | [Fix in VSCode 
Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=dd0edb00c39546109632b190e73c67e2&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/extensions/ExtensionsStartup.tsx
   **Line:** 131:136
   **Comment:**
        *Logic Error: The `unhandledrejection` listener is removed right after 
startup because this effect reruns when `initialized` flips to `true`; React 
runs the previous cleanup before rerunning, so extension rejection isolation 
stops almost immediately. Keep the listener in a one-time effect (or avoid 
depending on `initialized`) so it remains registered for the app lifetime.
   
   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
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=87a34162a98e94ec721fb2be2277339239eb78842a26426641a88b21e3f412f6&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=87a34162a98e94ec721fb2be2277339239eb78842a26426641a88b21e3f412f6&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/extensions/settings.py:
##########
@@ -0,0 +1,56 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Admin settings persistence for extensions (active chatbot, 
enable/disable)."""
+
+from typing import Any
+
+from superset import db
+from superset.models.core import ExtensionEnabled, ExtensionSettings
+from superset.utils.decorators import transaction
+
+_SETTINGS_ROW_ID = 1
+
+
+def get_extension_settings() -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    enabled_rows = db.session.query(ExtensionEnabled).all()
+    return {
+        "active_chatbot_id": row.active_chatbot_id if row else None,
+        "enabled": {r.extension_id: r.enabled for r in enabled_rows},
+    }
+
+
+@transaction()
+def update_extension_settings(body: dict[str, Any]) -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    if row is None:
+        row = ExtensionSettings(id=_SETTINGS_ROW_ID)
+        db.session.add(row)
+
+    if "active_chatbot_id" in body:
+        row.active_chatbot_id = body["active_chatbot_id"] or None
+
+    if "enabled" in body:
+        for extension_id, enabled in body["enabled"].items():

Review Comment:
   **Suggestion:** This assumes `body["enabled"]` is always a dict; malformed 
JSON like `{"enabled": []}` will raise `AttributeError` on `.items()` and 
return a server error. Validate that `enabled` is an object mapping before 
iterating and return a 4xx response for invalid payloads. [type error]
   
   <details>
   <summary><b>Severity Level:</b> Minor ๐Ÿงน</summary>
   
   ```mdx
   - โš ๏ธ Malformed payloads return 500 instead of validation error.
   - โš ๏ธ Harder for API clients to debug request mistakes.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. A client (for example, a script targeting the admin API) sends `PUT
   /api/v1/extensions/settings` to `ExtensionsRestApi.put_settings` in
   `superset/extensions/api.py:42-71` with a malformed JSON body such as 
`{"enabled": []}`
   instead of an object map, while authenticated as an admin so the
   `security_manager.is_admin()` check at line 67 passes.
   
   2. `put_settings` parses the JSON using `request.get_json(silent=True) or 
{}` at line 69,
   so `body["enabled"]` is a list, and then calls 
`update_extension_settings(body)` (line 70)
   in `superset/extensions/settings.py:38-56`.
   
   3. In `update_extension_settings`, the condition `if "enabled" in body:` at 
line 48
   succeeds, and the code executes `for extension_id, enabled in 
body["enabled"].items():` at
   line 49; since the value is a list (or any non-mapping type), it does not 
have an
   `.items()` method, causing Python to raise an `AttributeError`.
   
   4. The `@transaction()` decorator in `superset/utils/decorators.py:248-27` 
catches the
   exception, rolls back (line 17), and calls `on_error(ex)`; because 
`AttributeError` is not
   an instance of `SQLAlchemyError`, `on_error` re-raises the original 
`AttributeError`
   (lines 225-232), which the `@safe` wrapper converts into a 500 Internal 
Server Error
   instead of returning a 4xx validation error that would clearly indicate an 
invalid payload
   shape for the `"enabled"` field.
   ```
   </details>
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f1c7ef66bd7247d4809a13966b542f6e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 | [Fix in VSCode 
Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f1c7ef66bd7247d4809a13966b542f6e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/extensions/settings.py
   **Line:** 48:49
   **Comment:**
        *Type Error: This assumes `body["enabled"]` is always a dict; malformed 
JSON like `{"enabled": []}` will raise `AttributeError` on `.items()` and 
return a server error. Validate that `enabled` is an object mapping before 
iterating and return a 4xx response for invalid payloads.
   
   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
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=fb3fb051a6ad25a883a887a0371f01f51ac39eb30c55860192e93e5ae3ebf88f&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=fb3fb051a6ad25a883a887a0371f01f51ac39eb30c55860192e93e5ae3ebf88f&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/extensions/settings.py:
##########
@@ -0,0 +1,56 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Admin settings persistence for extensions (active chatbot, 
enable/disable)."""
+
+from typing import Any
+
+from superset import db
+from superset.models.core import ExtensionEnabled, ExtensionSettings
+from superset.utils.decorators import transaction
+
+_SETTINGS_ROW_ID = 1
+
+
+def get_extension_settings() -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    enabled_rows = db.session.query(ExtensionEnabled).all()
+    return {
+        "active_chatbot_id": row.active_chatbot_id if row else None,
+        "enabled": {r.extension_id: r.enabled for r in enabled_rows},
+    }
+
+
+@transaction()
+def update_extension_settings(body: dict[str, Any]) -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    if row is None:
+        row = ExtensionSettings(id=_SETTINGS_ROW_ID)
+        db.session.add(row)

Review Comment:
   **Suggestion:** Creating the singleton settings row with a read-then-insert 
pattern is race-prone: two concurrent admin updates can both see no row and 
both insert `id=1`, causing a duplicate-key failure for one request. Use an 
atomic upsert/get-or-create strategy (or handle `IntegrityError` and refetch) 
to make initialization concurrency-safe. [race condition]
   
   <details>
   <summary><b>Severity Level:</b> Major โš ๏ธ</summary>
   
   ```mdx
   - โŒ Concurrent admin updates can 500 saving global extension settings.
   - โš ๏ธ Admin UX unreliable under simultaneous settings changes.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. An admin user calls `PUT /api/v1/extensions/settings`, which is handled by
   `ExtensionsRestApi.put_settings` in `superset/extensions/api.py` (lines 
42-71 of the
   snippet), guarded by `@protect()` and `@safe` and checking 
`security_manager.is_admin()`
   at line 67 before reading the JSON body with `request.get_json(silent=True) 
or {}` and
   calling `update_extension_settings(body)` (line 70).
   
   2. Assume this is the first time settings are updated and the 
`extension_settings` table
   (defined as `ExtensionSettings` in `superset/models/core.py:111-118`) has no 
row with `id
   = 1`. In `superset/extensions/settings.py:38-56`, 
`update_extension_settings` (decorated
   with `@transaction()`) executes `row = db.session.get(ExtensionSettings,
   _SETTINGS_ROW_ID)` at line 40, which returns `None` for both of two 
concurrent admin
   requests.
   
   3. Each concurrent request enters the conditional at `settings.py:41-43`, 
constructs a new
   `ExtensionSettings(id=_SETTINGS_ROW_ID)` and calls `db.session.add(row)`, so 
the two
   independent transactions both attempt to insert a row with the same primary 
key `id=1`.
   
   4. When `transaction()` in `superset/utils/decorators.py:235-327` commits 
each transaction
   (line 14 inside `wrapped`), the first insert succeeds while the second 
raises a database
   `IntegrityError` (a subclass of `SQLAlchemyError`) due to the duplicate 
primary key; the
   decorator rolls back (line 17) and `on_error` re-raises as 
`SQLAlchemyError`, which the
   `@safe` wrapper in `ExtensionsRestApi` converts into a 500 error response 
for one of the
   concurrent `PUT /api/v1/extensions/settings` calls.
   ```
   </details>
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d7a735bd18414235bc30b0012dcc41e5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 | [Fix in VSCode 
Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d7a735bd18414235bc30b0012dcc41e5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/extensions/settings.py
   **Line:** 40:43
   **Comment:**
        *Race Condition: Creating the singleton settings row with a 
read-then-insert pattern is race-prone: two concurrent admin updates can both 
see no row and both insert `id=1`, causing a duplicate-key failure for one 
request. Use an atomic upsert/get-or-create strategy (or handle 
`IntegrityError` and refetch) to make initialization concurrency-safe.
   
   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
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=f131504922b59d4fc7d1d3f32ffb30ddcac8ce88a2613ff2bdd05fb05b67b701&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=f131504922b59d4fc7d1d3f32ffb30ddcac8ce88a2613ff2bdd05fb05b67b701&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/extensions/settings.py:
##########
@@ -0,0 +1,56 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Admin settings persistence for extensions (active chatbot, 
enable/disable)."""
+
+from typing import Any
+
+from superset import db
+from superset.models.core import ExtensionEnabled, ExtensionSettings
+from superset.utils.decorators import transaction
+
+_SETTINGS_ROW_ID = 1
+
+
+def get_extension_settings() -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    enabled_rows = db.session.query(ExtensionEnabled).all()
+    return {
+        "active_chatbot_id": row.active_chatbot_id if row else None,
+        "enabled": {r.extension_id: r.enabled for r in enabled_rows},
+    }
+
+
+@transaction()
+def update_extension_settings(body: dict[str, Any]) -> dict[str, Any]:
+    row = db.session.get(ExtensionSettings, _SETTINGS_ROW_ID)
+    if row is None:
+        row = ExtensionSettings(id=_SETTINGS_ROW_ID)
+        db.session.add(row)
+
+    if "active_chatbot_id" in body:
+        row.active_chatbot_id = body["active_chatbot_id"] or None
+
+    if "enabled" in body:
+        for extension_id, enabled in body["enabled"].items():
+            flag = db.session.get(ExtensionEnabled, extension_id)
+            if flag is None:
+                flag = ExtensionEnabled(extension_id=extension_id)
+                db.session.add(flag)

Review Comment:
   **Suggestion:** The per-extension flag insert path has the same race: two 
concurrent writes for the same unseen `extension_id` can both insert and one 
commit will fail with a duplicate primary key. Use an upsert/merge or 
catch-and-retry on integrity errors for this row creation path. [race condition]
   
   <details>
   <summary><b>Severity Level:</b> Major โš ๏ธ</summary>
   
   ```mdx
   - โŒ Concurrent toggles can 500 managing extension enabled flags.
   - โš ๏ธ Flaky behavior enabling new extensions under load.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. An admin issues `PUT /api/v1/extensions/settings` with a JSON body whose 
`"enabled"`
   map includes an entry for a previously unseen extension ID (for example 
`{"enabled":
   {"publisher.myext": true}}); this request is handled by 
`ExtensionsRestApi.put_settings`
   in `superset/extensions/api.py:42-71`, which reads the JSON and calls
   `update_extension_settings(body)` (line 70).
   
   2. Inside `update_extension_settings` in 
`superset/extensions/settings.py:38-56`, the
   `"enabled"` key is present so the loop at lines 48-49 iterates over
   `body["enabled"].items()`, and for the new `extension_id` it executes `flag =
   db.session.get(ExtensionEnabled, extension_id)` at line 50; since this 
extension has never
   been seen, both of two concurrent admin requests see `flag is None`.
   
   3. Both requests enter the `if flag is None:` branch at lines 51-53, each 
creates its own
   `ExtensionEnabled(extension_id=extension_id)` instance and calls 
`db.session.add(flag)`
   for the same primary key `extension_id`, against the `extension_enabled` 
table defined in
   `superset/models/core.py:119-124` with `extension_id` as `primary_key=True`.
   
   4. On commit in the `@transaction()` wrapper 
(`superset/utils/decorators.py:248-15`), the
   first transaction's insert succeeds, but the second raises an 
`IntegrityError` due to the
   unique primary key violation; the decorator rolls back and propagates the 
error (via
   `on_error` and `@safe`), causing a 500 response for one of the concurrent 
`PUT
   /api/v1/extensions/settings` requests that attempt to toggle the same new 
extension.
   ```
   </details>
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=209ca093b84941f2b0b9a3942946dba3&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 | [Fix in VSCode 
Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=209ca093b84941f2b0b9a3942946dba3&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/extensions/settings.py
   **Line:** 50:53
   **Comment:**
        *Race Condition: The per-extension flag insert path has the same race: 
two concurrent writes for the same unseen `extension_id` can both insert and 
one commit will fail with a duplicate primary key. Use an upsert/merge or 
catch-and-retry on integrity errors for this row creation path.
   
   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
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=013eec33c84919a7f3fc35ad2b48f507fcf6a5aa88c5d08feb43518dabfce4f5&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40434&comment_hash=013eec33c84919a7f3fc35ad2b48f507fcf6a5aa88c5d08feb43518dabfce4f5&reaction=dislike'>๐Ÿ‘Ž</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to