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


##########
superset/mcp_service/tag/tool/update_tag.py:
##########
@@ -0,0 +1,121 @@
+# 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.
+
+import logging
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.tag.schemas import UpdateTagRequest, 
UpdateTagResponse
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Tag",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update a tag",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_tag(request: UpdateTagRequest, ctx: Context) -> 
UpdateTagResponse:
+    """Update an existing custom tag in Superset.
+
+    Use this tool to rename a tag or update its description.
+    Existing object associations are preserved when only name or description 
change.
+
+    Workflow:
+    1. Call this tool with the tag ``id`` and the fields to update
+    2. Omit fields you do not want to change — they keep their current values
+    3. Use the returned ``id`` to confirm the update succeeded
+    """
+    await ctx.info("Updating tag: id=%d" % (request.id,))
+
+    try:
+        from superset.commands.tag.exceptions import (
+            TagInvalidError,
+            TagNotFoundError,
+        )
+        from superset.commands.tag.update import UpdateTagCommand
+        from superset.daos.tag import TagDAO
+
+        existing = TagDAO.find_by_id(request.id)
+        if existing is None:
+            await ctx.warning("Tag not found: id=%d" % (request.id,))
+            return UpdateTagResponse(
+                id=None,
+                name=None,
+                description=None,
+                error=f"Tag with id={request.id} not found",
+            )
+
+        name = request.name if request.name is not None else existing.name
+        description = (
+            request.description
+            if request.description is not None
+            else existing.description
+        )
+
+        # Preserve existing object associations. UpdateTagCommand calls
+        # create_tag_relationship with bulk_create=False (destructive default),
+        # so we must pass the current objects to avoid clearing them.
+        existing_objects = [
+            (obj.object_type.name, obj.object_id) for obj in existing.objects
+        ]
+
+        with event_logger.log_context(action="mcp.update_tag.update"):
+            properties = {
+                "name": name,
+                "description": description,
+                "objects_to_tag": existing_objects,
+            }
+            tag = UpdateTagCommand(request.id, properties).run()

Review Comment:
   **Suggestion:** Relationship preservation is based on a pre-fetched snapshot 
of `existing.objects`, but `UpdateTagCommand` applies destructive relationship 
sync (`bulk_create=False`), so concurrent tag-association changes made after 
this read can be deleted unintentionally. Fetch and lock the tag/relationships 
in the same transaction used for update, or add a non-destructive update mode 
in the command layer to avoid stale-snapshot deletions. [race condition]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Concurrent tagging operations can delete newly added tag associations.
   - ⚠️ Dashboards/charts may unexpectedly lose custom tag labels.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create a custom tag with at least one tagged object using the REST 
endpoint `POST
   /api/v1/tag/` implemented in `superset/tags/api.py:93-141`. This uses
   `CreateCustomTagWithRelationshipsCommand(...).run()`
   (`superset/commands/tag/create.py:15-27`), which calls
   `TagDAO.create_tag_relationship(..., bulk_create=self._bulk_create)` at 
lines 19-24 to
   populate initial `TaggedObject` associations.
   
   2. In client A, invoke the MCP `update_tag` tool to change only metadata 
(e.g.,
   `{"request": {"id": <tag_id>, "name": "tagged"}}`). The tool implementation 
in
   `superset/mcp_service/tag/tool/update_tag.py:39-82` loads the tag via
   `TagDAO.find_by_id(request.id)` at line 60 and builds `existing_objects =
   [(obj.object_type.name, obj.object_id) for obj in existing.objects]` at 
lines 80-82,
   capturing a snapshot of current relationships.
   
   3. Before client A reaches `UpdateTagCommand(request.id, properties).run()` 
at line 90 in
   `superset/mcp_service/tag/tool/update_tag.py`, have client B add an 
additional association
   to the same tag via `POST /api/v1/tag/<object_type>/<object_id>/` handled by
   `TagRestApi.add_objects` in `superset/tags/api.py:68-123`. That path calls
   `CreateCustomTagCommand(object_type, object_id, tags).run()` at line 122, 
which ultimately
   uses `TagDAO.create_custom_tagged_objects` (`superset/daos/tag.py:45-70`) to 
add a new
   `TaggedObject` row for this tag.
   
   4. When client A resumes, it calls `UpdateTagCommand(request.id, 
properties).run()` at
   `superset/mcp_service/tag/tool/update_tag.py:90` with 
`properties["objects_to_tag"]` set
   to the stale `existing_objects` snapshot. Inside `UpdateTagCommand.run()`
   (`superset/commands/tag/update.py:39-47`),
   
`TagDAO.create_tag_relationship(objects_to_tag=self._properties.get("objects_to_tag",
 []),
   tag=self._model)` is invoked at line 44. `create_tag_relationship` in
   `superset/daos/tag.py:31-89` computes `current_tagged_objects` from 
`tag.objects`
   (including the new association) and `updated_tagged_objects` from the stale 
list. Because
   `bulk_create` defaults to `False`, it calculates `tagged_objects_to_delete =
   current_tagged_objects - updated_tagged_objects` at lines 60-64 and deletes 
those
   relationships at lines 73-81, removing the concurrently added `TaggedObject` 
despite
   client A never requesting its deletion.
   ```
   </details>
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d2eae8addd7d4f4b9550d3295a9ed3ae&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=d2eae8addd7d4f4b9550d3295a9ed3ae&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/mcp_service/tag/tool/update_tag.py
   **Line:** 80:90
   **Comment:**
        *Race Condition: Relationship preservation is based on a pre-fetched 
snapshot of `existing.objects`, but `UpdateTagCommand` applies destructive 
relationship sync (`bulk_create=False`), so concurrent tag-association changes 
made after this read can be deleted unintentionally. Fetch and lock the 
tag/relationships in the same transaction used for update, or add a 
non-destructive update mode in the command layer to avoid stale-snapshot 
deletions.
   
   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%2F40358&comment_hash=c47aa320b58ad07f26a9c1a555196727fc5b2dc1ec961c746c40b3daf18a37cb&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40358&comment_hash=c47aa320b58ad07f26a9c1a555196727fc5b2dc1ec961c746c40b3daf18a37cb&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