Feature #16786

Updated by ioquatix (Samuel Williams) about 1 year ago

# Abstract 

 We propose to introduce a light weight fiber scheduler, to improve the concurrency of Ruby code with minimal changes. 

 # Background 

 We have been discussing and considering options to improve Ruby scalability for several years. More context can be provided by the following discussions: 


 The final Ruby Concurrency report provides some background on the various issues considered in the latest iteration: 

 # Proposal 

 We propose to introduce the following concepts: 

 - A `Scheduler` interface which provides hooks for user-supplied event loops. 
 - Non-blocking `Fiber` which can invoke the scheduler when it would otherwise block. 

 ## Scheduler 

 The per-thread fiber scheduler interface is used to intercept blocking operations. A typical implementation would be a wrapper for a gem like EventMachine or Async. This design provides separation of concerns between the event loop implementation and application code. It also allows for layered schedulers which can perform instrumentation, enforce constraints (e.g. during testing) and provide additional logging. You can see a [sample implementation here]( 

 class Scheduler 
   # Wait for the given file descriptor to become readable. 
   def wait_readable(fd) 

   # Wait for the given file descriptor to become writable. 
   def wait_writable(fd) 

   # Wait for the given file descriptor to match the specified events within 
   # the specified timeout. 
   # @param event [Integer] a bit mask of +IO::WAIT_READABLE+, 
   # @param timeout [#to_f] the amount of time to wait for the event. 
   def wait_for_single_fd(fd, events, timeout) 

   # Sleep the current task for the specified duration, or forever if not 
   # specified. 
   # @param duration [#to_f] the amount of time to sleep. 
   def wait_sleep(duration = nil) 

   # The Ruby virtual machine is going to enter a system level blocking 
   # operation. 
   def enter_blocking_region 

   # The Ruby virtual machine has completed the system level blocking 
   # operation. 
   def exit_blocking_region 

   # Intercept the creation of a non-blocking fiber. 
   def fiber(&block) false, &block).resume 

   # Invoked when the thread exits. 
   def run 
     # Implement event loop here. 

 A thread has a non-blocking fiber scheduler. All blocking operations on non-blocking fibers are hooked by the scheduler and the scheduler can switch to another fiber. If any mutex is acquired by a fiber, then a scheduler is not called; the same behaviour as blocking Fiber. 

 Schedulers can be written in Ruby. This is a desirable property as it allows them to be used in different implementations of Ruby easily. 

 To enable non-blocking fiber switching on blocking operations: 

 - Specify a scheduler: `Thread.current.scheduler =`. 
 - Create several non-blocking fibers: ` {...}`. 
 - As the main fiber exits, `` is invoked which 
   begins executing the event loop until all fibers are finished. 

 ### Time/Duration Arguments 

 Tony Arcieri suggested against using floating point values for time/durations, because they can accumulate rounding errors and other issues. He has a wealth of experience in this area so his advice should be considered carefully. However, I have yet to see these issues happen in an event loop. That being said, round tripping between `struct timeval` and `double`/`VALUE` seems a bit inefficient. One option is to have an opaque argument that responds to `to_f` as well as potentially `seconds` and `microseconds` or some other such interface (could be opaque argument supported by `` for example). 

 ### File Descriptor Arguments 

 There is a good case for prefering `IO` instances over file descriptors. However because of the public C interface we may need to support both. 

 int rb_io_wait_readable(int); 
 int rb_io_wait_writable(int); 
 int rb_wait_for_single_fd(int fd, int events, struct timeval *tv); 

 Internally, in CRuby, it may be possible to map from `fd` -> `IO` instance. Another option is to simply support both interfaces and leave it up to the scheduler to decide how to handle it, e.g. 

 class Scheduler 
   def wait_readable_fd(fd) 
     # wait_readable_io(IO.from_fd(fd)) 

   def wait_readable_io(io) 
     # wait_readable_fd(io.fileno) 

 We would like to be flexible, without imposing a performance burden on any particular implementation. This is a good point for further discussion. 

 ## Non-blocking Fiber 

 We propose to introduce per-fiber flag `blocking: true/false`. 

 A fiber created by ` true)` (the default ``) becomes a "blocking Fiber" and has no changes from current Fiber implementation. 

 A fiber created by ` false)` becomes a "non-blocking Fiber" and it will be scheduled by the per-thread scheduler when the blocking operations (blocking I/O, sleep, and so on) occurs. 

 ```ruby false) do 
   puts Fiber.current.blocking? # false 

   # May invoke `Thread.scheduler&.wait_readable`. 

   # May invoke `Thread.scheduler&.wait_writable`. 

   # Will invoke `Thread.scheduler&.wait_sleep`. 

 Non-blocking fibers also supports `Fiber#resume`, `Fiber#transfer` and `Fiber.yield` which are necessary to create a scheduler. 

 ### Fiber Method 

 We also introduce a new method which simplifes the creation of these non-blocking fibers: 

 Fiber do 
   puts Fiber.current.blocking? # false 

 This method invokes `Scheduler#fiber(...)`. The purpose of this method is to allow the scheduler to internally decide the policy for when to start the fiber, and whether to use symmetric or asymmetric fibers. 

 If no scheduler is specified, it creates a normal blocking fiber. An alternative is to make it an error. 

 ## Non-blocking I/O 

 As proposed by Eric Wong, we believe that making I/O non-blocking by default is the right approach. We have expanded his work in the current implementation. By doing this, when the user writes `Fiber do ... end` they are guaranteed the best possible concurrency possible, without any further changes to code. As an example, one of the tests shows `Net::HTTP.get` being used in this way with no further modifications required. 

 To support this further, consider the counterpoint, that `Net::HTTP.get(..., blocking: false)` is required for concurrent requests. Library code may not expose the relevant options, sevearly limiting the user's ability to improve concurrency, even if that is what they desire. 

 # Implementation 

 We have an evolving implementation here: which we will continue to update as the proposal changes. 

 # Evaluation 

 This proposal provides the hooks for scheduling fibers. With regards to performance, there are several things to consider: 

 - The impact of the scheduler design on non-concurrent workloads. We believe it's acceptable. 
 - The impact of the scheduler design on concurrent workloads. Our results are promising. 
 - The impact of different event loops on throughput and latency. We have independent tests which confirm the scalability of the approach. 

 We can control for the first two in this proposal, and depending on the design we may help or hinder the wrapper implementation. 

 In the tests, we provide a basic implementation using ``. As this proposal is finalised, we will introduce some basic benchmarks using this approach. 

 # Discussion 

 The following points are good ones for discussion: 

 - Handling of file descriptors vs `IO` instances. 
 - Handling of time/duration arguments. 
 - General design and naming conventions. 
 - Potential platform issues (e.g. CRuby vs JRuby vs TruffleRuby, etc). 

 The following is planned to be described by @eregon in another design document: 

 - Semantics of non-blocking mutex (e.g. ` false)` or some other approach). 

 In the future we hope to extend the scheduler to handle other blocking operations, including name resolution, file I/O (by `io_uring`) and others.