From: "thomas_witt (Thomas Witt) via ruby-core" Date: 2026-12-01T10:08:00+00:00 Subject: [ruby-core:127781] [Ruby Bug#21270] init_fast_fallback_inetsock_internal (default for TCPSocket.new/TCPSocket.open) isn't fiber aware Issue #21270 has been updated by thomas_witt (Thomas Witt). I found this while [investigating slow DynamoDB queries](https://github.com/aws/aws-sdk-ruby/issues/2621#issuecomment-7304622014) 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](https://github.com/ruby/ruby/pull/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](https://github.com/thomaswitt/aws-sdk-http-async/blob/a619fff3d99ff93f6c635b96f5210104605906af/benchmark/repro.rb), 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 `100` requests 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.open` in `Timeout.timeout(@open_timeout, Net::OpenTimeout)`. Version 0.9.1 passes `open_timeout:` when supported, including on Ruby 4.0.10, and otherwise uses the wrapper. Socket test script: ```ruby # 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 ``` ---------------------------------------- Bug #21270: init_fast_fallback_inetsock_internal (default for TCPSocket.new/TCPSocket.open) isn't fiber aware https://bugs.ruby-lang.org/issues/21270#change-120339 * Author: drahosj (Jake Drahos) * Status: Assigned * Assignee: ioquatix (Samuel Williams) * ruby -v: ruby 3.4.2 * Backport: 3.2: UNKNOWN, 3.3: UNKNOWN, 3.4: UNKNOWN ---------------------------------------- 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). ``` ruby 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: ``` shell $ 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: ``` shell $ ruby async-request.rb 16: Main fiber 24: Creating socket [Hangs here until the connect times out] ``` 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=, a2=, a3=, a4=, a5=a5@entry=0, a6=a6@entry=0, nr=270) at cancellation.c:49 #2 0x00007fc9e4c95871 in __syscall_cancel (a1=, a2=, a3=, a4=, a5=a5@entry=0, a6=a6@entry=0, nr=270) at cancellation.c:75 #3 0x00007fc9e4d1af07 in __GI___select (nfds=, readfds=, writefds=, exceptfds=, timeout=) at ../sysdeps/unix/sysv/linux/select.c:69 #4 0x00007fc9e5233c9f in rb_fd_select (n=, readfds=, writefds=, exceptfds=, timeout=) at /usr/src/debug/ruby-3.4.2/thread.c:4163 #5 0x00007fc9e5236cc6 in native_fd_select (n=, readfds=, writefds=, exceptfds=, timeout=, th=) 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 , data1=140504668626880, e_proc=0x7fc9e5232440 , 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 , data1=data1@entry=140504668627872, e_proc=e_proc@entry=0x7fc9c97b7880 , 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=, connect_timeout=, fast_fallback=, test_mode_settings=) at /usr/src/debug/ruby-3.4.2/ext/socket/ipsocket.c:1285 #12 0x00007fc9c97b8216 in tcp_init (argc=, argv=, 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`: ``` ruby 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. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/