Skip to content

fix(tags): make owner-tag creation safe under concurrent creates - #45498

Merged
aminghadersohi merged 5 commits into
apache:masterfrom
mikebridge:sc-128276-owner-tag-race
Oct 20, 2026
Merged

aminghadersohi merged 5 commits into
apache:masterfrom
mikebridge:sc-128276-owner-tag-race

Conversation

@mikebridge

@mikebridge mikebridge commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

What users saw

Charts created at the same time by the same user can fail with "Chart could not be created" (HTTP 422).

Why, in plain terms

Each chart gets an implicit tag identifying its editor. Two requests can both check for that tag before either has created it. One succeeds; the other tries to create the same tag and the database rejects the duplicate, failing chart creation too.

What this changes

The losing request reuses the matching tag created by the other request, without losing or committing the chart's surrounding transaction. The same protection applies to implicit tag-to-object links, including editor updates and favorites. The helper no longer commits db.session midway through custom-tag commands; their existing transaction boundary owns the commit.

This removes the most common Playwright flake identified on master: chart-list.spec.ts setup failing to create a chart with tag_name_key / duplicate editor:1. A scan of 26 Playwright jobs across 13 master push runs found this error in 18 jobs; retries let those jobs finish successfully. Examples: 39273032055, 39085487476, and 39304186168.

Technical details:

  • Insert and flush the candidate inside a SAVEPOINT. Recover an integrity error only when the exact matching tag or association exists; propagate other errors.
  • Log an error identifying the name when a tag of a different type already owns it; the original error is still raised.
  • Conflict recovery assumes Superset's default READ COMMITTED isolation on PostgreSQL and MySQL. Shared recovery reads do not make MySQL REPEATABLE READ deadlock-safe; an operator-selected stronger isolation level can require retrying the whole outer transaction.
  • Explicitly begin SQLite's outer transaction when needed, so releasing a first-write savepoint does not commit it.
  • Keep commit/rollback ownership with the caller; no migration or new dependency.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable: backend-only fix. Before, a duplicate implicit tag can fail chart creation; after, the existing tag is reused and chart creation continues.

TESTING INSTRUCTIONS

Run:

python -m pytest tests/unit_tests/tags tests/unit_tests/charts/dao tests/unit_tests/charts/commands -q
python -m pytest tests/integration_tests/tags/race_tests.py -q
pre-commit run --files superset/tags/models.py tests/unit_tests/tags/models_test.py tests/unit_tests/tags/race_test.py tests/integration_tests/tags/race_tests.py

Local result: 110 focused unit tests passed; changed-file hooks passed, including MyPy. New database-backed unit tests drive a real chart INSERT through its tagging listener with a deterministic stale lookup, and cover editor/type tags, caller commit and rollback, duplicate associations, favorites, and unrelated integrity errors. Restoring the original production code makes 12 of the 13 new unit cases fail; the remaining case already guards failure propagation. Restoring the fix makes all 13 pass.

The unit insert/transaction tests use disposable SQLite tables. The integration test uses two real connections on PostgreSQL/MySQL: it coordinates a competing INSERT, verifies reuse of the winning tag id, and verifies that the losing transaction can commit additional work. On disposable PostgreSQL 16 and MySQL 8 under READ COMMITTED, the test failed with master's get_tag (PostgreSQL tag_name_key / MySQL 1062) and passed with the candidate on both. SQLite skips this integration test. The full unit suite and Playwright were not run locally; no new browser run is claimed by the flake diagnosis above.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags: existing TAGGING_SYSTEM enables implicit tagging; no default change.
  • 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

Isolate tag and implicit association inserts in savepoints so a competing request can reuse the exact winner without rolling back or committing its caller. Use current locking reads for MySQL and preserve SQLite outer transactions. Never reuse a different tag type, and log its conflicting name before propagating the original error.

