Module: Lich::SQLiteBusyWait
- Defined in:
- documented/common/sqlite_connection.rb
Overview
Lock waits that let the rest of the process keep running.
sqlite3's busy_timeout waits inside C with the GVL held. If the lock holder is another thread of this process that still has Ruby code to run before it commits, it can't run, and the waiter fails when the timeout expires. A waiting thread also freezes every other thread (game I/O included) while another process holds the lock. Every connection Lich opens to lich.db3 (the Sequel pool, Lich.db, the session summary connection) gets the Ruby handler: a thread spinning in C with the GVL held while another thread of this process sleeps in the Ruby handler holding the lock it waits for would stall both for the full timeout.
A busy handler written in Ruby sleeps between retries, which releases the GVL. SQLite calls it from inside the C call that is waiting for the lock, though, so a Thread#kill, Thread#raise or Timeout delivered during that sleep would unwind through SQLite's C frames and leave the connection's mutex locked; the next thread to use that connection would then block forever with the GVL held. On these connections every sqlite3 entry point that can wait for a lock therefore defers interrupts until SQLite returns:
- SQLite3::Statement#initialize (sqlite3_prepare) and #step (sqlite3_step), which carry #execute, #query, #prepare, #execute_batch, #transaction and everything Sequel sends;
- Database#exec_batch (sqlite3_exec), which carries #execute_batch2;
- SQLite3::Backup#step (sqlite3_backup_step), when either end of the backup is one of these connections (see SQLiteBusyWait::Backup).
An interrupt that arrives during a lock wait ends the wait: the handler gives up at its next poll (within about 1 ms), SQLite returns SQLITE_BUSY, and the interrupt is delivered as the call returns, in place of the BusyException. The interrupted statement does not run. Letting the wait go on until the lock freed would deliver the interrupt after the write had landed: a Timeout around the write reports a failure for a write that happened, a second interrupt can arrive meanwhile and land outside the scope it was meant for (a Timeout::ExitException after its Timeout block has returned), and a killed script's write can land after the writes its cleanup makes once the kill returns. With the C busy timeout none of this could happen, because nothing else ran until the wait ended.
Two exceptions keep waiting until the lock frees or the busy timeout expires, and deliver the interrupt afterwards:
- a call that starts with an interrupt already pending, which means the caller deferred it with Thread.handle_interrupt to finish its writes first (see SQLiteBusyWait.wait_uninterrupted);
- ROLLBACK (see SQLiteBusyWait::Transactions).
A caller that defers interrupts itself and is interrupted during the wait gets the BusyException; the interrupt stays deferred, as it asked.
While one thread sleeps in the handler, SQLite holds that connection's mutex and other threads run, garbage collection included. GC finalizes an unclosed SQLite3::Statement with sqlite3_finalize, which needs the same mutex and waits for it with the GVL held: the sleeping thread can never wake and the process freezes. So every open statement on these connections is kept referenced by its connection until it is closed (see SQLiteBusyWait::Statement); GC never finalizes one while it is open. A statement nobody closes is freed with its connection.
A connection that several threads share has one more hazard: a second thread calling into it while the first sleeps in the handler blocks on the same connection mutex with the GVL held. Shared connections are therefore serialized; see SQLiteBusyWait::SerializedDatabase.
Deferring interrupts moves where a Thread#kill lands inside Sequel::Database#transaction to the end of BEGIN or COMMIT; see SQLiteBusyWait::Transactions.
Defined Under Namespace
Modules: Backup, Connection, SerializedDatabase, SerializedStatement, Statement, Transactions
Constant Summary collapse
- POLL_INTERVAL_S =
Interval in seconds between busy handler poll checks for interrupts.
0.001- UNSERIALIZED_DATABASE_METHODS =
sqlite3 C methods that a serialized connection or statement calls without its Monitor: they don't take SQLite's connection mutex (interrupt is meant to be called from another thread while a statement runs), or they only run while the connection is opened or discarded after a fork, before any other thread can see it. Statement#prepare runs under SerializedDatabase's Monitor from Statement#initialize.
%i[closed? complete? interrupt open16 open_v2 discard].freeze
- UNSERIALIZED_STATEMENT_METHODS =
SQLite3::Statement C methods that do not acquire the connection mutex and need no Monitor serialization.
%i[closed? prepare].freeze
- SETUP_LOCK =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Mutex protecting one-time setup of sqlite3 gem integration.
Mutex.new
- KEEP_WAITING_KEY =
Thread variable: while set, the busy handler keeps waiting even though an interrupt is pending.
:lich_sqlite_keep_waiting
Class Method Summary collapse
-
.give_up_for_interrupt? ⇒ Boolean
True when the busy handler should give up the current lock wait: an interrupt is pending for the waiting thread (the handler runs on it), it will be delivered as soon as the call returns, and nothing asked to keep waiting (see wait_uninterrupted).
-
.install(conn, timeout_ms, shared: false) ⇒ Object
Installs the busy handler on a raw SQLite3::Database and returns it.
-
.keep_waiting_through_interrupts ⇒ Object
Runs the block with the busy handler waiting through pending interrupts.
-
.prepare_sqlite3 ⇒ Object
Prepends Statement to SQLite3::Statement and Backup to SQLite3::Backup, and defines the Monitor wrappers for every C method of SQLite3::Database and SQLite3::Statement not listed as unserialized.
-
.wait_uninterrupted ⇒ Object
Runs one sqlite3 call that may wait for a lock with interrupts deferred.
Class Method Details
.give_up_for_interrupt? ⇒ Boolean
True when the busy handler should give up the current lock wait: an interrupt is pending for the waiting thread (the handler runs on it), it will be delivered as soon as the call returns, and nothing asked to keep waiting (see wait_uninterrupted).
503 504 505 |
# File 'documented/common/sqlite_connection.rb', line 503 def self.give_up_for_interrupt? Thread.pending_interrupt? && !Thread.current.thread_variable_get(KEEP_WAITING_KEY) end |
.install(conn, timeout_ms, shared: false) ⇒ Object
Installs the busy handler on a raw SQLite3::Database and returns it.
shared: true is for a connection that several threads use at once; it
is serialized (SerializedDatabase). Connections without the
busy_handler API keep their C busy timeout.
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 |
# File 'documented/common/sqlite_connection.rb', line 471 def self.install(conn, timeout_ms, shared: false) return conn unless conn.respond_to?(:busy_handler) prepare_sqlite3 timeout_s = timeout_ms / 1000.0 deadline = nil conn.busy_handler do |count| next false if give_up_for_interrupt? now = Process.clock_gettime(Process::CLOCK_MONOTONIC) deadline = now + timeout_s if count.zero? || deadline.nil? next false if now > deadline unless count.zero? sleep(POLL_INTERVAL_S) # An interrupt that arrived during the sleep woke it. Check again # before SQLite retries: the retry runs in C with the GVL held, so # once this check passes no other thread can interrupt before it, # and a write that lands was never interrupted. next false if give_up_for_interrupt? end true end conn.extend(Connection) conn.extend(SerializedDatabase) if shared conn end |
.keep_waiting_through_interrupts ⇒ Object
Runs the block with the busy handler waiting through pending interrupts. Callers defer interrupts around it, so the thread variable is always restored.
456 457 458 459 460 461 462 463 464 465 |
# File 'documented/common/sqlite_connection.rb', line 456 def self.keep_waiting_through_interrupts thread = Thread.current outer = thread.thread_variable_get(KEEP_WAITING_KEY) thread.thread_variable_set(KEEP_WAITING_KEY, true) begin yield ensure thread.thread_variable_set(KEEP_WAITING_KEY, outer) end end |
.prepare_sqlite3 ⇒ Object
Prepends Statement to SQLite3::Statement and Backup to SQLite3::Backup, and defines the Monitor wrappers for every C method of SQLite3::Database and SQLite3::Statement not listed as unserialized. Runs once.
510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'documented/common/sqlite_connection.rb', line 510 def self.prepare_sqlite3 SETUP_LOCK.synchronize do return if @sqlite3_prepared serialize_c_methods(SerializedDatabase, ::SQLite3::Database, UNSERIALIZED_DATABASE_METHODS) serialize_c_methods(SerializedStatement, ::SQLite3::Statement, UNSERIALIZED_STATEMENT_METHODS) ::SQLite3::Statement.prepend(Statement) unless ::SQLite3::Statement <= Statement # SQLite3::Backup exists only when sqlite3 was built with the backup API. ::SQLite3::Backup.prepend(Backup) if defined?(::SQLite3::Backup) && !(::SQLite3::Backup <= Backup) @sqlite3_prepared = true end end |
.wait_uninterrupted ⇒ Object
Runs one sqlite3 call that may wait for a lock with interrupts deferred. An interrupt already pending here was deferred by the caller (otherwise it would have been delivered before this call), so the caller wants its writes finished first: the busy handler keeps waiting for this call. Otherwise an interrupt that arrives during the wait makes the handler give up.
445 446 447 448 449 450 451 |
# File 'documented/common/sqlite_connection.rb', line 445 def self.wait_uninterrupted Thread.handle_interrupt(Object => :never) do next yield unless Thread.pending_interrupt? keep_waiting_through_interrupts { yield } end end |