Skip to content

Read current positions on MySQL when the snapshot may be stale - #94

Draft
brendon wants to merge 10 commits into
mainfrom
fix/mysql-current-reads
Draft

brendon wants to merge 10 commits into
mainfrom
fix/mysql-current-reads

Conversation

@brendon

@brendon brendon commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

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::RecordNotUnique when there's a unique index on the scope and position.

On main this happens on nearly every save, not only when the app reads first. The lock loads each belongs_to parent through its association with a plain read, then locks it:

BEGIN
SELECT `lists`.* FROM `lists` WHERE `lists`.`id` = 1 LIMIT 1               -- fixes the snapshot
SELECT `lists`.* FROM `lists` WHERE `lists`.`id` = 1 LIMIT 1 FOR UPDATE    -- the lock

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_to parent is locked with Parent.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 (a nil foreign key, or one with no row behind it), the scope's records are locked instead, as #76 does for a nil parent. 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 RecordNotUnique now 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:

  • The end of the list, read with ORDER BY position DESC LIMIT 1 LOCK IN SHARE MODE instead of MAX. With a [scope, position] index, that's one index entry, not the last record's row.
  • The record's own row (its position, and its old scope when the scope changes), read FOR UPDATE, because the save is about to write it anyway.
  • For an integer position, whether a record is at that position now, read with a shared lock. The end of the list is read only when the position is past it.
  • For before: and after:, 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:

  • The adapter is MySQL (its name matches mysql or trilogy).
  • A transaction is open, and it's nested or has already sent a statement. The second check uses Rails' internal current_transaction.materialized?.
  • The isolation level is REPEATABLE READ. It's taken from the transaction's isolation: option if Rails has one. Otherwise it comes from SELECT @@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.

  • Check the snapshot after building the scope locks. 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. On MySQL those schema queries fix the snapshot, after our check had already said it wasn't stale. The relations to lock are now built before the check.
  • Lock the healer's scope the way saves lock it. The healer still found each parent through its association. When the parent's default scope hid it, the healer locked the scope's records while saves locked the parent row, so the two didn't exclude each other. On PostgreSQL, an append during a heal ended up at position -6. The healer now calls Mechanisms#lock_positioning_scope!, so it always takes the same lock as a save to the same list. On MySQL, main got this case wrong too, and it now comes out right.
  • Lock the record's own row for update. The second commit first read the own row with a shared lock and then wrote it. That deadlocked with any transaction that already held a shared lock on the row and then wrote it. MySQL's foreign key check takes exactly that lock. So posting a comment on an item, with touch: true, while someone moved the item deadlocked 10 of 10 times, where main deadlocked 0 of 10. With the row read FOR 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.

  • Read the records the healer renumbers with locks. After its lock, the healer read the ids to renumber and the lowest position with plain reads. On MySQL, healing inside a transaction that had already read missed a record appended after that read, and the final update over the scope left it at a negative position. Both reads now take locks. The healer updates every one of those rows anyway. On PostgreSQL the read's FOR UPDATE locks are stronger than the ones its updates take, so inserts that reference those records by foreign key wait until that scope's healing commits.
  • Lock the list a record has moved to since it was read. When another transaction moved the record to a third list between our read of its list and our lock, the save contracted that third list without holding its lock, so an append to it at the same time could leave a gap. This happens on PostgreSQL too, and on main the 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.
  • Not changed: falling back to tx_isolation when transaction_isolation is 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 and enabled, 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:

  • insert at 1
  • append
  • destroy the first record
  • destroy the last record
  • move the last record to 1
  • move the first record to :last

Then our transaction makes one of 12 changes:

  • moves to 1, 5, 99 and :last
  • moves before: and after: another record
  • creates at the end, at 1, at 99 and after: another record
  • a destroy

Each of the 72 pairs is compared with running the two changes one after the other.

Model main This PR
Author 29 of 72 right: 15 in a different order, 12 with a gap, 16 RecordNotUnique 72 of 72 right
Item 29 of 72 right: 15 in a different order, 12 with a gap, 16 RecordNotUnique 72 of 72 right
NewItem 29 of 72 right: 15 in a different order, 28 with a gap 72 of 72 right

Before 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:

  • save
  • update
  • an attribute writer that reads during update
  • list.items.create
  • list.items << item
  • inside Item.transaction, List.transaction and ActiveRecord::Base.transaction
  • a read inside the app's own Item.transaction or List.transaction
  • autosaving a new item through list.save

Each 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 raise RecordNotUnique and 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:

  • two destroys
  • a move to :last
  • a move to 1
  • a create
  • a move after: another record
Model, validation main This PR
Item, none 19 of 50 rounds left a gap, 101 RecordNotUnique 0 of 50, no errors
Item, validates_presence_of :list 21 of 50, 88 RecordNotUnique 0 of 50, no errors
Item, a validation that queries the table 34 of 50, 61 RecordNotUnique 0 of 50, no errors
NewItem, a validation that queries the table 50 of 50, no errors 0 of 50, no errors

Before the attack-round fixes, a randomised run against a model of the expected result found no wrong lists, where main got nearly every round wrong in the same modes. It covered 13 model setups:

  • single table inheritance, polymorphic and self-referencing parents
  • composite primary keys, and two position columns
  • no scope at all
  • nil and missing parents

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

