From bdfd403232abbddcfea5705034ff3733fd9e6f02 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:19 +0100 Subject: [PATCH 01/23] fix(browser): always attempt every quit cleanup stage --- lib/ferrum/browser.rb | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index 49eb5764..f6d4a30c 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -230,13 +230,21 @@ def restart # The background cleanup thread when `wait: false`, `nil` otherwise. # def quit(wait: true) - return unless @client + return unless @client || @process - contexts&.close_connections - - @client.close - thread = @process.stop(wait: wait) + client, process, contexts = @client, @process, @contexts @client = @process = @contexts = nil + + thread = nil + begin + contexts&.close_connections + ensure + begin + client&.close + ensure + thread = process&.stop(wait: wait) + end + end thread end From e9c856c119d16dae789fe556b7618841dce7bced Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:22 +0100 Subject: [PATCH 02/23] fix(client): force-close websocket when cleanup raises --- lib/ferrum/client.rb | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/ferrum/client.rb b/lib/ferrum/client.rb index 69fe4bd3..a42f1712 100644 --- a/lib/ferrum/client.rb +++ b/lib/ferrum/client.rb @@ -301,11 +301,21 @@ def session(session_id) # def close @ws.close - # Give a thread some time to handle a tail of messages - @pendings.clear - @thread.kill unless @thread.join(1) - @subscriber.close - @ws.force_close + ensure + begin + # Give a thread some time to handle a tail of messages + @pendings.clear + ensure + begin + @thread.kill unless @thread.join(1) + ensure + begin + @subscriber.close + ensure + @ws.force_close + end + end + end end # From 02576d5f1463afeff4112be4ac1951a3abada4e7 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:25 +0100 Subject: [PATCH 03/23] fix(process): isolate Chromium temporary files per browser --- lib/ferrum/browser/process.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/ferrum/browser/process.rb b/lib/ferrum/browser/process.rb index 37f66bb1..052669ea 100644 --- a/lib/ferrum/browser/process.rb +++ b/lib/ferrum/browser/process.rb @@ -66,6 +66,13 @@ def initialize(options) @env = Hash(options.env) @user_data_dir = Dir.mktmpdir("ferrum_user_data_dir_") + if Utils::Platform.platform_name == :linux + # Chromium uses TMPDIR for files such as its process-singleton + # socket. Keep them inside this browser's directory so stop can + # remove them without touching another browser's files. + @temp_dir = File.join(@user_data_dir, "tmp") + Dir.mkdir(@temp_dir) + end @command = Command.build(options, @user_data_dir) end @@ -143,6 +150,7 @@ def spawn_browser(io) process_options = { in: File::NULL, out: io, err: io } process_options[:pgroup] = true unless Utils::Platform.windows? env = Hash(@xvfb&.to_env).merge(@env) + env["TMPDIR"] = @temp_dir if @temp_dir @pid = ::Process.spawn(env, *@command.to_a, process_options) ObjectSpace.define_finalizer(self, Killer.finalizer([@pid, @xvfb&.pid], @user_data_dir)) From 1f9e08375b64c7a59ec3d046731ce6e4b2274316 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:28 +0100 Subject: [PATCH 04/23] test(process): verify per-browser Chromium temp directory --- spec/unit/browser/process_spec.rb | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/spec/unit/browser/process_spec.rb b/spec/unit/browser/process_spec.rb index e7621393..efc8ca19 100644 --- a/spec/unit/browser/process_spec.rb +++ b/spec/unit/browser/process_spec.rb @@ -77,11 +77,34 @@ process.stop end + it "keeps Chromium temporary files inside the browser user data directory", if: Ferrum::Utils::Platform.platform_name == :linux do + process = described_class.new(Ferrum::Browser::Options.new) + user_data_dir = process.instance_variable_get(:@user_data_dir) + temp_dir = File.join(user_data_dir, "tmp") + + expect(Dir).to exist(temp_dir) + expect(Process).to receive(:spawn) do |env, *| + expect(env["TMPDIR"]).to eq(temp_dir) + expect(env["LD_PRELOAD"]).to be_nil + 5678 + end + allow(Process).to receive(:kill) + allow(Process).to receive(:wait).and_return(5678) + allow_any_instance_of(described_class).to receive(:parse_ws_url) + + process.start + process.stop + + expect(Dir).not_to exist(user_data_dir) + ensure + process&.stop + end + it "passes env through to the browser process" do allow(Process).to receive(:wait).and_return(nil) allow(Ferrum::Client).to receive(:new).and_return(client) - allow(Process).to receive(:spawn).with({ "LD_PRELOAD" => "some.so" }, any_args).and_return(123_456_789) + allow(Process).to receive(:spawn).with(hash_including("LD_PRELOAD" => "some.so"), any_args).and_return(123_456_789) allow_any_instance_of(Ferrum::Browser::Process).to receive(:parse_ws_url) From 5c574ae763d2d99de4e209a4b32e3c392bef0f0c Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:31 +0100 Subject: [PATCH 05/23] test(browser): cover cleanup after quit failures --- spec/unit/browser_spec.rb | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb index a195f843..87f73554 100644 --- a/spec/unit/browser_spec.rb +++ b/spec/unit/browser_spec.rb @@ -50,6 +50,46 @@ def puts(*args) end end + describe "#quit" do + it "stops the process even when context cleanup raises" do + error = StandardError.new("context cleanup failed") + contexts = double(close_connections: true) + client = double(close: true) + process = double(stop: nil) + browser = described_class.allocate + browser.instance_variable_set(:@contexts, contexts) + browser.instance_variable_set(:@client, client) + browser.instance_variable_set(:@process, process) + + allow(contexts).to receive(:close_connections).and_raise(error) + + expect(client).to receive(:close) + expect(process).to receive(:stop).with(wait: true) + + expect { browser.quit }.to raise_error(error) + expect(browser.client).to be_nil + expect(browser.process).to be_nil + expect(browser.contexts).to be_nil + end + + it "stops the process even when client cleanup raises" do + error = StandardError.new("client cleanup failed") + contexts = double(close_connections: true) + client = double + process = double(stop: nil) + browser = described_class.allocate + browser.instance_variable_set(:@contexts, contexts) + browser.instance_variable_set(:@client, client) + browser.instance_variable_set(:@process, process) + + allow(client).to receive(:close).and_raise(error) + + expect(process).to receive(:stop).with(wait: true) + + expect { browser.quit }.to raise_error(error) + end + end + describe "#restart" do it "restarts a browser whose previous start died after the client was built" do browser = Ferrum::Browser.new From 9d92458605317d582fc89c5e6d0e83c36e3d58b8 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:35 +0100 Subject: [PATCH 06/23] test(client): cover websocket close failure cleanup --- spec/unit/client_spec.rb | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb index 15875d90..7e3381d5 100644 --- a/spec/unit/client_spec.rb +++ b/spec/unit/client_spec.rb @@ -10,6 +10,28 @@ client.instance_variable_set(:@command_id_mutex, Mutex.new) end + describe "#close" do + it "stops every client resource when the websocket close handshake raises" do + error = StandardError.new("websocket close failed") + ws = double(force_close: true) + thread = double(join: false, kill: true) + subscriber = double(close: true) + client.instance_variable_set(:@ws, ws) + client.instance_variable_set(:@pendings, {}) + client.instance_variable_set(:@thread, thread) + client.instance_variable_set(:@subscriber, subscriber) + + allow(ws).to receive(:close).and_raise(error) + + expect(thread).to receive(:join).with(1) + expect(thread).to receive(:kill) + expect(subscriber).to receive(:close) + expect(ws).to receive(:force_close) + + expect { client.close }.to raise_error(error) + end + end + describe "#build_message" do it "carries the method and params" do expect(client.build_message("Page.enable", foo: 1)).to include(method: "Page.enable", params: { foo: 1 }) From 88f2ff6d1d941ca222f2a4c9fcd3f9fc03692ad0 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:38 +0100 Subject: [PATCH 07/23] docs: note browser cleanup fixes --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 029778c8..15951c27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,11 @@ `go_to` instead ### Fixed +- Browser GC finalization closes the CDP socket without running thread or queue operations in finalizer context +- Unquit browsers close their CDP connections and stop their browser process when garbage-collected +- WebSocket connections now close their local socket and writer when the peer disconnects unexpectedly +- Chromium's Linux temporary files now live inside each browser's Ferrum user-data directory and are removed with it +- `Browser#quit` and `Client#close` continue cleanup when an earlier close step raises - `AuthRequest#abort` raised `BrowserError` and left the page hanging, it cancels the auth challenge now - `InterceptedRequest#navigation_request?` and `AuthRequest#navigation_request?` always returned `nil`, they are true for document requests now From 75a13cc82f8c86c98510fd023157224b6e077aca Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:33:47 +0100 Subject: [PATCH 08/23] test(process): avoid spawning or waiting for a fake browser pid --- spec/unit/browser/process_spec.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spec/unit/browser/process_spec.rb b/spec/unit/browser/process_spec.rb index efc8ca19..b3493ab7 100644 --- a/spec/unit/browser/process_spec.rb +++ b/spec/unit/browser/process_spec.rb @@ -88,8 +88,7 @@ expect(env["LD_PRELOAD"]).to be_nil 5678 end - allow(Process).to receive(:kill) - allow(Process).to receive(:wait).and_return(5678) + allow(Ferrum::Browser::Process::Killer).to receive(:kill) allow_any_instance_of(described_class).to receive(:parse_ws_url) process.start From 22004569a1eb7ad09c1a5474be69ee5c37b687cf Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Fri, 6 Nov 2026 12:34:13 +0100 Subject: [PATCH 09/23] test(process): assert temp directory state directly --- spec/unit/browser/process_spec.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/unit/browser/process_spec.rb b/spec/unit/browser/process_spec.rb index b3493ab7..de71ee36 100644 --- a/spec/unit/browser/process_spec.rb +++ b/spec/unit/browser/process_spec.rb @@ -82,7 +82,7 @@ user_data_dir = process.instance_variable_get(:@user_data_dir) temp_dir = File.join(user_data_dir, "tmp") - expect(Dir).to exist(temp_dir) + expect(Dir.exist?(temp_dir)).to be true expect(Process).to receive(:spawn) do |env, *| expect(env["TMPDIR"]).to eq(temp_dir) expect(env["LD_PRELOAD"]).to be_nil @@ -94,7 +94,7 @@ process.start process.stop - expect(Dir).not_to exist(user_data_dir) + expect(Dir.exist?(user_data_dir)).to be false ensure process&.stop end From 6bd9b83acebf2aec7ba76ab1c30dbf0f6ad3123c Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Sat, 7 Nov 2026 19:27:32 +0100 Subject: [PATCH 10/23] fix: close websocket socket when reader reaches EOF --- lib/ferrum/client/web_socket.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/ferrum/client/web_socket.rb b/lib/ferrum/client/web_socket.rb index 196d5571..8cfb458a 100644 --- a/lib/ferrum/client/web_socket.rb +++ b/lib/ferrum/client/web_socket.rb @@ -236,6 +236,8 @@ def start warn("Ferrum: websocket reader stopped, #{e.class}: #{e.message}\n #{e.backtrace&.first}") ensure @messages.close + @outgoing.close + force_close end end From 9dda53e7d800ee5f3ca29075df2db934c45ab088 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Sat, 7 Nov 2026 19:27:40 +0100 Subject: [PATCH 11/23] test: cover websocket cleanup after peer EOF --- spec/unit/client/web_socket_spec.rb | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/spec/unit/client/web_socket_spec.rb b/spec/unit/client/web_socket_spec.rb index 5d3dc970..5d2c9e53 100644 --- a/spec/unit/client/web_socket_spec.rb +++ b/spec/unit/client/web_socket_spec.rb @@ -37,6 +37,33 @@ def peak_concurrent_writes = @peak.value web_socket.instance_variable_set(:@encoded, []) end + describe "reader cleanup" do + it "closes the socket and writer when the peer closes the connection" do + socket, peer = Socket.pair(:UNIX, :STREAM, 0) + messages = Queue.new + outgoing = Queue.new + web_socket.instance_variable_set(:@sock, socket) + web_socket.instance_variable_set(:@messages, messages) + web_socket.instance_variable_set(:@outgoing, outgoing) + + web_socket.send(:start_writer) + web_socket.send(:start) + reader = web_socket.instance_variable_get(:@thread) + writer = web_socket.instance_variable_get(:@writer) + + peer.close + + expect(reader.join(1)).to eq(reader) + expect(writer.join(1)).to eq(writer) + expect(socket).to be_closed + expect(messages).to be_closed + expect(outgoing).to be_closed + ensure + peer&.close unless peer&.closed? + socket&.close unless socket&.closed? + end + end + describe "#send_message" do it "hands the driver the message as JSON" do web_socket.send_message(id: 1) From b0c0cf2b6ab98c598cc966605aef1f13978baab5 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Sun, 8 Nov 2026 16:21:10 +0100 Subject: [PATCH 12/23] fix(browser): clean up unquit browsers on garbage collection --- lib/ferrum/browser.rb | 28 ++++++++++++++++++++++++++++ spec/unit/browser_spec.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index f6d4a30c..a77d94d8 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -232,6 +232,7 @@ def restart def quit(wait: true) return unless @client || @process + ObjectSpace.undefine_finalizer(self) client, process, contexts = @client, @process, @contexts @client = @process = @contexts = nil @@ -305,12 +306,39 @@ def start @client = Client.new(@process.ws_url, options) @options.default_user_agent = version.user_agent @contexts = Contexts.new(@client) + ObjectSpace.define_finalizer(self, self.class.send(:finalizer, @contexts, @client, @process)) rescue StandardError @process.stop raise end end + # The finalizer must not capture the Browser instance itself. It owns + # only the resources needed to perform the same best-effort shutdown as + # #quit. Explicit #quit unregisters it before taking ownership of cleanup. + def self.finalizer(contexts, client, process) + proc do + begin + contexts&.close_connections + rescue StandardError => e + warn("[Ferrum] GC cleanup: closing contexts failed: #{e.class}: #{e.message}") + ensure + begin + client&.close + rescue StandardError => e + warn("[Ferrum] GC cleanup: closing client failed: #{e.class}: #{e.message}") + ensure + begin + process&.stop + rescue StandardError => e + warn("[Ferrum] GC cleanup: stopping browser process failed: #{e.class}: #{e.message}") + end + end + end + end + end + private_class_method :finalizer + def debug_url response = JSON.parse(Net::HTTP.get(URI(build_remote_debug_url(path: "/json")))) diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb index 87f73554..4238c3f6 100644 --- a/spec/unit/browser_spec.rb +++ b/spec/unit/browser_spec.rb @@ -90,6 +90,32 @@ def puts(*args) end end + describe "GC cleanup" do + it "closes contexts and client and stops the process when finalized" do + contexts = double(close_connections: true) + client = double(close: true) + process = double(stop: nil) + finalizer = described_class.send(:finalizer, contexts, client, process) + + expect(contexts).to receive(:close_connections) + expect(client).to receive(:close) + expect(process).to receive(:stop) + finalizer.call + end + + it "continues cleanup when an earlier finalizer step raises" do + contexts = double + client = double(close: true) + process = double(stop: nil) + allow(contexts).to receive(:close_connections).and_raise(StandardError, "context cleanup failed") + finalizer = described_class.send(:finalizer, contexts, client, process) + + expect(client).to receive(:close) + expect(process).to receive(:stop) + expect { finalizer.call }.not_to raise_error + end + end + describe "#restart" do it "restarts a browser whose previous start died after the client was built" do browser = Ferrum::Browser.new From dc18bac4cf462670627486b1aa7428ee0bd9a7a2 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Wed, 11 Nov 2026 10:45:12 +0100 Subject: [PATCH 13/23] fix(browser): keep GC cleanup trap-safe --- lib/ferrum/browser.rb | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index a77d94d8..c5e7cb60 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -306,33 +306,27 @@ def start @client = Client.new(@process.ws_url, options) @options.default_user_agent = version.user_agent @contexts = Contexts.new(@client) - ObjectSpace.define_finalizer(self, self.class.send(:finalizer, @contexts, @client, @process)) + ObjectSpace.define_finalizer(self, self.class.send(:finalizer, @client, @process)) rescue StandardError @process.stop raise end end - # The finalizer must not capture the Browser instance itself. It owns - # only the resources needed to perform the same best-effort shutdown as - # #quit. Explicit #quit unregisters it before taking ownership of cleanup. - def self.finalizer(contexts, client, process) + # The finalizer must not capture the Browser instance itself. Client#finalize + # only closes the socket; its reader and dispatch threads finish cleanup in + # their own thread contexts. Process#stop handles the local browser process. + def self.finalizer(client, process) proc do begin - contexts&.close_connections + client&.finalize rescue StandardError => e - warn("[Ferrum] GC cleanup: closing contexts failed: #{e.class}: #{e.message}") + warn("[Ferrum] GC cleanup: closing client socket failed: #{e.class}: #{e.message}") ensure begin - client&.close + process&.stop rescue StandardError => e - warn("[Ferrum] GC cleanup: closing client failed: #{e.class}: #{e.message}") - ensure - begin - process&.stop - rescue StandardError => e - warn("[Ferrum] GC cleanup: stopping browser process failed: #{e.class}: #{e.message}") - end + warn("[Ferrum] GC cleanup: stopping browser process failed: #{e.class}: #{e.message}") end end end From 82a64f6ee8a7ecbbaa89f9917c828c26d7699db6 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Wed, 11 Nov 2026 10:45:15 +0100 Subject: [PATCH 14/23] fix(websocket): add finalizer-safe socket close --- lib/ferrum/client/web_socket.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/ferrum/client/web_socket.rb b/lib/ferrum/client/web_socket.rb index 8cfb458a..4ea1eeb0 100644 --- a/lib/ferrum/client/web_socket.rb +++ b/lib/ferrum/client/web_socket.rb @@ -167,6 +167,16 @@ def close # # @return [void] # + # Closes only the underlying socket. This deliberately avoids queues, + # mutexes and thread operations so it can be called from a GC finalizer. + # The reader and writer threads perform their normal queue cleanup when + # the socket close wakes them. + def finalize + @sock.close unless @sock.closed? + rescue IOError, SystemCallError + # The socket may already have been closed by either worker thread. + end + def force_close @outgoing.close @sock.close unless @sock.closed? From b28e56d246fa16f412e8095f147f30bd4bc074ce Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Wed, 11 Nov 2026 10:45:18 +0100 Subject: [PATCH 15/23] fix(client): finish worker cleanup after socket finalization --- lib/ferrum/client.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/ferrum/client.rb b/lib/ferrum/client.rb index a42f1712..c39dcf81 100644 --- a/lib/ferrum/client.rb +++ b/lib/ferrum/client.rb @@ -299,6 +299,12 @@ def session(session_id) # # @return [void] # + # Closes the socket without touching queues, locks or threads. Safe for + # Browser's GC finalizer; the reader/dispatch threads complete cleanup. + def finalize + @ws.finalize + end + def close @ws.close ensure @@ -365,7 +371,11 @@ def start warn("Ferrum: dispatch stopped, #{e.class}: #{e.message}\n #{e.backtrace&.first}") @ws.messages.close ensure - release_pendings + begin + release_pendings + ensure + @subscriber.close + end end end From 594048a6ba079271a35c2a04027194fbc83d41db Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Wed, 11 Nov 2026 10:45:48 +0100 Subject: [PATCH 16/23] docs(client): clarify finalizer and close methods --- lib/ferrum/client.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/ferrum/client.rb b/lib/ferrum/client.rb index c39dcf81..b411a3b1 100644 --- a/lib/ferrum/client.rb +++ b/lib/ferrum/client.rb @@ -294,17 +294,21 @@ def session(session_id) end # - # Closes the underlying websocket, drops pending commands and stops - # the message-processing thread and subscriber. + # Closes the socket without touching queues, locks or threads. Safe for + # Browser's GC finalizer; the reader/dispatch threads complete cleanup. # # @return [void] # - # Closes the socket without touching queues, locks or threads. Safe for - # Browser's GC finalizer; the reader/dispatch threads complete cleanup. def finalize @ws.finalize end + # + # Closes the underlying websocket, drops pending commands and stops + # the message-processing thread and subscriber. + # + # @return [void] + # def close @ws.close ensure From 3478128e4f6f8843b63f2edc84ae922e679a2111 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Thu, 12 Nov 2026 13:09:40 +0100 Subject: [PATCH 17/23] fix: keep killing process group when leader was reaped --- lib/ferrum/browser/process/killer.rb | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/ferrum/browser/process/killer.rb b/lib/ferrum/browser/process/killer.rb index 96b054a0..85726394 100644 --- a/lib/ferrum/browser/process/killer.rb +++ b/lib/ferrum/browser/process/killer.rb @@ -51,7 +51,16 @@ def kill(pid) # renderer/zygote that ignores TERM. Reaping the leader must not # by itself end the loop, or that child is orphaned forever # since KILL is only ever sent from the timeout branch below. - leader_exited ||= !::Process.wait(pid, ::Process::WNOHANG).nil? + unless leader_exited + begin + leader_exited = !::Process.wait(pid, ::Process::WNOHANG).nil? + rescue Errno::ECHILD + # Another thread or a SIGCHLD handler may already have reaped + # the leader. The process group can still contain live Chrome + # children, so keep checking it and escalate to KILL if needed. + leader_exited = true + end + end break if leader_exited && !process_group_alive?(pid) sleep(WAIT_KILLED) @@ -61,8 +70,8 @@ def kill(pid) wait_reaped(pid) unless leader_exited break end - rescue Errno::ESRCH, Errno::ECHILD - # nop + rescue Errno::ESRCH + # The process and its group are already gone. end # From 84c7e96b64f3fe68b77fa4b50710a15893dac3cf Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Thu, 12 Nov 2026 13:09:42 +0100 Subject: [PATCH 18/23] test: cover already-reaped browser process leader --- spec/unit/browser/process/killer_spec.rb | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/spec/unit/browser/process/killer_spec.rb b/spec/unit/browser/process/killer_spec.rb index da3b594a..68d34982 100644 --- a/spec/unit/browser/process/killer_spec.rb +++ b/spec/unit/browser/process/killer_spec.rb @@ -161,6 +161,40 @@ def reaped?(pid) end describe ".kill", if: Ferrum::Utils::Platform.mri? && !Ferrum::Utils::Platform.windows? do + it "still kills the process group when the leader was already reaped" do + child_pid_path = File.join(Dir.tmpdir, "ferrum-process-spec-reaped-child-#{Process.pid}") + script = <<~RUBY + pid = fork do + trap("TERM", "IGNORE") + sleep 30 + end + Process.detach(pid) + File.write(#{child_pid_path.inspect}, pid.to_s) + sleep 30 + RUBY + leader_pid = Process.spawn(RbConfig.ruby, "-e", script, pgroup: true) + + begin + start = Ferrum::Utils::ElapsedTime.monotonic_time + sleep(0.05) until File.size?(child_pid_path) || Ferrum::Utils::ElapsedTime.timeout?(start, 5) + child_pid = File.read(child_pid_path).to_i + + allow(Process).to receive(:wait).and_raise(Errno::ECHILD) + described_class.kill(leader_pid) + allow(Process).to receive(:wait).and_call_original + + expect { Process.kill(0, child_pid) }.to raise_error(Errno::ESRCH) + ensure + allow(Process).to receive(:wait).and_call_original + begin + Process.kill("KILL", -leader_pid) if leader_pid + rescue Errno::ESRCH + nil + end + File.delete(child_pid_path) if File.exist?(child_pid_path) + end + end + it "kills the whole process group, not just the leader, when a group member ignores TERM" do child_pid_path = File.join(Dir.tmpdir, "ferrum-process-spec-child-pid-#{Process.pid}") From 1bbbe93c83e7eb63cb7e8c8d9944c3e21166a2b3 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Thu, 12 Nov 2026 13:09:44 +0100 Subject: [PATCH 19/23] test: align browser finalizer specs with socket-only cleanup --- spec/unit/browser_spec.rb | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb index 4238c3f6..f1f688f5 100644 --- a/spec/unit/browser_spec.rb +++ b/spec/unit/browser_spec.rb @@ -93,24 +93,22 @@ def puts(*args) describe "GC cleanup" do it "closes contexts and client and stops the process when finalized" do contexts = double(close_connections: true) - client = double(close: true) + client = double(finalize: true) process = double(stop: nil) - finalizer = described_class.send(:finalizer, contexts, client, process) + finalizer = described_class.send(:finalizer, client, process) - expect(contexts).to receive(:close_connections) - expect(client).to receive(:close) + expect(client).to receive(:finalize) expect(process).to receive(:stop) finalizer.call end it "continues cleanup when an earlier finalizer step raises" do contexts = double - client = double(close: true) + client = double(finalize: true) process = double(stop: nil) - allow(contexts).to receive(:close_connections).and_raise(StandardError, "context cleanup failed") - finalizer = described_class.send(:finalizer, contexts, client, process) + finalizer = described_class.send(:finalizer, client, process) - expect(client).to receive(:close) + expect(client).to receive(:finalize) expect(process).to receive(:stop) expect { finalizer.call }.not_to raise_error end From fd98af226527826d211bb0b74b3262a231cebecc Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Thu, 12 Nov 2026 13:09:53 +0100 Subject: [PATCH 20/23] test: cover socket finalizer failure handling --- spec/unit/browser_spec.rb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb index f1f688f5..edb72c5b 100644 --- a/spec/unit/browser_spec.rb +++ b/spec/unit/browser_spec.rb @@ -91,8 +91,7 @@ def puts(*args) end describe "GC cleanup" do - it "closes contexts and client and stops the process when finalized" do - contexts = double(close_connections: true) + it "closes the client socket and stops the process when finalized" do client = double(finalize: true) process = double(stop: nil) finalizer = described_class.send(:finalizer, client, process) @@ -102,13 +101,12 @@ def puts(*args) finalizer.call end - it "continues cleanup when an earlier finalizer step raises" do - contexts = double - client = double(finalize: true) + it "stops the process even when closing the client socket raises" do + client = double process = double(stop: nil) + allow(client).to receive(:finalize).and_raise(StandardError, "socket cleanup failed") finalizer = described_class.send(:finalizer, client, process) - expect(client).to receive(:finalize) expect(process).to receive(:stop) expect { finalizer.call }.not_to raise_error end From 68abc6e6453ed85150bd6ed274d7bc06e338ae9d Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Thu, 12 Nov 2026 13:23:49 +0100 Subject: [PATCH 21/23] test: simulate a genuinely reaped Chromium leader --- spec/unit/browser/process/killer_spec.rb | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/spec/unit/browser/process/killer_spec.rb b/spec/unit/browser/process/killer_spec.rb index 68d34982..dbf6bc99 100644 --- a/spec/unit/browser/process/killer_spec.rb +++ b/spec/unit/browser/process/killer_spec.rb @@ -179,13 +179,25 @@ def reaped?(pid) sleep(0.05) until File.size?(child_pid_path) || Ferrum::Utils::ElapsedTime.timeout?(start, 5) child_pid = File.read(child_pid_path).to_i - allow(Process).to receive(:wait).and_raise(Errno::ECHILD) + # Reap the leader for real while its detached child remains in the + # same process group. This reproduces ECHILD without stubbing wait. + Process.kill("TERM", leader_pid) + expect(Process.wait(leader_pid)).to eq(leader_pid) + described_class.kill(leader_pid) - allow(Process).to receive(:wait).and_call_original - expect { Process.kill(0, child_pid) }.to raise_error(Errno::ESRCH) + start = Ferrum::Utils::ElapsedTime.monotonic_time + loop do + begin + Process.kill(0, child_pid) + rescue Errno::ESRCH + break + end + raise "process group child survived KILL" if Ferrum::Utils::ElapsedTime.timeout?(start, 5) + + sleep(0.05) + end ensure - allow(Process).to receive(:wait).and_call_original begin Process.kill("KILL", -leader_pid) if leader_pid rescue Errno::ESRCH From 5c11a81da56d1ea8e36868f26710d84279d3407c Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Sat, 14 Nov 2026 17:41:11 +0100 Subject: [PATCH 22/23] Fix RuboCop offenses --- lib/ferrum/browser.rb | 19 +++++++++---------- spec/unit/browser/process/killer_spec.rb | 2 +- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index c5e7cb60..3505af44 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -233,10 +233,11 @@ def quit(wait: true) return unless @client || @process ObjectSpace.undefine_finalizer(self) - client, process, contexts = @client, @process, @contexts + client = @client + process = @process + contexts = @contexts @client = @process = @contexts = nil - thread = nil begin contexts&.close_connections ensure @@ -318,16 +319,14 @@ def start # their own thread contexts. Process#stop handles the local browser process. def self.finalizer(client, process) proc do + client&.finalize + rescue StandardError => e + warn("[Ferrum] GC cleanup: closing client socket failed: #{e.class}: #{e.message}") + ensure begin - client&.finalize + process&.stop rescue StandardError => e - warn("[Ferrum] GC cleanup: closing client socket failed: #{e.class}: #{e.message}") - ensure - begin - process&.stop - rescue StandardError => e - warn("[Ferrum] GC cleanup: stopping browser process failed: #{e.class}: #{e.message}") - end + warn("[Ferrum] GC cleanup: stopping browser process failed: #{e.class}: #{e.message}") end end end diff --git a/spec/unit/browser/process/killer_spec.rb b/spec/unit/browser/process/killer_spec.rb index dbf6bc99..2df566d8 100644 --- a/spec/unit/browser/process/killer_spec.rb +++ b/spec/unit/browser/process/killer_spec.rb @@ -203,7 +203,7 @@ def reaped?(pid) rescue Errno::ESRCH nil end - File.delete(child_pid_path) if File.exist?(child_pid_path) + FileUtils.rm_f(child_pid_path) end end From 88480d6cd447420e1bec017d89acfd9662a607c7 Mon Sep 17 00:00:00 2001 From: Dimitri Kulk Date: Sat, 14 Nov 2026 17:48:10 +0100 Subject: [PATCH 23/23] Capture expected GC cleanup warning in spec --- spec/unit/browser_spec.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb index edb72c5b..7d931722 100644 --- a/spec/unit/browser_spec.rb +++ b/spec/unit/browser_spec.rb @@ -108,7 +108,9 @@ def puts(*args) finalizer = described_class.send(:finalizer, client, process) expect(process).to receive(:stop) - expect { finalizer.call }.not_to raise_error + expect { finalizer.call }.to output( + "[Ferrum] GC cleanup: closing client socket failed: StandardError: socket cleanup failed\n" + ).to_stderr end end