From 6454e881e92aa4003f7860169f88378cc5a5e57e Mon Sep 17 00:00:00 2001
From: Jens Kraemer <jk@jkraemer.net>
Date: Mon, 30 Oct 2023 13:46:09 +0800
Subject: [PATCH 2/2] switch tx isolation level to READ-COMMITTED for MySQL /
 MariaDB

- "Repeatable Read" means that MySQL creates a snapshot at the start of the
  transaction (when the first select is made). Any subsequent SELECTs will
  work on that snapshot.
- the transaction is implicitly opened by Rails when Issue#save is called
- the nested set is locked later, in the after_save hook of issue_nested_set
- this time gap between snapshot creation and locking leaves room for
  race conditions.
- example for a failing sequence (assuming issues 2 and 3 are part of the same nested set)
  - A starts transaction to update issue 2
  - B starts transaction to update issue 3
  - several SELECTs are made by A and B (during validations etc), each now
    work on their own snapshot, not seeing modifications made by the other
  - B locks and modifies the nested set
  - A attemts to lock the same tree, has to wait
  - B commits
  - A locks the tree, but still has the old snapshot, so it doesn't see the changes made by B
  - A now works on the set with stale data, which may lead to a corrupted tree and stale record errors

Another possible solution / workaround would be to move the whole nested set
manipulation to a separate transaction. This could be done by moving it into
an after_commit hook and opening a new transaction in which the snapshot is
created with the SELECT ... FOR UPDATE.
---
 config/initializers/09-mysql-tx-isolation.rb | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
 create mode 100644 config/initializers/09-mysql-tx-isolation.rb

diff --git a/config/initializers/09-mysql-tx-isolation.rb b/config/initializers/09-mysql-tx-isolation.rb
new file mode 100644
index 000000000..6ee62dbbc
--- /dev/null
+++ b/config/initializers/09-mysql-tx-isolation.rb
@@ -0,0 +1,19 @@
+# MySQL / MariaDB default to a tx isolation level of "REPEATABLE READ". This
+# patch sets the tx isolation level to "READ COMMITTED" for the duration of the
+# connection.
+#
+# Reason: Repeatable Read semantics break the current implementation of the
+# issue nested set model on MySQL when parallel modifications to the same tree
+# happen.
+#
+module Mysql2ReadCommittedIsolation
+  private
+
+  def configure_connection
+    super.tap do
+      execute("SET SESSION tx_isolation='READ-COMMITTED'")
+    end
+  end
+end
+
+ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend Mysql2ReadCommittedIsolation
-- 
2.42.0

