Bug #21270
openinit_fast_fallback_inetsock_internal (default for TCPSocket.new/TCPSocket.open) isn't fiber aware
Description
Sockets created via init_fast_fallback_inetsock_internal() don't get a chance to call the scheduler hook(s). This is the default for connections created with TCPSocket.new unless fast_fallback is specified as false. Unfortunately, this has the effect of blocking all fibers in the thread if the initial connect() call hangs. TCPSocket.open() is used in Net::HTTP, which means the issue is present there.
Here's a quick proof of concept. It works as intended as written (starts both fibers even though the first fiber hangs). Switching to the default TCPSocket.new call causes the whole thread to block.
NOTE: Uses the "toy" scheduler from test/fiber/scheduler.rb, but the Socketry async gem is also affected (should affect all schedulers since the hook isn't called).
require 'socket'
require_relative 'scheduler'
Fiber.set_scheduler(Scheduler.new)
puts "#{Fiber.current.object_id}: Main fiber"
Fiber.schedule do
puts "#{Fiber.current.object_id}: Creating socket"
# Assuming that attempting to connect to example.com on port 12345 hangs
# Default causes the scheduler to hang and never create second fiber
# TCPSocket.new("example.com", 12345)
TCPSocket.new("example.com", 12345, fast_fallback: false)
puts "#{Fiber.current.object_id}: Connected"
end
Fiber.schedule do
puts "#{Fiber.current.object_id}: Sleeping"
sleep 2
puts "#{Fiber.current.object_id}: Done sleeping"
end
puts "#{Fiber.current.object_id}: Both fibers started"
Running the working PoC:
$ ruby async-connect.rb
16: Main fiber
24: Creating socket
32: Sleeping
16: Both fibers started
32: Done sleeping
[Hangs here until the socket connection eventually times out]
However, without fast_fallback: false, the TCPSocket.new call will block the entire scheduler, never creating the second fiber:
Here's a stack dump of the hung version:
#0 __syscall_cancel_arch () at ../sysdeps/unix/sysv/linux/x86_64/syscall_cancel.S:56
#1 0x00007fc9e4c9581c in __internal_syscall_cancel (a1=<optimized out>, a2=<optimized out>,
a3=<optimized out>, a4=<optimized out>, a5=a5@entry=0, a6=a6@entry=0, nr=270) at cancellation.c:49
#2 0x00007fc9e4c95871 in __syscall_cancel (a1=<optimized out>, a2=<optimized out>, a3=<optimized out>,
a4=<optimized out>, a5=a5@entry=0, a6=a6@entry=0, nr=270) at cancellation.c:75
#3 0x00007fc9e4d1af07 in __GI___select (nfds=<optimized out>, readfds=<optimized out>,
writefds=<optimized out>, exceptfds=<optimized out>, timeout=<optimized out>)
at ../sysdeps/unix/sysv/linux/select.c:69
#4 0x00007fc9e5233c9f in rb_fd_select (n=<optimized out>, readfds=<optimized out>,
writefds=<optimized out>, exceptfds=<optimized out>, timeout=<optimized out>)
at /usr/src/debug/ruby-3.4.2/thread.c:4163
#5 0x00007fc9e5236cc6 in native_fd_select (n=<optimized out>, readfds=<optimized out>,
writefds=<optimized out>, exceptfds=<optimized out>, timeout=<optimized out>, th=<optimized out>)
at /usr/src/debug/ruby-3.4.2/thread_pthread.c:2380
#6 do_select (p=p@entry=140504668626880) at /usr/src/debug/ruby-3.4.2/thread.c:4314
#7 0x00007fc9e50e7416 in rb_ensure (b_proc=0x7fc9e52368b0 <do_select>, data1=140504668626880,
e_proc=0x7fc9e5232440 <select_set_free>, data2=140504668626880)
at /usr/src/debug/ruby-3.4.2/eval.c:1074
#8 0x00007fc9e523700f in rb_thread_fd_select (max=max@entry=21, read=read@entry=0x7fc9cadce430,
write=write@entry=0x7fc9cadce440, except=except@entry=0x0, timeout=timeout@entry=0x0)
at /usr/src/debug/ruby-3.4.2/thread.c:4374
#9 0x00007fc9c97b5050 in init_fast_fallback_inetsock_internal (v=v@entry=140504668627872)
at /usr/src/debug/ruby-3.4.2/ext/socket/ipsocket.c:894
#10 0x00007fc9e50e7416 in rb_ensure (
b_proc=b_proc@entry=0x7fc9c97b4950 <init_fast_fallback_inetsock_internal>,
data1=data1@entry=140504668627872,
e_proc=e_proc@entry=0x7fc9c97b7880 <fast_fallback_inetsock_cleanup>,
data2=data2@entry=140504668627872) at /usr/src/debug/ruby-3.4.2/eval.c:1074
#11 0x00007fc9c97b7f3c in rsock_init_inetsock (self=self@entry=140504646018560,
remote_host=remote_host@entry=140504646018640, remote_serv=remote_serv@entry=24691,
local_host=local_host@entry=4, local_serv=local_serv@entry=4, type=type@entry=0,
resolv_timeout=<optimized out>, connect_timeout=<optimized out>, fast_fallback=<optimized out>,
test_mode_settings=<optimized out>) at /usr/src/debug/ruby-3.4.2/ext/socket/ipsocket.c:1285
#12 0x00007fc9c97b8216 in tcp_init (argc=<optimized out>, argv=<optimized out>, sock=140504646018560)
at /usr/src/debug/ruby-3.4.2/ext/socket/tcpsocket.c:76
tcp_init is the TCPSocket#initialize defined in tcpsocket.c, which just calls into the pure-C stack without ever backing out to check io_wait as is done in other socket-creation code path. It looks like the main difference is that init_fast_fallback_inetsock_internal hasn't been updated to be Fiber-aware (eg. init_inetsock_internal calls rsock_connect which uses the Fiber-aware wait_connectable), but init_fast_fallback_inetsock_internal is hard-coded to use thread stuff.
In case anybody stumbles across this wondering why Net::HTTP sometimes blocks the Fiber scheduler during connect(), here's a quick workaround by hacking default fast_fallback: false into TCPSocket.open:
orig_open = TCPSocket.method(:open)
TCPSocket.define_singleton_method(:open) do |*args, **kwargs, &block|
kwargs[:fast_fallback] ||= false
orig_open.call(*args, **kwargs, &block)
end
A slightly fancier workaround would be to have TCPSocket#initialize default fast_fallback to false if the current scheduler is non-nil. That would get rid of unexpected scheduler blocking without requiring a rewrite of the fast fallback code to be fiber-aware. I'm not sure if that's as trivial to implement in a c-defined method as it is in a native Ruby definition.
Updated by drahosj (Jake Drahos) over 1 year ago
· Edited
Ignore the hack workaround above; the default for fast fallback is exposed and can be set back to false per 3.4.0 release notes. https://www.ruby-lang.org/en/news/2024/12/25/ruby-3-4-0-released/
Updated by byroot (Jean Boussier) over 1 year ago
- Assignee set to ioquatix (Samuel Williams)
Updated by hsbt (Hiroshi SHIBATA) over 1 year ago
- Status changed from Open to Assigned
Updated by sampokuokkanen (Sampo Kuokkanen) about 1 month ago
The DNS side has the same problem. Only rsock_getaddrinfo asks the scheduler's address_resolve, and the fast-fallback path resolves on its own threads, so the default TCPSocket.new never calls the hook. The address_resolve docs list TCPSocket.new as a caller, so I think this is a bug too. I ran into it while adding address_resolve support to JRuby's TCPSocket.new.
require "socket"
class Scheduler
def address_resolve(host) = host == "hooked.test" ? ["127.0.0.1"] : nil
def io_wait(io, events, timeout)
r = events.anybits?(IO::READABLE) ? [io] : nil
w = events.anybits?(IO::WRITABLE) ? [io] : nil
IO.select(r, w, nil, timeout) ? events : false
end
def kernel_sleep(*) = raise(NotImplementedError)
def block(*) = raise(NotImplementedError)
def unblock(*) = raise(NotImplementedError)
def fiber_interrupt(*) = raise(NotImplementedError)
def fiber(&) = Fiber.new(blocking: false, &).tap(&:resume)
def close = nil
end
port = TCPServer.new("127.0.0.1", 0).addr[1]
Thread.new do
Fiber.set_scheduler(Scheduler.new)
Fiber.schedule do
[{fast_fallback: false}, {}].each do |opts|
TCPSocket.new("hooked.test", port, **opts).close
puts "#{opts}: connected"
rescue => e
puts "#{opts}: #{e.class}"
end
end
end.join
On 3.4.11, 4.0.7 and master this prints:
Falling back to the old path when a scheduler is set, as suggested above, would fix this as well.
Updated by thomas_witt (Thomas Witt) 1 day ago
I found this while investigating slow DynamoDB queries from fibers in a Rails app on Falcon. By default, the AWS SDK for Ruby uses Net::HTTP, which calls TCPSocket.open for new connections.
I reproduced the scheduler stall while TCPSocket.new waited for resolver results on Ruby 3.4.13, 4.0.10 and 4.1.0-preview1. Five connects in separate fibers took about five times as long as one. A connect wrapped in Timeout.timeout(0.05) returned normally after the deadline. With PR 18370, five connects took about as long as one, and the timeout raised Timeout::Error.
If this fix is merged, please consider backporting it to 4.0.
Each SDK batch started with an empty connection pool and sent ten DynamoDB queries to a local HTTPS server. DNS replies for ddb.repro.test were delayed by 100 ms. Times in ms on aarch64-linux, median of five batches, first of two runs per build. Benchmark script, run with TRANSPORTS=net_http REAL_DNS_MS=100.
PR cb5fa1e9fc |
same tree, ext/socket/ipsocket.c change reverted |
|
|---|---|---|
| threads | 162 | 163 |
| fibers | 161 | 576 |
fibers, Socket.tcp_fast_fallback = false |
163 | 160 |
With the change reverted and fast fallback enabled, the server accepted five connections per ten-request fiber batch. It accepted ten per batch in every other SDK case shown.
For the direct TCPSocket.new test on localhost, test_mode_settings delays resolver notifications. Times in ms on aarch64-linux. The fiber and timeout cases use async 2.46.0. First run shown (three per release, two per PR configuration).
| 3.4.13 | 4.0.10 | 4.1.0-preview1 | PR cb5fa1e9fc |
same tree, ext/socket/ipsocket.c change reverted |
|
|---|---|---|---|---|---|
| 1 connect | 210 | 203 | 110 | 204 | 202 |
| 5 connects in threads | 204 | 206 | 103 | 204 | 204 |
| 5 connects in fibers | 1027 | 1028 | 534 | 208 | 1021 |
longest observed sleep 0.001 |
208 | 212 | 111 | 2 | 207 |
Timeout.timeout(0.05) around 1 connect |
no exception after 212 | no exception after 209 | no exception after 110 | Timeout::Error after 58 | no exception after 204 |
- A per-family value of
100requests 201 ms on 3.4.13, 4.0.10 and both PR builds, and 100 ms on 4.1.0-preview1 (NUM2LONG, 3b64ab47d0). - For TCP setup, net-http 0.6.0 on Ruby 3.4.13 wraps
TCPSocket.openinTimeout.timeout(@open_timeout, Net::OpenTimeout). Version 0.9.1 passesopen_timeout:when supported, including on Ruby 4.0.10, and otherwise uses the wrapper.
Socket test script:
# Bug #21270: TCPSocket.new('localhost', port) in threads and in fibers, with delayed resolver notifications.
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'async'
end
require 'socket'
require 'timeout'
N = 5
DELAY = { test_mode_settings: { delay: { ipv4: 100, ipv6: 100 } } }.freeze
servers = [TCPServer.new('127.0.0.1', 0)]
PORT = servers.first.addr[1]
servers << TCPServer.new('::1', PORT) if Socket.ip_address_list.any?(&:ipv6_loopback?)
servers.each { |server| Thread.new { loop { server.accept.close } } }
def ms
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
yield
((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
end
def connect(**options) = TCPSocket.new('localhost', PORT, **options).close
puts RUBY_DESCRIPTION, "async #{Async::VERSION}, Socket.tcp_fast_fallback=#{Socket.tcp_fast_fallback}"
puts "1 connect: #{ms { connect(**DELAY) }} ms"
puts "#{N} connects in threads: #{ms { Array.new(N) { Thread.new { connect(**DELAY) } }.each(&:join) }} ms"
Sync do |task|
late = 0
timer = task.async { loop { late = [late, ms { sleep 0.001 }].max } }
puts "#{N} connects in fibers: #{ms { Array.new(N) { task.async { connect(**DELAY) } }.each(&:wait) }} ms"
sleep 0.005
timer.stop
puts "longest observed `sleep 0.001`: #{late} ms"
result = nil
elapsed = ms do
Timeout.timeout(0.05) { connect(**DELAY) }
result = 'no exception'
rescue Timeout::Error => e
result = e.class.name
end
puts "Timeout.timeout(0.05) around 1 connect: #{result} after #{elapsed} ms"
end