Skip to content

Commit 4684851

Browse files
waterclauderusackas
authored
fix(import): isolate per-tag import in a SAVEPOINT to avoid poisoned session (#42912) (#42920)
Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: Evan Rusackas <evan@preset.io>
1 parent e7139a7 commit 4684851

2 files changed

Lines changed: 104 additions & 20 deletions

File tree

‎superset/commands/importers/v1/utils.py‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -318,27 +318,39 @@ def import_tag(
318318

319319
for tag_name in target_tag_names:
320320
try:
321-
tag = existing_tags.get(tag_name)
322-
323-
# If tag does not exist, create it
324-
if tag is None:
325-
description = tag_descriptions.get(tag_name, None)
326-
tag = Tag(name=tag_name, description=description, type="custom")
327-
db_session.add(tag)
328-
existing_tags[tag_name] = tag # Update the existing_tags dictionary
329-
330-
# Ensure the association with the object
331-
tagged_object = (
332-
db_session.query(TaggedObject)
333-
.filter_by(object_id=object_id, object_type=object_type, tag_id=tag.id)
334-
.first()
335-
)
336-
if not tagged_object:
337-
new_tagged_object = TaggedObject(
338-
tag_id=tag.id, object_id=object_id, object_type=object_type
321+
# Isolate each tag operation in a SAVEPOINT so a failure (e.g. a
322+
# concurrent unique-constraint violation) rolls back only the failed
323+
# tag and leaves the session usable for the remaining tags, instead
324+
# of poisoning the session with a pending-rollback state.
325+
with db_session.begin_nested():
326+
tag = existing_tags.get(tag_name)
327+
328+
# If tag does not exist, create it
329+
if tag is None:
330+
description = tag_descriptions.get(tag_name, None)
331+
tag = Tag(name=tag_name, description=description, type="custom")
332+
db_session.add(tag)
333+
existing_tags[tag_name] = tag # Update the existing_tags dictionary
334+
335+
# Ensure the association with the object
336+
tagged_object = (
337+
db_session.query(TaggedObject)
338+
.filter_by(
339+
object_id=object_id, object_type=object_type, tag_id=tag.id
340+
)
341+
.first()
339342
)
340-
db_session.add(new_tagged_object)
343+
if not tagged_object:
344+
new_tagged_object = TaggedObject(
345+
tag_id=tag.id, object_id=object_id, object_type=object_type
346+
)
347+
db_session.add(new_tagged_object)
341348

349+
# Only record the tag as imported once the SAVEPOINT has been
350+
# released (and its pending inserts flushed) without error; the
351+
# nested block's own flush can still fail on a concurrent
352+
# unique-constraint violation, in which case this line must not
353+
# run.
342354
new_tag_ids.append(tag.id)
343355

344356
except SQLAlchemyError as err:
@@ -349,7 +361,9 @@ def import_tag(
349361
object_id,
350362
err,
351363
)
352-
continue # No need for manual rollback, handled by transaction decorator
364+
# The SAVEPOINT was rolled back by begin_nested(); the session is
365+
# still usable for the remaining tags.
366+
continue
353367

354368
# Remove old tags not in the new config
355369
for tag in existing_assocs:

‎tests/unit_tests/charts/commands/importers/v1/import_test.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@
1919
import copy
2020
from collections.abc import Generator
2121
from datetime import datetime, timezone
22+
from typing import Any
2223
from unittest.mock import patch
2324

2425
import pytest
2526
import yaml
2627
from flask_appbuilder.security.sqla.models import Role, User
2728
from pytest_mock import MockerFixture
29+
from sqlalchemy.exc import SQLAlchemyError
2830
from sqlalchemy.orm.session import Session
2931

3032
from superset import security_manager
@@ -506,3 +508,71 @@ def test_import_tag_logic_for_charts(session_with_schema: Session):
506508
.all()
507509
)
508510
assert len(associated_tags) == 0
511+
512+
513+
def test_import_tag_savepoint_keeps_session_usable(
514+
mocker: MockerFixture, session_with_schema: Session
515+
) -> None:
516+
"""
517+
When a single tag operation fails with a SQLAlchemyError (e.g. a unique
518+
constraint violation from a concurrent import), the per-tag SAVEPOINT
519+
isolates the failure so the session is not left in a pending-rollback
520+
state, and the remaining tags still import successfully.
521+
"""
522+
contents = {
523+
"tags.yaml": yaml.dump(
524+
{
525+
"tags": [
526+
{"tag_name": "tag_1", "description": "Description for tag_1"},
527+
{"tag_name": "tag_2", "description": "Description for tag_2"},
528+
]
529+
}
530+
)
531+
}
532+
533+
object_id = 1
534+
object_type = "chart"
535+
536+
# Simulate a unique-constraint violation discovered when the first
537+
# TaggedObject's SAVEPOINT is flushed (e.g. a concurrent import already
538+
# created the same association) -- not synchronously from Session.add().
539+
# `import_tag`'s own pre-insert existence check would normally catch a
540+
# real duplicate row, so the failure is injected at the point SQLAlchemy
541+
# actually persists the pending row: `begin_nested()`'s implicit flush
542+
# on a successful `with` exit, which calls `Session.flush()` directly
543+
# (see `SessionTransaction._prepare_impl`).
544+
pending_tagged_objects: list[TaggedObject] = []
545+
original_add = session_with_schema.add
546+
547+
def tracking_add(obj: object) -> None:
548+
if isinstance(obj, TaggedObject):
549+
pending_tagged_objects.append(obj)
550+
original_add(obj)
551+
552+
original_flush = session_with_schema.flush
553+
554+
def flaky_flush(*args: Any, **kwargs: Any) -> None:
555+
# Only the first TaggedObject ever added should fail, and only while
556+
# it's still pending -- once its SAVEPOINT rolls back, SQLAlchemy
557+
# expunges it from the session, so this does not also fail tag_2's
558+
# flush.
559+
if (
560+
pending_tagged_objects
561+
and pending_tagged_objects[0] is not None
562+
and pending_tagged_objects[0] in session_with_schema.new
563+
):
564+
raise SQLAlchemyError("UNIQUE constraint failed: tagged_object")
565+
original_flush(*args, **kwargs)
566+
567+
mocker.patch.object(session_with_schema, "add", side_effect=tracking_add)
568+
mocker.patch.object(session_with_schema, "flush", side_effect=flaky_flush)
569+
570+
with patch.object(feature_flag_manager, "is_feature_enabled", return_value=True):
571+
new_tag_ids = import_tag(
572+
["tag_1", "tag_2"], contents, object_id, object_type, session_with_schema
573+
)
574+
575+
# tag_1 failed on the unique violation, but tag_2 succeeded.
576+
assert len(new_tag_ids) == 1
577+
# The session is still usable — no PendingRollbackError.
578+
assert session_with_schema.query(TaggedObject).count() == 1

0 commit comments

Comments
 (0)