Exercise the real chart insert listener with stale reads, caller rollback, duplicate links, and unrelated failures.
@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 83.60%. Comparing base (0a17a75) to head (07c7b6a).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
superset/tags/models.py 97.05% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #45498       +/-   ##
===========================================
+ Coverage   65.15%   83.60%   +18.45%     
===========================================
  Files        3053     3050        -3     
  Lines      200640   200281      -359     
  Branches    46820    46684      -136     
===========================================
+ Hits       130719   167442    +36723     
+ Misses      66981    29593    -37388     
- Partials     2940     3246      +306     
Flag Coverage Δ
hive 34.91% <11.76%> (-0.01%) ⬇️
mysql 52.87% <58.82%> (-0.01%) ⬇️
postgres 52.87% <58.82%> (-0.01%) ⬇️
presto 36.66% <47.05%> (+<0.01%) ⬆️
python 87.16% <97.05%> (+34.00%) ⬆️
sqlite 52.64% <58.82%> (-0.01%) ⬇️
unit 81.33% <97.05%> (?)

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 02:42
@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 because concurrent-insert recovery has an acknowledged isolation-level limitation.
  • The code notes that MySQL REPEATABLE READ can still deadlock during recovery, while the integration test only exercises READ COMMITTED.

Assessed commit: a7c2bada5934

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

LGTM, no blocking issues. Two non-blocking notes inline.

