From bda94fb95132f1ff1cfea1a9483786fa66aafa70 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Tue, 1 Dec 2026 08:33:39 -0700 Subject: [PATCH 1/2] fix: stop replacing TERM/INT handlers on require Requiring the gem installed process-wide TERM and INT traps that called exit(0). This made interrupted processes exit with status 0, replaced any handlers the application had already registered, and stopped `rescue Interrupt` from catching Ctrl-C. The traps were unnecessary because the cleanup already runs from an at_exit hook, which Ruby also runs when the default INT/TERM handlers end the process. Remove the traps and add subprocess specs checking that existing handlers are kept, that the process is ended by the signal, and that the wrapper shutdown still runs. Fixes #253 --- lib/aws_advanced_ruby_driver_wrapper.rb | 12 ++-- spec/unit/shutdown_spec.rb | 84 +++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 7 deletions(-) diff --git a/lib/aws_advanced_ruby_driver_wrapper.rb b/lib/aws_advanced_ruby_driver_wrapper.rb index 2a699858..e0622380 100644 --- a/lib/aws_advanced_ruby_driver_wrapper.rb +++ b/lib/aws_advanced_ruby_driver_wrapper.rb @@ -58,8 +58,8 @@ class << self attr_reader :config end - # Gracefully tears down all background resources. Invoked by the at_exit hook (and thus - # indirectly by the TERM/INT signal traps, which just exit). Safe to call more than once. + # Gracefully tears down all background resources. Invoked by the at_exit hook. Safe to call more + # than once. def self.shutdown(grace_period_sec: 10) Plugins::BlueGreen::BlueGreenPlugin.clean_up_providers release_resources(grace_period_sec: grace_period_sec) @@ -114,11 +114,9 @@ def self.release_resources(grace_period_sec: 5) end end -# Register signal traps and at_exit hook for graceful shutdown. The traps only exit — the real -# teardown runs in the at_exit hook, since acquiring locks / joining threads inside a signal-trap -# context is unsafe in Ruby and can deadlock. -%w[TERM INT].each { |signal| trap(signal) { exit(0) } } - +# Tear down background resources when the process exits. at_exit hooks also run when the process is +# ended by INT or TERM under Ruby's default handlers, so the gem deliberately installs no signal +# handlers of its own: doing so would replace the application's handlers and change its exit status. at_exit { AwsAdvancedRubyDriverWrapper.shutdown } Process.singleton_class.prepend(AwsAdvancedRubyDriverWrapper::ForkHook) diff --git a/spec/unit/shutdown_spec.rb b/spec/unit/shutdown_spec.rb index bf01bbe3..d1f75998 100644 --- a/spec/unit/shutdown_spec.rb +++ b/spec/unit/shutdown_spec.rb @@ -15,6 +15,9 @@ # limitations under the License. require 'rspec' +require 'open3' +require 'rbconfig' +require 'timeout' require 'aws_advanced_ruby_driver_wrapper' require 'aws_advanced_ruby_driver_wrapper/monitoring/monitor' require 'aws_advanced_ruby_driver_wrapper/services/service_utility' @@ -47,3 +50,84 @@ def monitor described_class.shutdown end end + +# Signal handlers are process-wide, so these checks run in a fresh Ruby process rather than in the +# RSpec process. +RSpec.describe 'Signal handling after requiring the gem' do + lib_dir = File.expand_path('../../lib', __dir__) + + it 'keeps the TERM and INT handlers the application registered before the require' do + script = <<~RUBY + term_handler = proc {} + int_handler = proc {} + Signal.trap('TERM', term_handler) + Signal.trap('INT', int_handler) + require 'aws_advanced_ruby_driver_wrapper' + print Signal.trap('TERM', 'DEFAULT').equal?(term_handler) && Signal.trap('INT', 'DEFAULT').equal?(int_handler) + RUBY + + output, status = Open3.capture2e(RbConfig.ruby, '-I', lib_dir, '-e', script) + + expect(status).to be_success, output + expect(output).to eq('true') + end + + # Starts a process that requires the gem and sleeps, sends it +signal+, and returns its output and + # exit status. The process prints a marker once the wrapper's at_exit shutdown has completed. + def run_until_signaled(lib_dir, signal) + script = <<~RUBY + $stdout.sync = true + require 'aws_advanced_ruby_driver_wrapper' + AwsAdvancedRubyDriverWrapper.singleton_class.prepend(Module.new do + def shutdown(...) + super + puts 'shutdown ran' + end + end) + begin + puts 'ready' + sleep + rescue Interrupt + puts 'rescued Interrupt' + raise + end + RUBY + + Open3.popen3(RbConfig.ruby, '-I', lib_dir, '-e', script) do |_stdin, out, err, wait_thread| + err_reader = Thread.new { err.read } + Timeout.timeout(30) do + # Wait for the exact line on stdout so the signal is never sent while the gem is still loading. + line = out.gets + line = out.gets until line.nil? || line.chomp == 'ready' + raise "child exited before it was ready: #{out.read}#{err_reader.value}" if line.nil? + + Process.kill(signal, wait_thread.pid) + status = wait_thread.value + [out.read + err_reader.value, status] + end + ensure + # Open3 waits for the child when the block ends, so kill it if it is still running (for example + # after a timeout) instead of letting the suite hang. + begin + Process.kill('KILL', wait_thread.pid) if wait_thread.alive? + rescue Errno::ESRCH + # The child exited between the check and the kill. + end + end + end + + it 'is terminated by TERM and still runs the wrapper shutdown' do + output, status = run_until_signaled(lib_dir, 'TERM') + + expect(status.termsig).to eq(Signal.list['TERM']), output + expect(output).to include('shutdown ran') + end + + it 'raises Interrupt on INT, is terminated by INT, and still runs the wrapper shutdown' do + output, status = run_until_signaled(lib_dir, 'INT') + + expect(status.termsig).to eq(Signal.list['INT']), output + expect(output).to include('rescued Interrupt') + expect(output).to include('shutdown ran') + end +end From 709d0a3847b1e3d3beea3d74cadab7c440405554 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Tue, 1 Dec 2026 09:53:17 -0700 Subject: [PATCH 2/2] test: add monitor shutdown and source scan specs for signal handling Add a spec that starts a background monitor in a child process, sends TERM, and checks the at_exit shutdown stopped the monitor cleanly and quickly. Add a spec that parses every file under lib/ with Prism and fails if any calls trap, since many files are only loaded once a connection uses them and are not covered by checking handlers after a bare require. Make the handler-preservation spec compare only stdout and report each signal separately. --- spec/unit/shutdown_spec.rb | 98 ++++++++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 8 deletions(-) diff --git a/spec/unit/shutdown_spec.rb b/spec/unit/shutdown_spec.rb index d1f75998..eacfbdce 100644 --- a/spec/unit/shutdown_spec.rb +++ b/spec/unit/shutdown_spec.rb @@ -16,6 +16,7 @@ require 'rspec' require 'open3' +require 'prism' require 'rbconfig' require 'timeout' require 'aws_advanced_ruby_driver_wrapper' @@ -63,18 +64,26 @@ def monitor Signal.trap('TERM', term_handler) Signal.trap('INT', int_handler) require 'aws_advanced_ruby_driver_wrapper' - print Signal.trap('TERM', 'DEFAULT').equal?(term_handler) && Signal.trap('INT', 'DEFAULT').equal?(int_handler) + # Signal.trap returns the handler it replaces, so this prints whether each handler registered + # above is still the one installed after the require. + { 'TERM' => term_handler, 'INT' => int_handler }.each do |signal, handler| + puts "\#{signal} handler kept: \#{Signal.trap(signal, 'DEFAULT').equal?(handler)}" + end RUBY - output, status = Open3.capture2e(RbConfig.ruby, '-I', lib_dir, '-e', script) + # Pass/fail depends only on stdout, so a warning Ruby prints to stderr cannot fail the test. Stderr is + # still shown in the failure message to help debug a real failure. + stdout, stderr, status = Open3.capture3(RbConfig.ruby, '-I', lib_dir, '-e', script) - expect(status).to be_success, output - expect(output).to eq('true') + expect(status).to be_success, stderr + expect(stdout).to eq("TERM handler kept: true\nINT handler kept: true\n"), stderr end - # Starts a process that requires the gem and sleeps, sends it +signal+, and returns its output and - # exit status. The process prints a marker once the wrapper's at_exit shutdown has completed. - def run_until_signaled(lib_dir, signal) + # Starts a process that requires the gem, runs +setup+, and sleeps, then sends it +signal+. Returns + # the process's output, its exit status, and the seconds between the signal and the exit. The + # process prints a marker once the wrapper's at_exit shutdown has completed, followed by the state + # of the monitor in $signal_test_monitor, and whether its loop finished, if +setup+ started one. + def run_until_signaled(lib_dir, signal, setup: '') script = <<~RUBY $stdout.sync = true require 'aws_advanced_ruby_driver_wrapper' @@ -82,8 +91,13 @@ def run_until_signaled(lib_dir, signal) def shutdown(...) super puts 'shutdown ran' + if $signal_test_monitor + puts "monitor state: \#{$signal_test_monitor.state}" + puts "monitor finished: \#{$signal_test_monitor_finished == true}" + end end end) + #{setup} begin puts 'ready' sleep @@ -101,9 +115,11 @@ def shutdown(...) line = out.gets until line.nil? || line.chomp == 'ready' raise "child exited before it was ready: #{out.read}#{err_reader.value}" if line.nil? + signaled_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) Process.kill(signal, wait_thread.pid) status = wait_thread.value - [out.read + err_reader.value, status] + elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - signaled_at + [out.read + err_reader.value, status, elapsed] end ensure # Open3 waits for the child when the block ends, so kill it if it is still running (for example @@ -130,4 +146,70 @@ def shutdown(...) expect(output).to include('rescued Interrupt') expect(output).to include('shutdown ran') end + + it 'stops background monitors from the at_exit shutdown when terminated by TERM' do + # Monitor#stop kills a monitor thread that does not finish within its termination timeout and still + # reports the monitor as stopped, so the monitor records when its loop finishes on its own. The + # short timeout only keeps a monitor that ignores the stop request from delaying the test by the + # 30 second default. + setup = <<~RUBY + require 'aws_advanced_ruby_driver_wrapper/monitoring/monitor' + require 'aws_advanced_ruby_driver_wrapper/services/service_utility' + monitor_class = Class.new(AwsAdvancedRubyDriverWrapper::Monitoring::Monitor) do + def monitor + sleep(0.01) until stopped? + $signal_test_monitor_finished = true + end + end + monitor_service = AwsAdvancedRubyDriverWrapper::Services::CoreServices.monitor_service + monitor_service.register_type(:signal_test_monitor, expiration_timeout_sec: 60) + $signal_test_monitor = monitor_service.run_if_absent(:signal_test_monitor, 'k1', Object.new) do |_| + monitor_class.new(termination_timeout_sec: 2) + end + raise "monitor did not start: \#{$signal_test_monitor.state}" unless $signal_test_monitor.state == :running + RUBY + + output, status, elapsed = run_until_signaled(lib_dir, 'TERM', setup: setup) + + expect(status.termsig).to eq(Signal.list['TERM']), output + expect(output).to include('shutdown ran') + expect(output).to include('monitor state: stopped') + expect(output).to include('monitor finished: true') + # Shutdown wakes the monitor service's cleanup thread from its 60 second sleep and waits up to 5 + # seconds for it to exit. If the wakeup stopped working, every shutdown would take the full 5 seconds, + # which only this timing check would notice. + expect(elapsed).to be < 5, output + end +end + +# The gem must never install signal handlers, since doing so replaces the application's handlers. +# Many files under lib/ are only loaded once a connection uses them, so checking the handlers after +# requiring the gem cannot cover them. This parses every file instead and flags any call to a method +# named trap (Signal.trap, Kernel.trap or a bare trap). Indirect calls such as send(:trap) are not +# detected. +RSpec.describe 'Signal handlers in the gem source' do + trap_call_finder = Class.new(Prism::Visitor) do + attr_reader :lines + + def initialize + super + @lines = [] + end + + def visit_call_node(node) + @lines << node.location.start_line if node.name == :trap + super + end + end + + it 'does not register a signal handler in any file under lib/' do + lib_dir = File.expand_path('../../lib', __dir__) + offenders = Dir.glob('**/*.rb', base: lib_dir).flat_map do |relative_path| + finder = trap_call_finder.new + Prism.parse_file(File.join(lib_dir, relative_path)).value.accept(finder) + finder.lines.map { |line| "#{relative_path}:#{line}" } + end + + expect(offenders).to be_empty, "signal handlers registered at: #{offenders.join(', ')}" + end end