Skip to content

ruflet_record: give each thread the connection to itself (no shared transactions or crossed row ids); keep pending changes across update_columns and touch - #126

Open
AdamMusa wants to merge 5 commits into
mainfrom
audit/record-connection-lock
Open

AdamMusa wants to merge 5 commits into
mainfrom
audit/record-connection-lock

Conversation

@AdamMusa

@AdamMusa AdamMusa commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Fixes #124

Problem

  1. All threads shared one transaction. RufletRecord.connection is one SQLiteAdapter per process. It has one SQLite handle and an unlocked @transaction_depth. ruflet_server runs a Thread per client, and Page#invoke(on_result:) runs its timeout callback on a Thread too. So any thread's statements ran inside whatever transaction another thread had open:
    • A thread's transaction opened a SAVEPOINT inside the other thread's transaction, and its plain writes joined it.
    • When that transaction rolled back, the thread's writes were erased, with no error.
    • Reads saw another thread's uncommitted rows.
    • insert ran execute and then last_insert_row_id without a lock, so about 0.6% of records got another thread's id (36 of 6000 in the run below). update and changes had the same race.
  2. update_columns and touch erased unrelated pending changes. Both ended with @original_attributes = @attributes.dup. After item.name = "x"; item.touch, the record reported changed? == false, and save! never wrote name. Active Record 8.1 keeps name pending.

What changed

Only packages/ruflet_record: adapters/sqlite_adapter.rb, base.rb, the README, test/mruby_smoke.rb, test/api_surface_test.rb, and the new test/connection_threads_test.rb.

  • SQLiteAdapter takes a connection lock (ThreadLock, CRuby only):
    • execute and execute_batch hold it for one statement.
    • insert holds it across execute and last_insert_row_id, and update/delete across execute and changes.
    • transaction holds it for the whole block. Another thread waits until the block ends. It never joins the transaction.
  • How the lock works:
    • It is reentrant, so statements inside a block and nested transactions (savepoints) work as before.
    • A thread owns it, not a fiber. Ruby 3's Monitor belongs to the fiber, so an Enumerator#next that queries inside a transaction would wait on itself. That is why this is a small Mutex + ConditionVariable lock and not a Monitor.
    • A waiting thread waits at most the busy timeout, but never less than the default 5000 ms. It then gets StatementInvalid: database is locked (...). The floor exists because plain statements on two threads overlap all the time: with no floor and timeout: 0, one of two threads doing plain create! calls failed 1000 of 1000 times. PRAGMA busy_timeout still gets timeout unchanged.
    • Thread#kill, Thread#raise and Timeout never leak the lock. Taking it runs under Thread.handle_interrupt(Object => :never); Exception => :never would not defer Thread#kill. A thread waiting for the lock can still be killed or timed out, and then takes nothing. A lock left by a dead thread, in a forked child for example, is taken over.
    • In a Signal.trap handler it takes nothing. CRuby raises ThreadError for Mutex#lock in trap context, so the handler's statements run unlocked, exactly as on main. Ruflet reaches this path: the hot-reload runner calls the app's own USR1 handler from trap context.
  • On the mruby VM the adapter uses NullLock, which only yields. The VM's Thread is cooperative (fibers on one native thread), it has no Monitor, and its Mutex shim is not reentrant. Device behavior is unchanged, including its residual: a VM thread that writes while another VM thread's transaction block is paused (in sleep, say) writes inside that transaction. The README now says so.
  • update_columns marks only the columns it wrote as saved: values.each_key { |name| @original_attributes[name] = @attributes[name] }. touch goes through it.
  • README: the Transactions section describes the thread behavior, the wait, the trap-handler case and the VM residual. The persistence section says that update_columns/touch leave other changes pending.

Behavior changes

Both are data-loss bug fixes.

  1. Concurrent threads on CRuby are serialized instead of silently sharing one transaction.
    • While a thread has a transaction open, other threads' reads and writes wait for it to end.
    • A thread that waits longer than max(timeout, 5000) ms raises StatementInvalid ("database is locked"). Through save!/create! that surfaces as RecordNotSaved, and save returns false.
    • A transaction block that waits for another thread that uses the database now makes that thread wait, and the wait fails. On main that thread's statements ran inside the block's transaction, which is the bug. The README says not to do this.
    • Before, these calls returned normally, and their writes could be rolled back by another thread or get another thread's row id.
  2. update_columns and touch keep other unsaved changes pending. changed? stays true for them, and the next save writes them. Before, they were marked clean and never saved. With no pending changes, the result is the same as before.

Unchanged: single-threaded code (same SQL, results and errors, timeout: 0 included), statements in Signal.trap handlers, PRAGMA busy_timeout, and the device VM.

How verified

