Skip to content

feat(browser)!: add disconnect and shutdown, drop session callbacks when Chrome detaches a target - #750

Merged
route merged 1 commit into
mainfrom
feat/browser-disconnect
Nov 29, 2026
Merged

route merged 1 commit into
mainfrom
feat/browser-disconnect

Conversation

@route

@route route commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Teardown now comes in steps you can combine yourself. quit stays the safe default, and shutdown always ends the browser.

  • browser.close sends Browser.close, so Chrome exits gracefully, a remote one included.
  • browser.disconnect (new) closes the connection and leaves the browser running. browser.process stays reachable, so a launched browser can be stopped later.
  • browser.process.stop(grace:) kills a launched browser, reaps it and removes its temporary user data directory. grace: (new) waits that many seconds for it to exit on its own before signaling.
  • quit is disconnect followed by process.stop, and it now also stops a browser that was disconnected first. On a remote browser it still only disconnects.
  • browser.shutdown (new) is close, disconnect, then process.stop(grace: 2). A launched Chrome exits on its own, which lets it save a persistent :user_data_dir, and is killed only if it doesn't. Unlike quit, it also shuts down a remote browser. A browser that doesn't answer Browser.close raises TimeoutError; a launched one is killed first.
browser.quit      # leave a remote browser running
browser.shutdown  # always end the browser

The close_connection chain was left over from when every page had its own WebSocket. With a single connection it only removed a session's event callbacks, and only when the close went through Ferrum, so a page that closed itself, e.g. with window.close(), kept its callbacks for the rest of the browser's life. Now a session's callbacks are removed when Chrome reports it detached, whatever closed it.

Breaking:

  • page.close_connection and worker.close_connection are removed. The internal Target#close_connection, Context#close_targets_connection and Contexts#close_connections are removed too, and SessionClient#close is renamed to unsubscribe.

Browser-driven specs that were in spec/unit move to the feature specs.

…hen Chrome detaches a target

browser.disconnect closes the connection and leaves the browser running, keeping browser.process, so close, disconnect
and process.stop make up a custom shutdown. quit is disconnect followed by process.stop and still stops a browser
that was disconnected first. browser.shutdown sends Browser.close, disconnects and stops a launched process with
process.stop(grace:), which waits for it to exit on its own before TERM. Unlike quit it also shuts down a remote browser.

A session's event callbacks are now removed when Chrome reports it detached, which also covers a page that closes
itself, e.g. by window.close(), whose callbacks used to leak. The close_connection chain left over from per-page
WebSockets is removed: page.close_connection, worker.close_connection, Target#close_connection,
Context#close_targets_connection and Contexts#close_connections. SessionClient#close is renamed to unsubscribe.

Browser-driven specs that sat in spec/unit move to the feature specs.
@route
route force-pushed the feat/browser-disconnect branch from 6265757 to 0129a9a Compare November 29, 2026 20:42
@route route changed the title feat(browser)!: add disconnect and drop session callbacks when Chrome detaches a target feat(browser)!: add disconnect and shutdown, drop session callbacks when Chrome detaches a target Nov 29, 2026
@route
route merged commit f6e1da0 into main Nov 29, 2026
7 checks passed
@route
route deleted the feat/browser-disconnect branch November 29, 2026 20:53
@ZilvinasKucinskas

Copy link
Copy Markdown

shutdown leaves the client connected when Browser.close raises.

close_browser and disconnect share one begin, and only process.stop is in the ensure. Any error from Browser.close other than DeadBrowserError therefore skips disconnect: the TimeoutError of a browser that doesn't answer, which the docs describe, or a CDP error from a remote endpoint that refuses the command. The client's threads and socket stay alive, and browser.client still points at them.

Repro, stopping Chrome so Browser.close never answers:

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "ferrum", github: "rubycdp/ferrum", ref: ENV.fetch("REF", "main")
end

def threads = Thread.list.count { |t| t.alive? && !t.inspect.include?("thread_pool_executor") }

launched = Ferrum::Browser.new
before = threads
remote = Ferrum::Browser.new(ws_url: launched.process.ws_url.to_s, timeout: 2)
socket = remote.client.instance_variable_get(:@ws).instance_variable_get(:@sock)
puts "connected: +#{threads - before} threads"

Process.kill("STOP", launched.process.pid) # Chrome stops answering, so Browser.close times out
begin
  remote.shutdown
rescue Ferrum::TimeoutError => e
  puts "shutdown raised #{e.class}"
end
sleep 1

puts "after shutdown: +#{threads - before} threads, client #{remote.client ? "still set" : "nil"}, socket #{socket.closed? ? "closed" : "open"}"

Process.kill("CONT", launched.process.pid)
remote.quit
launched.quit

On main (9199cfb):

connected: +5 threads
shutdown raised Ferrum::TimeoutError
after shutdown: +5 threads, client still set, socket open

Backtest on a hung Chrome (SIGSTOP) and on a Browser.close that answers with an error (close stubbed to raise BrowserError), connected with :ws_url and launched:

Ref quit shutdown, no answer shutdown, error reply
7967359, before #750 clean n/a n/a
f6e1da0 (#750) and 9199cfb (main) clean :ws_url: 5 threads and the socket left; launched: 3 threads and the socket, after Chrome is killed same
main with the fix below clean clean clean

quit is unaffected on every ref, and shutdown of a healthy browser works on all of them.

Impact. The docs present shutdown as the way to always end a browser, so it ends up in ensure blocks and at_exit hooks, and it fails in the case those exist for: a hung or overloaded browser. For a launched browser the error comes after Chrome is killed, so the browser looks gone while its connection isn't, and nothing tells the caller to follow up with quit, which does clean up. A long-running process that starts and stops browsers (job workers, crawlers, test suites) keeps 3 to 5 threads and a file descriptor per failed shutdown until it exits.

Fix, disconnecting in the ensure:

       begin
         close_browser if @client
-        disconnect
       ensure
-        thread = @process&.stop(wait: wait, grace: Process::Killer::KILL_TIMEOUT)
-        @process = nil
+        begin
+          disconnect
+        ensure
+          thread = @process&.stop(wait: wait, grace: Process::Killer::KILL_TIMEOUT)
+          @process = nil
+        end
       end

With it, the #quit, #disconnect, #shutdown and #close examples in spec/browser_spec.rb still pass (12 examples), and this spec, which fails on main, passes:

describe Ferrum::Browser do
  describe "#shutdown" do
    [Ferrum::TimeoutError, Ferrum::BrowserError.new("message" => "not allowed")].each do |error|
      it "disconnects when Browser.close raises #{error.is_a?(Class) ? error : error.class}", :launch do
        browser = Ferrum::Browser.new
        allow(browser).to receive(:close).and_raise(error)

        expect { browser.shutdown }.to raise_error(error.is_a?(Class) ? error : error.class)
        expect(browser.client).to be_nil
        expect(browser.process).to be_nil
      ensure
        browser&.quit
      end
    end
  end
end

Nit: the disconnect doc comment still says it closes "the page connections", which this PR removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants