Repository navigation
Description
Summary
Two separate data-loss bugs in ruflet_record:
- Threads share one transaction.
RufletRecord.connectionis oneSQLiteAdapterper 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 owncreate!andtransactioncalls returned normally.insertis also not atomic, so a record can get another thread's row id. update_columnsandtoucherase unrelated pending changes. Afteritem.name = "renamed"; item.touch, the record reportschanged? == falseand a latersave!never writesname.
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 itstransactionopens aSAVEPOINTinside thread A's transaction and its plaincreate!joins it. A'sROLLBACKremoves 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
idthat 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_depthwith no lock.transactionopens aSAVEPOINTwhenever the depth is non-zero, whichever thread opened the transaction.insertandupdatereadlast_insert_row_idandchangesafter a separateexecute.packages/ruflet_record/lib/ruflet_record/base.rb:366-383:update_columnsends with@original_attributes = @attributes.dup, which marks every attribute clean, not just the ones it wrote.touchgoes throughupdate_columns.
Proposal
- Give
SQLiteAdaptera reentrant, thread-owned lock on CRuby:execute,execute_batch,insert(withlast_insert_row_id) andupdate/delete(withchanges) each hold it.transactionholds 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 getsStatementInvalid: 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
Threadis cooperative (fibers on one native thread), it has noMonitor, and itsMutexshim is not reentrant, so nested savepoint transactions would break with thatMutex.
update_columnsmarks clean only the attributes it wrote.- 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