Run on the final head, or on f47cb87, whose ruflet_record tree is identical (the final head only merges main's #132, a CLI change). Scripts and outputs are in the session's state/train/audit7/rework/ and review/ directories.

  • Regression tests. test/connection_threads_test.rb has 17 tests:

    • rollback isolation, no dirty reads, own insert id, own change count;
    • the wait: the lock's own timeout, the 5000 ms floor at timeout: 0 (and a longer timeout kept), and two threads x 300 plain create! with timeout: 0 all succeeding;
    • kill of the owner (the waiter writes within 10 s, with a 60 s timeout); a waiter killed or timed out at once, after which the owner still holds the lock (a third thread waits, and its row survives the owner's rollback);
    • Thread#raise and Thread#kill arriving while a thread takes the lock; a lock whose owner is gone after fork;
    • three Signal.trap tests: a handler's create!, transaction and count; a handler inside the main thread's own transaction; a handler while another thread holds a transaction;
    • an Enumerator inside a transaction.

    api_surface_test.rb has a touch-then-save test and an update_columns-then-save test.

  • Bugs planted back.

    • With main's lib, 8 of the 9 original-bug thread tests fail, the 4 tests that use ThreadLock directly error, and both new api_surface tests fail. The trap tests, the timeout: 0 plain-writes test and the Enumerator test pass on main: they guard behavior the fix must keep.
    • With the previous head's (4cbc4ad) lib, the 3 trap tests and the timeout: 0 plain-writes test error, and the floor test fails.
    • 17 mutants of the lock and of update_columns are all caught: no lock around insert/update (2 failures), around transaction (6 failures), or around execute (1); no handle_interrupt; Exception instead of Object; acquired set before taking the lock; a fiber-owned lock; no broadcast; no timeout; no dead-owner takeover; non-reentrant release; a waiter that cannot be interrupted; the old update_columns; no trap fallback; a trap fallback for every call; no floor; timeout ignored.
  • Issue repros (issue_repros.rb). The queue repro keeps B's two rows (main: none). In the no-queue stress, 0 of 200 rows are lost (main: 200 of 200). The insert-id race gives 0 wrong ids of 6000 (main: 36, plus 3 ids given to two records). touch and update_columns give changed? == true, and the next save! writes the pending name, as Active Record 8.1.4 does in the issue (main: false, and the name is never saved).

  • Review probes.

    • trap_repro.rb on Ruby 4.0.5 and 3.4.5: create!, transaction and count all succeed in the handler, and both rows are stored, the same output as main.
    • waiter_release_probe.rb, in both timeout and kill modes: C waits while A's transaction is open, and C's row survives A's rollback.
    • timeout_plain_breakdown.rb with timeout 0, 1 and the default: 0 failures, 2000 of 2000 rows each.
    • timeout0_single.rb: unchanged.
    • interrupt_storm.rb with seeds 1 to 5: afterwards no owner, depth 0, and the next write does not wait.
  • Same SQL. The review's sql_corpus2.rb runs single-threaded calls covering validations, associations, errors, nested transactions and schema changes. It logs 55 driver calls (statements with binds, row ids, change counts) and every call's result. The output is identical on main and this branch.

  • Full ruflet_record suite. Each of the 15 test files ran in its own process with -w: 114 runs, 666 assertions, 0 failures and 0 warnings on Ruby 4.0.5 and on Ruby 3.4.5. bundle exec rake test gives the same counts. The thread tests also passed 9 more times (seeds 1, 2, 3, 42, 999, 31337 on 4.0.5; 7, 1234, 31337 on 3.4.5) at 1-minute load averages of 247 to 280.

  • Embedded mruby VM. This branch's lib was loaded over the copy preloaded in a desktop mruby build (framework 0.0.23).

    • The new test/mruby_smoke.rb and main's smoke pass, as does a probe of a VM Thread with nested transactions and return/break/throw.
    • With main's lib, the new smoke fails at its NullLock check.
    • vm_yield_probe.rb loses B's row on both main and this branch. That is the unchanged residual the README now states.
    • Like the existing checks, the smoke passes inside a shipped VM only once the VM is rebuilt from this source.
  • H1 goldens. cd packages/ruflet && ruby test/compat/compat.rb --jobs 4 checked 359 goldens (main's 358 plus the one fix: escape RUFLET_ANDROID_* signing values in key.properties so Gradle reads them as set #132 added) with no difference. ruby -Ilib -Itest test/compat_goldens_test.rb: 367 runs, 802 assertions, 0 failures.

  • Merges cleanly with the open ruflet_record: apply a relation's limit, offset, distinct and order in writes, count, last and find_each; chain scopes on relations #118 and ci: run every Ruby test suite (rails, record, runtime, tools), fail on silent skips, declare the test toolchain, clear 61 lockfile advisories #151. Neither CI workflow runs the ruflet_record tests yet; ci: run every Ruby test suite (rails, record, runtime, tools), fail on silent skips, declare the test toolchain, clear 61 lockfile advisories #151 adds them.

Docs follow-up (after merge)

ruflet.dev's app/content/docs/ruflet_record.md needs next-release notes in three places. The timeout bullet should say it now also bounds waits on other threads, with the 5000 ms floor. The update_columns/touch bullet should say other pending changes stay pending. The Transactions section needs the thread serialization. The site's CI pin c061df08 also needs to move forward.

…g changes across update_columns and touch

All threads share the one SQLiteAdapter. On CRuby a thread now holds it
for each statement, for insert plus last_insert_row_id, for update plus
changes, and for a whole transaction block. Another thread waits instead
of running inside that transaction, where a rollback erased its writes.
The lock is reentrant and owned by a thread, so nested transactions stay
savepoints and an Enumerator stepped inside a block reuses it. A waiting
thread gives up after the busy timeout with "database is locked", as from
a second SQLite connection. On the mruby VM, whose threads are
cooperative and whose Mutex is not reentrant, the connection takes no
lock, as before.

update_columns (and so touch) marks clean only the columns it wrote.
Other unsaved changes stay pending and the next save writes them, as in
Active Record.

Single-threaded code sends the same SQL as before.

Fixes #124
…t least the default for another thread

Signal.trap handlers cannot lock a Mutex on CRuby, so the connection lock
now takes nothing there and the handler's statements run as they did on
main. A busy timeout below the default no longer shortens a thread's wait
for another thread (timeout: 0 failed half of two threads' plain writes).
Tests now pin that a killed or timed-out waiter leaves the owner holding
the lock, that waiters wake and can be interrupted promptly, that an
interrupt while taking the lock leaves it free, and that a lock whose
owner is gone is taken over. README notes the VM residual.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant