Skip to content

ruflet_record: all threads share one transaction (a rollback erases another thread's committed writes, ids cross threads); update_columns/touch erase unrelated pending changes #124

Open

Description

@AdamMusa

Summary

Two separate data-loss bugs in ruflet_record:

  1. Threads share one transaction. RufletRecord.connection is one SQLiteAdapter per process, with one SQLite handle and an unlocked @transaction_depth. Any thread's statements run inside whatever transaction another thread has open. When that transaction rolls back, the other thread's writes are erased, even though its own create! and transaction calls returned normally. insert is also not atomic, so a record can get another thread's row id.
  2. update_columns and touch erase unrelated pending changes. After item.name = "renamed"; item.touch, the record reports changed? == false and a later save! never writes name.

ruflet_server runs one Thread per WebSocket client (packages/ruflet_server/lib/ruflet/server.rb:264). Page#invoke(..., on_result:) runs its timeout callback on its own Thread (packages/ruflet_core/lib/ruflet_ui/ruflet/page.rb:956). Two browser tabs, or one reconnect, are enough to hit (1).

Repro 1: a rolled-back transaction erases another thread's committed writes

require "ruflet_record"
require "tmpdir"

path = File.join(Dir.tmpdir, "rr_threads_#{Process.pid}.sqlite3")
RufletRecord.establish_connection(database: path)
RufletRecord::Schema.define { create_table(:notes) { |t| t.string :body } }
class Note < RufletRecord::Base; end

a_started = Queue.new
b_done = Queue.new
a = Thread.new do
  Note.transaction do
    Note.create!(body: "A (meant to roll back)")
    a_started << true
    b_done.pop
    raise "A fails"
  end
rescue => e
  puts "thread A: #{e.message}"
end
b = Thread.new do
  a_started.pop
  Note.transaction { Note.create!(body: "B (its own transaction)") }
  Note.create!(body: "B2 (plain create)")
  b_done << true
end
[a, b].each(&:join)
p Note.pluck(:body)
  • Expected: ["B (its own transaction)", "B2 (plain create)"]
  • Actual: [], in 3 of 3 runs. Thread B sees depth 1, so its transaction opens a SAVEPOINT inside thread A's transaction and its plain create! joins it. A's ROLLBACK removes both.

This repro hands control between threads with queues. It is the same without them:

  • Thread A runs Note.transaction { Note.create!; sleep 0.002; raise } 50 times.
  • Thread B runs a plain Note.create! 200 times.
  • Over 3 runs, B's create! returned normally 200 times each run, but only 25, 28 and 27 of B's rows were stored. No error was raised.

Repro 2: a record gets another thread's id

Two threads each run Note.create! 3000 times, with no transaction.

  • In 2 runs, 36 and 33 records had an id that pointed at the other thread's row.
  • 5 and 4 ids were handed to two records.

SQLiteAdapter#insert runs execute and then last_insert_row_id without a lock. A later update! on such a record writes to the other thread's row.

Repro 3: touch / update_columns drop pending changes

RufletRecord.establish_connection(database: ":memory:")
RufletRecord::Schema.define { create_table(:items) { |t| t.string :name; t.integer :qty; t.timestamps } }
class Item < RufletRecord::Base; end

i = Item.create!(name: "m1", qty: 1)
i.name = "renamed"
i.touch
p i.changed?               # false (Active Record 8.1: true)
i.save!
p Item.find(i.id).name     # "m1" (Active Record 8.1: "renamed")

j = Item.create!(name: "m2", qty: 1)
j.name = "renamed2"
j.update_columns(qty: 5)
j.save!
p Item.find(j.id).name     # "m2" (Active Record 8.1: "renamed2")

I ran the same script on Active Record 8.1.4. There the pending name stays dirty and save! writes it. The README describes the API as "shaped like the useful core of Active Record" and lists update_columns and touch.

Location

  • packages/ruflet_record/lib/ruflet_record/adapters/sqlite_adapter.rb:8-88: one driver and @transaction_depth with no lock. transaction opens a SAVEPOINT whenever the depth is non-zero, whichever thread opened the transaction. insert and update read last_insert_row_id and changes after a separate execute.
  • packages/ruflet_record/lib/ruflet_record/base.rb:366-383: update_columns ends with @original_attributes = @attributes.dup, which marks every attribute clean, not just the ones it wrote. touch goes through update_columns.

Proposal

  1. Give SQLiteAdapter a reentrant, thread-owned lock on CRuby:
    • execute, execute_batch, insert (with last_insert_row_id) and update/delete (with changes) each hold it.
    • transaction holds it for the whole block. Another thread then waits for the transaction to end instead of joining it.
    • Nested transactions on the owning thread stay savepoints, as today.
    • A waiting thread waits at most the configured busy timeout (default 5000 ms), then gets StatementInvalid: database is locked. That is what SQLite does for a second connection. A transaction block that waits on another thread that needs the database then fails after the timeout instead of hanging.
    • On the mruby VM, use a no-op lock, so device behavior is unchanged. Its Thread is cooperative (fibers on one native thread), it has no Monitor, and its Mutex shim is not reentrant, so nested savepoint transactions would break with that Mutex.
  2. update_columns marks clean only the attributes it wrote.
  3. Add a two-thread regression test, an insert-id race test and touch-then-save tests.

Single-threaded behavior, the device VM and the SQL that is sent stay unchanged.

Not covered by #93 / #99, which fixed only non-local exits from a transaction block.

Activity

  1. added
    bug
    on Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions