Repository navigation
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
Conversation
…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.
…it; README trap wording
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #124
Problem
RufletRecord.connectionis oneSQLiteAdapterper process. It has one SQLite handle and an unlocked@transaction_depth.ruflet_serverruns aThreadper client, andPage#invoke(on_result:)runs its timeout callback on aThreadtoo. So any thread's statements ran inside whatever transaction another thread had open:transactionopened aSAVEPOINTinside the other thread's transaction, and its plain writes joined it.insertranexecuteand thenlast_insert_row_idwithout a lock, so about 0.6% of records got another thread's id (36 of 6000 in the run below).updateandchangeshad the same race.update_columnsandtoucherased unrelated pending changes. Both ended with@original_attributes = @attributes.dup. Afteritem.name = "x"; item.touch, the record reportedchanged? == false, andsave!never wrotename. Active Record 8.1 keepsnamepending.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 newtest/connection_threads_test.rb.SQLiteAdaptertakes a connection lock (ThreadLock, CRuby only):executeandexecute_batchhold it for one statement.insertholds it acrossexecuteandlast_insert_row_id, andupdate/deleteacrossexecuteandchanges.transactionholds it for the whole block. Another thread waits until the block ends. It never joins the transaction.Monitorbelongs to the fiber, so anEnumerator#nextthat queries inside a transaction would wait on itself. That is why this is a smallMutex+ConditionVariablelock and not aMonitor.timeout, but never less than the default 5000 ms. It then getsStatementInvalid: database is locked (...). The floor exists because plain statements on two threads overlap all the time: with no floor andtimeout: 0, one of two threads doing plaincreate!calls failed 1000 of 1000 times.PRAGMA busy_timeoutstill getstimeoutunchanged.Thread#kill,Thread#raiseandTimeoutnever leak the lock. Taking it runs underThread.handle_interrupt(Object => :never);Exception => :neverwould not deferThread#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.Signal.traphandler it takes nothing. CRuby raisesThreadErrorforMutex#lockin trap context, so the handler's statements run unlocked, exactly as onmain. Ruflet reaches this path: the hot-reload runner calls the app's ownUSR1handler from trap context.NullLock, which only yields. The VM'sThreadis cooperative (fibers on one native thread), it has noMonitor, and itsMutexshim is not reentrant. Device behavior is unchanged, including its residual: a VM thread that writes while another VM thread's transaction block is paused (insleep, say) writes inside that transaction. The README now says so.update_columnsmarks only the columns it wrote as saved:values.each_key { |name| @original_attributes[name] = @attributes[name] }.touchgoes through it.update_columns/touchleave other changes pending.Behavior changes
Both are data-loss bug fixes.
max(timeout, 5000)ms raisesStatementInvalid("database is locked"). Throughsave!/create!that surfaces asRecordNotSaved, andsavereturnsfalse.mainthat thread's statements ran inside the block's transaction, which is the bug. The README says not to do this.update_columnsandtouchkeep other unsaved changes pending.changed?stays true for them, and the nextsavewrites 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: 0included), statements inSignal.traphandlers,PRAGMA busy_timeout, and the device VM.How verified
Run on the final head, or on f47cb87, whose
ruflet_recordtree is identical (the final head only merges main's #132, a CLI change). Scripts and outputs are in the session'sstate/train/audit7/rework/andreview/directories.Regression tests.
test/connection_threads_test.rbhas 17 tests:timeout: 0(and a longertimeoutkept), and two threads x 300 plaincreate!withtimeout: 0all succeeding;Thread#raiseandThread#killarriving while a thread takes the lock; a lock whose owner is gone afterfork;Signal.traptests: a handler'screate!,transactionandcount; a handler inside the main thread's own transaction; a handler while another thread holds a transaction;api_surface_test.rbhas a touch-then-save test and an update_columns-then-save test.Bugs planted back.
main'slib, 8 of the 9 original-bug thread tests fail, the 4 tests that useThreadLockdirectly error, and both newapi_surfacetests fail. The trap tests, thetimeout: 0plain-writes test and the Enumerator test pass onmain: they guard behavior the fix must keep.lib, the 3 trap tests and thetimeout: 0plain-writes test error, and the floor test fails.update_columnsare all caught: no lock around insert/update (2 failures), aroundtransaction(6 failures), or aroundexecute(1); nohandle_interrupt;Exceptioninstead ofObject;acquiredset 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 oldupdate_columns; no trap fallback; a trap fallback for every call; no floor;timeoutignored.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 givechanged? == true, and the nextsave!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.rbon Ruby 4.0.5 and 3.4.5:create!,transactionandcountall succeed in the handler, and both rows are stored, the same output asmain.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.rbwith timeout 0, 1 and the default: 0 failures, 2000 of 2000 rows each.timeout0_single.rb: unchanged.interrupt_storm.rbwith seeds 1 to 5: afterwards no owner, depth 0, and the next write does not wait.Same SQL. The review's
sql_corpus2.rbruns 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 onmainand this branch.Full
ruflet_recordsuite. 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 testgives 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
libwas loaded over the copy preloaded in a desktop mruby build (framework 0.0.23).test/mruby_smoke.rbandmain's smoke pass, as does a probe of a VMThreadwith nested transactions and return/break/throw.main'slib, the new smoke fails at itsNullLockcheck.vm_yield_probe.rbloses B's row on bothmainand this branch. That is the unchanged residual the README now states.H1 goldens.
cd packages/ruflet && ruby test/compat/compat.rb --jobs 4checked 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_recordtests 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.mdneeds next-release notes in three places. Thetimeoutbullet should say it now also bounds waits on other threads, with the 5000 ms floor. Theupdate_columns/touchbullet should say other pending changes stay pending. The Transactions section needs the thread serialization. The site's CI pinc061df08also needs to move forward.