Repository navigation
Ractor support (supersedes #365) #749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rubys
wants to merge
4
commits into
sparklemotion:main
Choose a base branch
from
rubys:ractor-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| # Ractor support in SQLite3-Ruby | ||
|
|
||
| SQLite3 has [3 different modes of threading support](https://www.sqlite.org/threadsafe.html). | ||
|
|
||
| 1. Single-thread | ||
| 2. Multi-thread | ||
| 3. Serialized | ||
|
|
||
| "Single thread" mode means there are no mutexes, so the library itself is not | ||
| thread safe. In other words if two threads do `SQLite3::Database.new` on the | ||
| same file, it will have thread safety problems. | ||
|
|
||
| "Multi thread" mode means that SQLite3 puts mutexes in place, but it does not | ||
| mean that the SQLite3 API itself is thread safe. In other words, in this mode | ||
| it is SAFE for two threads to do `SQLite3::Database.new` on the same file, but | ||
| it is NOT SAFE to share that database object between two threads. | ||
|
|
||
| "Serialized" mode is like "Multi thread" mode except that there are mutexes in | ||
| place such that it IS SAFE to share the same database object between threads. | ||
|
|
||
| ## Ractor Safety | ||
|
|
||
| When a C extension claims to be Ractor safe by calling `rb_ext_ractor_safe`, | ||
| it's merely claiming that its C API is thread safe. This _does not_ mean that | ||
| objects allocated from said C extension are allowed to cross between Ractor | ||
| boundaries. | ||
|
|
||
| In other words, `rb_ext_ractor_safe` matches the expectations of the | ||
| "multi-thread" mode of SQLite3. We can detect the multithread mode via the | ||
| `sqlite3_threadsafe` function. In other words, it's fine to declare this | ||
| extension is Ractor safe, but only if `sqlite3_threadsafe` returns true. | ||
| `SQLite3.ractor_safe?` reports whether the extension made that declaration. | ||
|
|
||
| The supported pattern is that each Ractor opens and uses its own connections. | ||
| Everything works inside a Ractor, including user-defined functions, | ||
| aggregators, collations, the authorizer, `trace`, and `busy_handler`. Several | ||
| Ractors may open connections to the same database file; SQLite's own locking | ||
| coordinates them, just as it does for separate processes. | ||
|
|
||
| ```ruby | ||
| require "sqlite3" | ||
|
|
||
| ractors = 4.times.map do |i| | ||
| Ractor.new(i) do |i| | ||
| db = SQLite3::Database.new("app.db") | ||
| db.busy_timeout = 5000 | ||
| db.execute("INSERT INTO log (worker) VALUES (?)", [i]) | ||
| db.close | ||
| end | ||
| end | ||
| ractors.each(&:value) | ||
| ``` | ||
|
|
||
| ## Database objects can't be passed between Ractors | ||
|
|
||
| A `SQLite3::Database` belongs to the Ractor that opened it. Passing one to | ||
| another Ractor raises a `Ractor::Error`: | ||
|
|
||
| ```ruby | ||
| require "sqlite3" | ||
|
|
||
| r = Ractor.new { Ractor.receive } | ||
|
|
||
| db = SQLite3::Database.new ":memory:" | ||
|
|
||
| begin | ||
| r.send db | ||
| puts "unreachable" | ||
| rescue Ractor::Error | ||
| end | ||
| ``` | ||
|
|
||
| This is true even for a connection opened in "Serialized" mode | ||
| (`SQLite3::Constants::Open::FULLMUTEX`). Serialized mode makes the SQLite | ||
| calls safe, but a `Database` also holds Ruby state: the procs and objects | ||
| registered as functions, aggregators, collations, and handlers. Those can't | ||
| be shared between Ractors. | ||
|
|
||
| ## Fork Safety | ||
|
|
||
| Fork safety is restricted to database objects that were created on the main | ||
| Ractor. When a process forks, the child process shuts down all Ractors, so | ||
| any database connections that are inside a Ractor should be released. | ||
| Because a connection can't be passed between Ractors, every connection the main | ||
| Ractor can reach is tracked. |
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,18 @@ | ||
| module SQLite3 | ||
| # a hash of descriptive metadata about the current version of the sqlite3 gem | ||
| # a hash of descriptive metadata about the current version of the sqlite3 gem, | ||
| # deeply frozen so that it can be read from any Ractor | ||
| VERSION_INFO = { | ||
| ruby: RUBY_DESCRIPTION, | ||
| gem: { | ||
| version: SQLite3::VERSION | ||
| }, | ||
| version: SQLite3::VERSION.freeze | ||
| }.freeze, | ||
| sqlite: { | ||
| compiled: SQLite3::SQLITE_VERSION, | ||
| loaded: SQLite3::SQLITE_LOADED_VERSION, | ||
| packaged: SQLite3::SQLITE_PACKAGED_LIBRARIES, | ||
| precompiled: SQLite3::SQLITE_PRECOMPILED_LIBRARIES, | ||
| sqlcipher: SQLite3.sqlcipher?, | ||
| threadsafe: SQLite3.threadsafe? | ||
| } | ||
| } | ||
| }.freeze | ||
| }.freeze | ||
| end |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "helper" | ||
| require "open3" | ||
| require "rbconfig" | ||
|
|
||
| # Each Ractor test runs in a child process. Once a process has started a | ||
| # Ractor, some process-wide behavior changes for good (for example, | ||
| # ObjectSpace.each_object stops seeing objects), which would leak into | ||
| # unrelated tests. A child process also lets us fail on a hang instead of | ||
| # stalling the suite. | ||
| class IntegrationRactorTestCase < SQLite3::TestCase | ||
| TIMEOUT = 60 | ||
|
|
||
| PRELUDE = <<~RUBY | ||
| require "sqlite3" | ||
| Warning[:experimental] = false | ||
| def ractor_value(r) = r.respond_to?(:value) ? r.value : r.take | ||
| RUBY | ||
|
|
||
| def setup | ||
| super | ||
| skip("Requires a Ractor-safe build") unless SQLite3.ractor_safe? | ||
|
|
||
| # valgrind follows the child processes, and a Ruby process that has created a Ractor can't | ||
| # exit cleanly under it: with RUBY_FREE_AT_EXIT, Ruby 4.0.7 reads freed memory in | ||
| # ractor_free (RUBY_FREE_AT_EXIT=1 valgrind ruby -e 'Ractor.new { 1 }.value'); without it, | ||
| # everything Ruby allocated is reported as leaked. | ||
| skip("Ractor processes can't exit cleanly under valgrind") if i_am_running_in_valgrind | ||
| end | ||
|
|
||
| def test_ractor_safe | ||
| assert_predicate SQLite3, :ractor_safe? | ||
| end | ||
|
|
||
| def test_open_and_query_in_ractors | ||
| assert_ractor_script(<<~RUBY, "4950,4950,4950,4950") | ||
| ractors = 4.times.map do | ||
| Ractor.new do | ||
| db = SQLite3::Database.new(":memory:") | ||
| begin | ||
| db.execute "CREATE TABLE t (a INTEGER)" | ||
| db.transaction do | ||
| stmt = db.prepare("INSERT INTO t VALUES (?)") | ||
| 100.times { |n| stmt.execute(n) } | ||
| stmt.close | ||
| end | ||
| db.get_first_value("SELECT sum(a) FROM t") | ||
| ensure | ||
| db.close | ||
| end | ||
| end | ||
| end | ||
| print ractors.map { ractor_value(_1) }.join(",") | ||
| RUBY | ||
| end | ||
|
|
||
| def test_callbacks_in_ractor | ||
| assert_ractor_script(<<~RUBY, "20,b,true,true") | ||
| class Summer | ||
| def initialize = @sum = 0 | ||
| def step(v) = @sum += v | ||
| def finalize = @sum | ||
| end | ||
|
|
||
| class Reverse | ||
| def compare(a, b) = b <=> a | ||
| end | ||
|
|
||
| r = Ractor.new do | ||
| db = SQLite3::Database.new(":memory:") | ||
| begin | ||
| traced = false | ||
| db.trace { traced = true } | ||
| db.authorizer = ->(*) { true } | ||
| db.create_function("double", 1) { |fn, x| fn.result = x * 2 } | ||
| db.define_aggregator("summer", Summer.new) | ||
| db.collation("rev", Reverse.new) | ||
|
|
||
| db.execute "CREATE TABLE t (a INTEGER, s TEXT)" | ||
| db.execute "INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'a'), (4, 'b')" | ||
| stmt = db.prepare("SELECT s FROM t ORDER BY s COLLATE rev LIMIT 1") | ||
| first = stmt.execute.to_a.flatten.first | ||
| stats = stmt.stat.key?(:vm_steps) | ||
| stmt.close | ||
|
|
||
| [db.get_first_value("SELECT summer(double(a)) FROM t"), first, stats, traced].join(",") | ||
| ensure | ||
| db.close | ||
| end | ||
| end | ||
| print ractor_value(r) | ||
| RUBY | ||
| end | ||
|
|
||
| def test_version_info_is_shareable | ||
| assert_ractor_script(<<~RUBY, SQLite3::VERSION) | ||
| print ractor_value(Ractor.new { SQLite3::VERSION_INFO[:gem][:version] }) | ||
| RUBY | ||
| end | ||
|
|
||
| def test_database_cannot_be_sent_to_another_ractor | ||
| # Before ruby/ruby@ce47ee00, sending a T_DATA object made a shallow copy instead of raising | ||
| skip("Requires Ruby 3.3 or later") if RUBY_VERSION < "3.3" | ||
|
|
||
| assert_ractor_script(<<~RUBY, "Ractor::Error") | ||
| db = SQLite3::Database.new(":memory:") | ||
| r = Ractor.new { Ractor.receive } | ||
| begin | ||
| r.send(db) | ||
| print "sent" | ||
| rescue Ractor::Error => e | ||
| print e.class | ||
| end | ||
| RUBY | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def assert_ractor_script(script, expected) | ||
| load_path = $LOAD_PATH.select { |dir| File.directory?(dir) }.flat_map { |dir| ["-I", dir] } | ||
| cmd = [RbConfig.ruby, *load_path, "-e", PRELUDE + script] | ||
|
|
||
| Open3.popen3(*cmd) do |stdin, out, err, wait_thr| | ||
| stdin.close | ||
| out_reader = Thread.new { out.read } | ||
| err_reader = Thread.new { err.read } | ||
|
|
||
| unless wait_thr.join(TIMEOUT) | ||
| Process.kill(:KILL, wait_thr.pid) | ||
| flunk "Ractor script did not finish within #{TIMEOUT}s:\n#{script}" | ||
| end | ||
|
|
||
| output = out_reader.value | ||
| assert_predicate wait_thr.value, :success?, "Ractor script failed:\n#{output}#{err_reader.value}" | ||
| assert_equal expected, output | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This does work in Ractors on 4.0, but I don't think it was intended to and it may not (or warn or whatever) in the future.
In Ruby 4.1, the rule changes so that the instance variables can be set by the class's owner, so the existing code should work.
I opened #752 which I think should also fix this in a Ractor. IMO we can skip define_aggregator's Ractor compatibility in this PR