Repository navigation
fix(tags): make owner-tag creation safe under concurrent creates - #45498
Conversation
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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
CodeAnt PR Risk: Medium Risk
Assessed commit: |
fitzee
left a comment
There was a problem hiding this comment.
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 theTaggedObjectrace 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.
| # Such failures are not recoverable tag conflicts. | ||
| if not session.is_active: | ||
| raise | ||
| # Locking reads see the winner even under MySQL REPEATABLE READ. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
| if not session.is_active: | ||
| raise | ||
| # Recovery assumes the default READ COMMITTED isolation. | ||
| # A locking read does not prevent MySQL REPEATABLE READ deadlocks. |
There was a problem hiding this comment.
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?
| 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() |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
LGTM. Checked the diff, sibling call sites and review threads at this head; CI is green and the tests cover the reported behavior.
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.sessionmidway through custom-tag commands; their existing transaction boundary owns the commit.This removes the most common Playwright flake identified on master:
chart-list.spec.tssetup failing to create a chart withtag_name_key/ duplicateeditor: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:
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:
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
TAGGING_SYSTEMenables implicit tagging; no default change.