Operation, after a read main This PR
Item, create at the end 4 7
Item, create at 1 34 34
Item, move to :last 19 23
Item, move to the next list 21 24
Item, destroy the last record 4 4
NewItem, create at the end 13 25
NewItem, move to :last 12 22

NewItem has 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, where main took 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:

Pattern main This PR
Saves in two neighbouring lists, with one transaction paused after reading the end of its list 0 of 24 pairs deadlock 9 of 24 pairs deadlock
8 threads on 2 neighbouring lists, every save reading first, 2,400 saves 107 Deadlocked, 596 RecordNotUnique, 9 of 50 lists broken 368 Deadlocked, nothing else, no broken lists
8 threads on 4 lists, half the saves reading first, 2,400 saves 42 Deadlocked, 330 RecordNotUnique, 8 of 100 lists broken 55 Deadlocked, nothing else, no broken lists
A bulk update_all, in_batches, delete or update_column on a list, while a move in it is paused before its first write 6 of 42 pairs deadlock 21 of 42 pairs deadlock
A default-scoped model: edit the list's last record, then touch the parent, during an append 0 of 5 kinds of edit deadlock 5 of 5 deadlock

So overall, fewer saves fail than on main, and none of them fail silently. Some patterns that never deadlocked on main now do, and an app that hits them will need to retry.

There are two causes:

  • Neighbouring lists. Confirming where a list ends needs a lock on the gap after its last index entry. That's the same gap as the one before the next list's first entry. While the next list's positions shift, move_out_of_the_way (position 0) and the negative positions in expand and contract insert into that gap. We're looking into whether positions could be shifted another way.
  • Bulk writes. A bulk statement locks rows one by one through the list. It gets stuck on any row the move already holds, and the move then needs rows the statement has already locked. On 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:

  • A missing parent. Locking a parent id that has no row takes a gap lock on the parent table. On MySQL, 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.
  • A parent destroyed while a save waits for its lock. On main, the save raises RecordNotFound. 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.
  • A new Positioning::Error. "relative position record must be in the same scope" is now raised on MySQL when the relative record was destroyed or moved after the snapshot. Before, main positioned the record from the old data. PostgreSQL on main already raises this.

Gaps in the fix, where main is just as wrong:

  • A nested save inside a REPEATABLE READ transaction on a READ COMMITTED connection. On Rails 7.2 and 8.0, a savepoint has no isolation of its own, so the check reads the connection's level and misses it. The same gap means a nested save inside transaction(isolation: :read_committed) still takes the locks.
  • A manual SET TRANSACTION ISOLATION LEVEL. It isn't detected on any Rails version.

Who this changes things for

  • Every database:
    • The parent is no longer loaded to lock it, and its default scopes no longer apply to the lock. If a default scope hid the parent, main found no parent and locked the scope's records instead. This PR now locks the parent row.
    • The healer takes the same lock as a save.
  • MySQL at REPEATABLE READ, when the transaction has sent something before the lock: positions are read with locks that are held until the transaction ends, with the costs above.
  • MySQL at READ COMMITTED, PostgreSQL and SQLite: reads are unchanged.

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

  • TestReadsAfterTheLock has 20 tests. They run on MySQL and PostgreSQL, and are skipped on SQLite.
    • 13 change the list while a save is waiting, after it read through a validation, a callback, attribute assignment, an association create, autosave, the app's transaction, or Rails loading the parent's schema. On MySQL, all 13 fail on main.
    • 4 check that the shared locks don't hold up an edit of the last record or of a relative record, a move in the next list, or (with a default scope) the whole list.
    • 1 checks that a move doesn't deadlock with a transaction that holds a shared lock on the record and then writes it. On MySQL, it deadlocks when the own row is read with a shared lock.
    • 1 heals inside a transaction that read before another transaction appended to the list. On MySQL, it fails without the healer fix.
    • 1 moves a record between lists after another transaction moved it to a third list, and checks that the third list gets locked. It fails on MySQL and PostgreSQL without the fix.
    • The concurrent change in these tests now has to finish within 3 seconds, or the test fails saying so. Before, the save carried on after half a second whether the change had finished or not.
  • TestSnapshot has 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 parent is locked without being loaded, with only its id selected. A parent that's missing falls back to locking the scope's records.
  • The healer locks the parent by key when the parent's default scope hides it.

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

  • Measurements on MySQL 8.0 and 8.4. Everything measured above is 9.7.4. CI's tests pass on MySQL 8.4.13 (the ubuntu-26.04 runner's version), but the harness hasn't run on it.
  • The trilogy adapter.

#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_to parent 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

brendon and others added 2 commits November 28, 2026 15:30
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>
@brendon brendon added the concurrency Locking, isolation and race conditions label Nov 28, 2026
brendon and others added 4 commits November 28, 2026 23:37
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread lib/positioning/healer.rb
@model.where(scope_record.slice(*scope_columns)).reorder(primary_key).lock.ids
end

Mechanisms.new(scope_record, @column).lock_positioning_scope!

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread test/test_positioning.rb Outdated
next unless payload[:sql].match?(matching)

other_thread = Thread.new { ActiveRecord::Base.connection_pool.with_connection { concurrent.call } }
other_thread.join(0.5)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

brendon and others added 4 commits November 29, 2026 15:35
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

concurrency Locking, isolation and race conditions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants