Repository navigation
Conversation
The lock loaded each belongs_to parent through its association before locking it. That's a plain read before the lock, which on MySQL fixes the transaction's snapshot, so a save that then waited for the lock read positions from before the wait. The parent's default scopes also applied to the lock. Parents are now locked by primary key, using the record's foreign key values, selecting only ids and ignoring default scopes. When no parent row gets locked (a nil key, or a key with no row behind it), the scope's records are locked instead, as before. On its own this makes things worse where a validation reads before the lock: fewer saves fail with RecordNotUnique, and more commit with a gap. The next commit reads current positions in that case. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At MySQL's default isolation level, a transaction's first plain read fixes what its later plain reads see. When that read came before our lock (a validation, a callback, the app's own query), the positions we read after waiting for the lock could be from before the wait, leaving gaps, duplicates, misplaced records or unique index violations. A locking read sees what's current, so on MySQL at REPEATABLE READ, if the transaction has already sent something when we take the lock, the positions are read with LOCK IN SHARE MODE. The shared locks are only there to see what's current, since the scope lock already keeps other position writers out, so we read as little as we can: the end of the list, the record's own row, the entry at a requested position, and a relative record's entry, reading its row only if it has moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Locking a parent by key needs its primary key and columns. In a process that hasn't loaded the parent's schema yet, Rails loads it inside the open transaction, and on MySQL those schema queries fix the REPEATABLE READ snapshot. We checked whether the snapshot might be stale before that happened, so a save that read nothing else could still read positions from before the lock wait. The relations to lock are now built first, which loads any schema they need, and the snapshot is checked after that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The healer found each scope's parent through its association, so the parent's default scope applied, and a hidden parent came back nil. The healer then locked the scope's records, while saves now lock the parent row by key. The two no longer excluded each other: on PostgreSQL, an append that committed while the healer was renumbering was flipped to a negative position. The healer now takes the lock through Mechanisms#lock_positioning_scope!, so it always takes the same lock as a save to the same list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the snapshot may be stale, we read the record's own row with a shared lock, then wrote to it. A transaction that already held a shared lock on that row and then wrote to it deadlocked with us. That includes MySQL's foreign key check: posting a comment on an item takes a shared lock on the item, and `touch: true` then updates it. So posting a comment on an item while someone moved it deadlocked every time, as long as the move had read something first or was changing lists. A save that reads its own row nearly always goes on to write it, so the row is now locked for update up front. The other transaction's write then goes ahead, and we wait for it to commit, as we already did on main. The exception is assigning a record the position it already has, which now holds an exclusive lock on its row without writing it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An independent attack on this branch found three patterns where the shared locks turn waits into deadlocks on MySQL: bulk writes across a list during a move, saves in neighbouring lists, and edits of the last record of a list with a default scope followed by a touch of the parent. It also found that without a [scope, position] index the reads lock every record in the list, and with an index on the position column alone, records in other lists too. The README said none of this. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved stale-snapshot and source-scope locking defects can leave positions negative or introduce gaps during concurrent writes.
4 open issues
What changed in this PR
This PR addresses stale MySQL transaction snapshots that can corrupt list positions during concurrent saves. It updates the positioning callbacks’ locking and read behavior and documents the added concurrency costs.
Changes:
- Lock scope parents directly by key and share scope-locking logic with healing.
- Detect potentially stale MySQL snapshots and use targeted locking reads for positions.
- Add regression tests and document lock waits, deadlocks, and READ COMMITTED as an alternative.
| File | Description |
|---|---|
test/test_positioning.rb |
Adds stale-snapshot, concurrency, and parent-locking tests. |
test/test_healing.rb |
Tests locking parents hidden by default scopes. |
README.md |
Explains MySQL locking costs and isolation options. |
lib/positioning/snapshot.rb |
Adds adapter, transaction-state, and isolation checks. |
lib/positioning/mechanisms.rb |
Locks parents by key and adds current-position reads. |
lib/positioning/healer.rb |
Reuses the scope-locking method used by saves. |
lib/positioning.rb |
Loads the new snapshot helper. |
CHANGELOG.md |
Records the MySQL fix and locking trade-offs. |
Review effort: Max
| @model.where(scope_record.slice(*scope_columns)).reorder(primary_key).lock.ids | ||
| end | ||
|
|
||
| Mechanisms.new(scope_record, @column).lock_positioning_scope! |
There was a problem hiding this comment.
Fixed in 46cac44. After the scope lock, sequence now reads both the ids to renumber and the lowest position with locking reads, so on MySQL they're current even when the transaction has already read. A record appended after that first read is now renumbered with the rest, so it isn't left at a negative position.
test_healing_when_the_list_grows_after_a_read covers this. It reads the list inside a transaction, another thread appends "F", and then it heals. The list ends up as A to F at positions 1 to 6.
| end | ||
|
|
||
| def lock_positioning_scope! | ||
| record_in_database = record_scope.first if @positioned.persisted? && positioning_scope_changed? |
There was a problem hiding this comment.
Fixed in aa1335e. After locking the list the record was loaded in and the list it's moving to, the save rereads the record's row. If the record is now in another list, the save locks that list too, and it repeats this until the record stays put. test_moving_between_scopes_after_another_transaction_moved_it_to_a_third_list covers this.
On PostgreSQL, that reread takes no row lock, so the list is locked before the row, as you suggested. On MySQL, once the transaction has read, a locking read is the only way to see which list the row is in now. InnoDB holds that lock until commit, so the third list's lock comes after the row lock.
I checked what that does on MySQL with a scratch test, which isn't in the PR. Another transaction held the third list's lock and then updated the record's row. MySQL rolled one transaction back with ActiveRecord::Deadlocked, and all three lists stayed contiguous. Before this fix, the same overlap left a gap without any error. The deadlock can only happen when the record really has moved since it was read, and the PR description covers it.
| level = transaction.try(:isolation) || transaction.isolation_level | ||
| return level == :repeatable_read if level | ||
|
|
||
| connection.show_variable("transaction_isolation") == "REPEATABLE-READ" |
There was a problem hiding this comment.
Not changing this. Positioning supports MySQL, PostgreSQL and SQLite; it doesn't test or support MariaDB. MySQL has had transaction_isolation since 5.7.20, and the versions without it have been end of life since 2023.
| next unless payload[:sql].match?(matching) | ||
|
|
||
| other_thread = Thread.new { ActiveRecord::Base.connection_pool.with_connection { concurrent.call } } | ||
| other_thread.join(0.5) |
There was a problem hiding this comment.
Fixed in 8f864aa. The helper now waits up to 3 seconds for the concurrent change and asserts that it finished. If it hasn't, the test fails with "the concurrent change hadn't finished when the save carried on". Before, the save carried on after 0.5 seconds and could take the lock first, and the test then failed with a list that didn't match.
after_first_query runs the concurrent change in another thread and waited up to half a second for it, then let the save carry on whether it had finished or not. Every test using it expects the change to land before the save continues, so a slow run (a slow connection checkout on a busy CI machine) failed later with a confusing list mismatch instead of saying what went wrong. It now waits up to three seconds and fails with that message if the change still hasn't finished. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The healer locks the scope, then read the ids to renumber and the lowest position with plain reads. On MySQL at REPEATABLE READ, healing inside a transaction that had already read (including the healer's own query for the scopes, which then runs inside that transaction) took those reads from the old snapshot. A record another transaction appended after that read, but before the lock, was missing from the ids yet included in the final update over the whole scope, so it was left with a negative position. It now reads both with locks, which always see the latest committed rows. The healer goes on to update every one of these rows, so this doesn't lock any row it wasn't already going to lock. On PostgreSQL the read takes FOR UPDATE row locks, which are stronger than the ones its updates take, so inserts of rows that reference these records by foreign key wait until that scope's healing commits. SQLite ignores the locks. The new test fails on MySQL without this: the appended record ends up first, with a negative position. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
To move a record between lists, the save reads which list it's in with a plain read, locks that list and the new one, and later contracts the list the record is in by then, read again with a current read. When another transaction moved the record to a third list in between (after our plain read, or before it on MySQL when the snapshot was already fixed), the save contracted that third list without holding its lock. A save to the third list at the same time could then read its end before our contract committed and append after it, leaving a gap. On main the same move contracts the list the record used to be in, which is worse. After taking its locks, the save now reads where the record is now (with a lock when the snapshot may be stale), and if that's a list it hasn't locked, locks it too, repeating until the record stays put. Once it holds the lock of the list the record is in, no other positioning save can move the record out of it. In the usual case this is one extra read per move between lists, and on MySQL it takes the record's row lock just before position_was would have taken it anyway. Only when the record really has moved does the extra list lock come after that row lock, so it can deadlock with a save to that list; a deadlock raises, where the old behaviour left a silent gap. The two lock-count unit tests stub this out so they keep counting only the scope locks. The new test fails on PostgreSQL and MySQL without the change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The note said READ COMMITTED avoids our extra locks and that FOR UPDATE stops guarding gaps. It now also says: - the other deadlocks still happen, so transactions still need retrying. - list.with_lock(isolation: :read_committed) sets the level and locks the list first, which also avoids the foreign key deadlock. - Rails only takes an isolation level when a transaction starts. Inside another transaction it raises TransactionIsolationError, which is also why positioning can't set it from its callbacks. - what it costs an app: a find-or-create guarded by a lock can create two rows, two plain reads can disagree, and MySQL refuses writes when binlog_format is STATEMENT (error 1665, checked on MySQL 9.7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>


At MySQL's default isolation level (REPEATABLE READ), a transaction's first plain read fixes what its later plain reads see. Positioning takes its lock and then reads positions. If anything in the transaction read before the lock, those reads still see the list as it was before the wait, not what other transactions committed while this one waited. Positions are then worked out from old data. That leaves gaps, duplicate positions and records in the wrong place, or raises
ActiveRecord::RecordNotUniquewhen there's a unique index on the scope and position.On
mainthis happens on nearly every save, not only when the app reads first. The lock loads eachbelongs_toparent through its association with a plain read, then locks it:PostgreSQL and SQLite aren't affected at their defaults. PostgreSQL's READ COMMITTED gives each statement a fresh snapshot, and SQLite runs one writer at a time.
This PR fixes the silent corruption on MySQL. In exchange, some patterns deadlock more often than on
main. See What this costs.Fix
1. Lock scope parents by key, without loading them. Each
belongs_toparent is locked withParent.base_class.unscoped.where(primary_key => <the record's foreign key>).lock.ids. A save on its own now reads nothing before the lock, and the lock no longer goes through the parent's default scopes. When no parent row gets locked (anilforeign key, or one with no row behind it), the scope's records are locked instead, as #76 does for anilparent. This runs on every database.On its own, this commit makes things worse on MySQL wherever a validation reads before the lock. Saves that used to fail with
RecordNotUniquenow wait for the lock and commit a gap. In the workload below, it left a gap in 50 of 50 rounds with either validation, and 0 of 50 with none.2. Read current positions when the snapshot may be stale. A locking read sees what's current. So on MySQL at REPEATABLE READ, if the transaction has already sent something when we take the lock, positions are read with a lock. The scope lock already keeps out other transactions that write positions, so these locks are only there to see what's current. They're kept to as few reads as possible:
ORDER BY position DESC LIMIT 1 LOCK IN SHARE MODEinstead ofMAX. With a[scope, position]index, that's one index entry, not the last record's row.FOR UPDATE, because the save is about to write it anyway.before:andafter:, the index entry at the relative record's position in the snapshot, read with a shared lock. The relative record's own row is read with a lock only if it has moved since.The MySQL-specific part is
lib/positioning/snapshot.rb. The snapshot may be stale when all three of these are true:mysqlortrilogy).current_transaction.materialized?.isolation:option if Rails has one. Otherwise it comes fromSELECT @@transaction_isolation, which is one extra query per save.A save that hasn't read before the lock reads exactly as it does on
main.3. Fixes from an independent attack on the first two commits. Two reviewers tried to break this PR: one went after correctness, the other after harm to apps. Every finding below was reproduced again before it was fixed.
Mechanisms#lock_positioning_scope!, so it always takes the same lock as a save to the same list. On MySQL,maingot this case wrong too, and it now comes out right.touch: true, while someone moved the item deadlocked 10 of 10 times, wheremaindeadlocked 0 of 10. With the row readFOR UPDATE, it's 0 of 10 again. The one cost is when a record is assigned the position it already has: it now holds an exclusive lock on its row without writing it.4. Document the deadlocks that remain, in the README's note for MySQL users.
5. Fixes from the Copilot review.
FOR UPDATElocks are stronger than the ones its updates take, so inserts that reference those records by foreign key wait until that scope's healing commits.mainthe wrong list gets contracted. After locking, the save now rereads where the record is and locks that list as well. That's one extra read per move between lists. Only when the record really has moved does the extra list lock come after the record's row lock, where it can deadlock with a save to that list; the deadlock raises, where before the gap was silent.tx_isolationwhentransaction_isolationis missing. That variable is only missing on MariaDB before 11.1 and on MySQL before 5.7.20 (end of life since 2023).Measurements
MySQL 9.7.4, locally, with a probe harness that isn't part of this PR. Everything here was measured on the final code unless it says otherwise. These test models are used:
Item: scoped to a list, with a unique[list_id, position]index.NewItem: scoped to a list, with no index on position.Author: single table inheritance, scoped to a list andenabled, with a unique[list_id, enabled, position]index.Stale reads. Each run starts a transaction and reads the list, which fixes the snapshot. Another transaction then commits one of 6 changes:
:lastThen our transaction makes one of 12 changes:
:lastbefore:andafter:another recordafter:another recordEach of the 72 pairs is compared with running the two changes one after the other.
mainAuthorRecordNotUniqueItemRecordNotUniqueNewItemBefore the attack-round fixes, the second commit also got all 72 right on Rails 7.2 and 8.0, and with prepared statements.
Ways to reach a save. There are 11 ways in:
saveupdateupdatelist.items.createlist.items << itemItem.transaction,List.transactionandActiveRecord::Base.transactionItem.transactionorList.transactionlist.saveEach one reads before the lock, through a validation, the attribute writer or the app's transaction, while another transaction creates a record at position 1. On
main, 8 raiseRecordNotUniqueand 3 put the new record in the wrong place. With this PR, all 11 are right.Ordinary concurrent saves. There are 50 rounds, each on a new list of 8 records. In each round, six operations run at once, as separate requests would, with no app transactions:
:lastafter:another recordmainItem, noneRecordNotUniqueItem,validates_presence_of :listRecordNotUniqueItem, a validation that queries the tableRecordNotUniqueNewItem, a validation that queries the tableBefore the attack-round fixes, a randomised run against a model of the expected result found no wrong lists, where
maingot nearly every round wrong in the same modes. It covered 13 model setups:niland missing parentsThe saves ran with prior reads, validations, savepoints and rollbacks.
Locks held. These are the record locks a transaction holds after one position write that read first, from
performance_schema.data_locks.mainItem, create at the endItem, create at 1Item, move to:lastItem, move to the next listItem, destroy the last recordNewItem, create at the endNewItem, move to:lastNewItemhas no index on position, so reading the end of its list takes shared locks on every one of its rows. With an index on the position column alone, the reads also take shared locks in other lists. For example, before the attack-round fixes, an append after a read took 25 locks, 18 of them in other lists, wheremaintook 3.What this costs
These deadlocks happen more often than on
main. They only happen on MySQL at REPEATABLE READ, when the save has read before the lock or is moving a record to another list. They were measured on the final code:mainDeadlocked, 596RecordNotUnique, 9 of 50 lists brokenDeadlocked, nothing else, no broken listsDeadlocked, 330RecordNotUnique, 8 of 100 lists brokenDeadlocked, nothing else, no broken listsupdate_all,in_batches,deleteorupdate_columnon a list, while a move in it is paused before its first writeSo overall, fewer saves fail than on
main, and none of them fail silently. Some patterns that never deadlocked onmainnow do, and an app that hits them will need to retry.There are two causes:
move_out_of_the_way(position 0) and the negative positions inexpandandcontractinsert into that gap. We're looking into whether positions could be shifted another way.main, the move holds no row locks before its first write. Locking the own row for update didn't change these numbers.Other changes the attack found, all rare:
List.create!then waits until the saving transaction ends. This happens on every save to a list whose parent row doesn't exist, whether or not it read first.main, the save raisesRecordNotFound. Here, the lock by key finds no row and falls back to locking the scope's records, so the record is saved into a list that no longer exists. A foreign key constraint on the parent stops this.Positioning::Error. "relativepositionrecord must be in the same scope" is now raised on MySQL when the relative record was destroyed or moved after the snapshot. Before,mainpositioned the record from the old data. PostgreSQL onmainalready raises this.Gaps in the fix, where
mainis just as wrong:transaction(isolation: :read_committed)still takes the locks.SET TRANSACTION ISOLATION LEVEL. It isn't detected on any Rails version.Who this changes things for
mainfound no parent and locked the scope's records instead. This PR now locks the parent row.The README's note for MySQL users explains what's locked, what waits, which patterns deadlock more often, and how to opt out with READ COMMITTED, including what that changes for the rest of an app and why we can't set it from our callbacks.
Tests
TestReadsAfterTheLockhas 20 tests. They run on MySQL and PostgreSQL, and are skipped on SQLite.main.TestSnapshothas 10 tests. They cover when the snapshot counts as stale (outside a transaction, before anything is sent, nested, READ COMMITTED on the transaction or the connection), that only MySQL reads with a shared lock, and that a save that hasn't read is unchanged.The full suites pass on SQLite, PostgreSQL and MySQL with Rails 8.1, and on MySQL with Rails 7.2 and 8.0.
Not done yet
#77
#77 (stable lock order) turns two MySQL deadlocks into silent gaps without this PR, which is why its CI fails on MySQL. With this PR's first two commits and #77's ordering merged by hand, #77's three swap tests and the full MySQL suite pass. #77 will need rebasing onto this PR, because its ordering has to sort the parent rows that are now locked by key.
Changelog: Fix gaps, duplicate positions, misplaced records and unique index violations on MySQL when saves to the same list overlap. At REPEATABLE READ, a transaction's first read fixes what it sees. When that read came before our lock, the transaction couldn't see what others committed while it waited. A scope's
belongs_toparent is now locked by its key, without loading it first or going through its default scope, so a save on its own reads nothing before the lock. When something else has read first (a validation, a callback or your own query), positions are read with locks. That can make other writers wait, and makes some deadlocks more likely. See the Concurrency section of the README.🤖 Generated with Claude Code