Real-backend results (two to eight concurrent connections, listener-style Session(bind=outer.connection()), contested editor:1 tag plus TaggedObject, outer transaction reused after recovery):

  • master: every losing writer fails with tag_name_key (PG) / 1062 (MySQL).
  • This PR, PostgreSQL 16 and MySQL 8.0 under READ COMMITTED (Superset's default for both via set_db_default_isolation): every writer succeeds, one tag, one link per object, outer transaction still usable. Same result for the TaggedObject race on a shared object.
  • PostgreSQL REPEATABLE READ: the loser still raises, as the description says.
  • MySQL REPEATABLE READ: see the inline note.

The Playwright flake matches: on master run 39273032055, chart-list.spec.ts retried after UniqueViolation ... "tag_name_key" ... (editor:1). On this PR, both playwright-tests jobs ran 90/90 with no retries. CI on efa158e: 57 pass, 15 skipped, 0 failing. With the master models.py restored, 12 of the 13 new race_test.py cases fail.

Comment thread superset/tags/models.py Outdated
# Such failures are not recoverable tag conflicts.
if not session.is_active:
raise
# Locking reads see the winner even under MySQL REPEATABLE READ.

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.

non-blocking: "even under MySQL REPEATABLE READ" overstates it. Under REPEATABLE READ, eight concurrent first-time chart creates (each resolving new editor:1, editor:2 and type:chart) deadlock in 5/5 runs. InnoDB's duplicate-key check takes next-key S locks, and the losers' subsequent tag inserts conflict on those gaps. InnoDB then rolls back the victim's whole transaction, and begin_nested()'s ROLLBACK TO SAVEPOINT turns the 1213 into (1305, 'SAVEPOINT sa_savepoint_N does not exist'), which is misleading in logs. With 2–3 writers it passed, and READ COMMITTED passed 15/15. This is still strictly better than master, where every loser fails. Since READ COMMITTED is now the enforced default, consider making this comment and the description state the READ COMMITTED assumption for MySQL the same way they already do for PostgreSQL, rather than claiming REPEATABLE READ safety.

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.

Good catch—corrected the comment in a7c2bad and the description to state the READ COMMITTED assumption for both backends. The misleading deadlock/savepoint diagnostic is left for a separate follow-up; this doesn't promise REPEATABLE READ safety.

with (
patch("superset.tags.models.tagging_enabled", return_value=True),
patch.object(ChartUpdater, "get_editor_user_ids", return_value=[1]),
patch.object(Query, "one_or_none", stale_lookup),

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.

non-blocking: These cases only simulate the stale read on SQLite. There, with_for_update compiles to nothing and writers are serialized by the database lock, so the recovery read that matters for the reported PostgreSQL flake (and the MySQL locking read) is never run against a backend that can actually race. A small two-connection test under tests/integration_tests/tags/ (next to mysql_compatibility_test.py) would run in test-postgres/test-mysql. Pattern: open connection A, get_tag("editor:1", Session(bind=a_conn), ...) without committing; in a thread, connection B calls get_tag for the same name and blocks on the unique index; commit A; assert that B returns A's id and can still commit further work. It fails on master and passes here on both backends.

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 two-connection integration test in a7c2bad: it reuses the winning tag id and checks that the losing transaction can commit additional work. Verified it fails with master's get_tag and passes with the fix on both PostgreSQL 16 and MySQL 8 under READ COMMITTED.

Address fitzee's review by proving the real PostgreSQL/MySQL duplicate-key path can reuse the winner and commit subsequent work. Narrow the isolation comment to READ COMMITTED; locking reads do not guarantee MySQL REPEATABLE READ deadlock safety.
The master PNG-preview change grew the shared preview schema but left its recorded inventory stale. Regenerate the three affected tool entries, matching the refresh in apache#45311, so apache#45498 can exercise its unit-test gate without inherited inventory drift.

@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 chasing this down to the actual mechanism; the writeup made it easy to follow.

Approving. I raced chart creation through the API against a disposable PostgreSQL 16 and MySQL 8: 64 of 80 concurrent creates return the 422 on the merge base and 0 of 80 do at this head, and your race_tests.py genuinely races, failing on the merge base with tag_name_key and passing here. Two non-blocking notes inline, both about the comment and the coverage around the recovery read rather than the fix itself.

CI is green on 07c7b6a: 57 passing, 15 skipped, nothing failing or queued, and race_tests.py did run in both test-postgres and test-mysql.

Comment thread superset/tags/models.py
if not session.is_active:
raise
# Recovery assumes the default READ COMMITTED isolation.
# A locking read does not prevent MySQL REPEATABLE READ deadlocks.

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. @fitzee measured this on REPEATABLE READ, but I do not think it is specific to that level: InnoDB takes the gap S locks during its duplicate key check on READ COMMITTED too, which is what set_db_default_isolation enforces. Racing 8 first time editors on MySQL 8 under READ COMMITTED, 6 of 120 writers failed and every one of them reported (1305, 'SAVEPOINT sa_savepoint_1 does not exist'). SHOW ENGINE INNODB STATUS has the real cause: two inserts each holding a gap S lock before editor:3, each waiting for an insert intention X lock in that same gap. Master reports the underlying (1213, 'Deadlock found when trying to get lock; try restarting transaction') in the same scenario, which at least tells an operator to retry.

It is still a clear win there (114 of 120 against master's 60 of 120), so nothing to hold the PR for. Could this comment say READ COMMITTED instead, so the deferred diagnostic is not scoped to a level nobody runs?

Comment thread superset/tags/models.py
raise
# Recovery assumes the default READ COMMITTED isolation.
# A locking read does not prevent MySQL REPEATABLE READ deadlocks.
tag = query.with_for_update(read=True).one_or_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, more a question: nothing pins the with_for_update(read=True) on this line. With just that clause removed, tests/unit_tests/tags and the new race_tests.py both stay green on PostgreSQL, but on MySQL 8 the same 8 writer race drops from 34 of 40 recovering to 5 of 40, which is master's number. So the locking read looks like the one thing that makes recovery work under REPEATABLE READ, the level the comment above says is out of scope, and a no op under READ COMMITTED.

Worth pinning? A before_cursor_execute listener in race_tests.py asserting that the recovery SELECT on the losing connection is a locking read would run in both test-postgres and test-mysql, and would catch someone simplifying this line later.

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

LGTM. Checked the diff, sibling call sites and review threads at this head; CI is green and the tests cover the reported behavior.

@aminghadersohi
aminghadersohi merged commit fe79ab4 into apache:master Oct 20, 2026
72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants