Skip to content

[rb] raise BiDi handler errors at the next command and serialize WebSocket writes - #18389

Merged
titusfortner merged 3 commits into
SeleniumHQ:trunkfrom
titusfortner:rb-listener-errors
Nov 25, 2026
Merged

titusfortner merged 3 commits into
SeleniumHQ:trunkfrom
titusfortner:rb-listener-errors

Conversation

@titusfortner

Copy link
Copy Markdown
Member

🔗 Related Issues

💥 What does this PR do?

  • Lays the groundwork in the Ruby BiDi bridge for raising an exception from handlers on the user's next command (either BiDi or classic), since the listener thread itself can't communicate it to the user's thread.
  • Fixes a bug where WebSocket commands sent at the same time from different threads can corrupt the WebSocket connection, mainly over wss://.

🔧 Implementation Notes

  • The store is per session and lives on the bridge, because it is the one object that sees both classic commands (execute) and BiDi commands (a before_send hook on the connection); Driver#network is created lazily, so a per-feature store has no hook for classic commands.
  • The store is opt-in: only features whose ADR says errors surface (network, alerts) call add, while script and low-level listeners keep logging per the proposed ADRs [adr] script and logging async/event API on driver.script #17776 and [adr] Behavioral contract for low-level event subscriptions #18299.
  • Listener threads are marked (as a thread variable, so fibers on them count too) and check does nothing on them, so a command a listener sends cannot take another listener's error and lose it to a log.
  • The check runs before a command so that a failed handler stops the next action, except delete_session, which is sent first and raises the stored error afterward, so a handler failure never leaves the browser open.

🤖 AI assistance

  • No substantial AI assistance used
  • AI assisted (complete below)
    • Tool(s): Claude Code (Claude Opus 5.5)
    • What was generated: the implementation, specs, and this description
    • I reviewed all AI output and can explain the change

🔄 Types of changes

  • Bug fix (backwards compatible) (concurrent WebSocket writes)
  • New feature (non-breaking change which adds functionality and tests!) (internal; nothing calls the store until the network and alert handlers land)

@selenium-ci

Copy link
Copy Markdown
Member

/agentic_describe

@selenium-ci selenium-ci added C-rb Ruby Bindings B-devtools Includes everything BiDi or Chrome DevTools related labels Nov 25, 2026
@qodo-code-review

qodo-code-review Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Surface stored BiDi listener errors and serialize WebSocket writes

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Add a session-wide store for opt-in listener errors, raised on the next user command.
• Preserve session cleanup before raising a stored error during quit.
• Serialize WebSocket frame writes to prevent concurrent commands from corrupting the connection.
Merge Risk 🔴 High

Blast radius 🔴 High 💥 3 capabilities

  • 3 affected capabilities span independent functional scopes: Chrome DevTools integration, WebDriver BiDi integration.
  • BiDi constructs WebSocketConnection and uses its command/response path for the end-to-end BiDi protocol behavior; the changed write path is therefore part of one BiDi command transport capability.
  • DevTools independently constructs and uses WebSocketConnection for its protocol commands.
  • Although the implementation boundary is shared, the affected browser-automation outcome is independent of the BiDi integration.
  • Listener dispatch, listener-thread command behavior, stored-error checks, subsequent BiDi/classic commands, and quit cleanup are one bounded BiDi integration outcome.
  • The inspected production callback rescue logs exceptions but does not call ListenerErrors#add, so the stored-error branch is a supported conditional behavior rather than a verified automatic callback path.
Sources

rb/lib/selenium/webdriver/remote/bidi_bridge.rb[48-55]

        # A stored error is raised once the session has ended, and outside Bridge#quit's rescue of connection errors
        def quit
          bidi&.close
        rescue *QUIT_ERRORS
          nil
        ensure
          super
          @listener_errors.check

rb/lib/selenium/webdriver/remote/bidi_bridge.rb[64-67]

        def execute(command, *)
          @listener_errors.check unless command == :delete_session
          super
        end

rb/lib/selenium/webdriver/common/listener_errors.rb[46-56]

      # Keeps only the first error until it is raised, since later ones are often its consequences
      def add(error)
        @mutex.synchronize { @error ||= error }
        nil
      end

      def check
        return if self.class.listener_thread?

        error = @mutex.synchronize { @error.tap { @error = nil } }
        raise error if error
Behavioral complexity 🔴 High 🧩 Interacting branches, Concurrent ordering

  • Before, concurrent callers could construct and write frames independently.
  • After, complete frame writes are serialized per connection and before-send callbacks can abort a command before transmission.
  • Before: pending-response registration, frame construction, socket write, and response waiting were not coordinated with a shared write lock.
  • After: callbacks run after pending registration but before frame construction, and socket.write occurs inside @write_mtx.
  • New correctness conditions: complete frames must not interleave across listener and driving threads; a callback refusal must remove pending state without sending; and write/response failure must preserve the command-tracking invariants while other callers use the connection.
Potential damage 🟡 Medium 🩹 Recoverable

  • A transport fault can temporarily prevent command delivery or response correlation within the affected session.
  • Recreating the session or retrying a safely retryable command can restore operation, but a remote command accepted before a client-side write/response failure may require caller-specific compensation.
  • Usually recoverable through a healthy connection/session restart or a command-specific retry.
  • Persistent browser-side effects are not automatically repaired by this change.
Assessed commit 20cde70
Diagram

graph TD
  L["Listener threads"] -->|opt-in errors| S["Error store"] -->|checked by| B["BiDi bridge"] -->|classic| C["HTTP commands"] --> R["Browser session"]
  B -->|BiDi| H["Before-send hook"] --> W["Serialized writes"] --> R
  L -->|listener commands| H
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Serialize entire WebSocket commands
  • ➕ Would also prevent concurrent frame writes with one lock.
  • ➖ Holding the lock while awaiting responses would block independent commands and could stall listener-driven commands.

Recommendation: Keep the session-wide store on the bridge, which sees both command paths, and lock only frame writes so commands can still await responses concurrently. The store is groundwork: this PR does not yet add an opt-in handler that calls add.

Files changed (12) +293 / -11

Enhancement (7) +124 / -1
listener.rbMark dispatched listener threads +2/-0

Mark dispatched listener threads

• Marks the thread before invoking a listener so commands issued there do not consume another thread's stored error.

rb/lib/selenium/webdriver/bidi/dispatcher/listener.rb

common.rbLoad the listener error store +1/-0

Load the listener error store

• Requires ListenerErrors with the shared WebDriver components.

rb/lib/selenium/webdriver/common.rb

listener_errors.rbAdd a thread-safe, session-scoped listener error store +60/-0

Add a thread-safe, session-scoped listener error store

• Retains the first error until a non-listener thread checks and raises it. Uses a thread variable so listener commands, including those issued from fibers, leave the error untouched.

rb/lib/selenium/webdriver/common/listener_errors.rb

bidi_bridge.rbCheck stored errors across both command paths +11/-1

Check stored errors across both command paths

• Creates a store per session and connects it to classic execution and the BiDi pre-send hook. Sends delete_session before checking for a stored error so quit still ends the session.

rb/lib/selenium/webdriver/remote/bidi_bridge.rb

listener_errors.rbsDeclare listener error store types +38/-0

Declare listener error store types

• Adds signatures for thread marking and the error store's add and check operations.

rb/sig/lib/selenium/webdriver/common/listener_errors.rbs

websocket_connection.rbsDeclare WebSocket hook and write-lock types +8/-0

Declare WebSocket hook and write-lock types

• Adds signatures for the pre-send callables, write mutex, and frame-writing method.

rb/sig/lib/selenium/webdriver/common/websocket_connection.rbs

bidi_bridge.rbsDeclare bridge error store and execute override +4/-0

Declare bridge error store and execute override

• Types the bridge's listener_errors reader and its private classic-command interception.

rb/sig/lib/selenium/webdriver/remote/bidi_bridge.rbs

Bug fix (1) +16 / -9
websocket_connection.rbSerialize frame writes and add a pre-send hook +16/-9

Serialize frame writes and add a pre-send hook

• Protects socket frame writes with a mutex to prevent concurrent writes from interleaving. Adds callables that can refuse a command before it is sent and marks callback threads as listener threads.

rb/lib/selenium/webdriver/common/websocket_connection.rb

Tests (4) +153 / -1
event_listeners_spec.rbVerify dispatched listeners are marked +8/-0

Verify dispatched listeners are marked

• Confirms that a dispatched BiDi listener runs on a thread identified as a listener thread.

rb/spec/unit/selenium/webdriver/bidi/event_listeners_spec.rb

listener_errors_spec.rbTest error retention and listener-thread isolation +74/-0

Test error retention and listener-thread isolation

• Covers empty checks, one-time raising, first-error retention, and checks from listener threads and fibers.

rb/spec/unit/selenium/webdriver/common/listener_errors_spec.rb

websocket_connection_spec.rbTest protected writes and pre-send hooks +35/-0

Test protected writes and pre-send hooks

• Verifies that socket writes hold the write mutex, hooks receive command payloads, and a rejecting hook sends nothing and clears pending state.

rb/spec/unit/selenium/webdriver/common/websocket_connection_spec.rb

bidi_bridge_spec.rbTest error delivery and quit cleanup +36/-1

Test error delivery and quit cleanup

• Checks that stored errors block the next classic or BiDi command and that quit deletes the session and closes HTTP before raising. Updates navigation doubles to expose the new hook.

rb/spec/unit/selenium/webdriver/remote/bidi_bridge_spec.rb

@qodo-code-review

qodo-code-review Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Quit silently drops some handler errors ✓ Resolved

Resolving commit: cbd0687

Resolution reason
The stored-error check for delete_session was moved out of execute and into BiDiBridge#quit's ensure
clause, after the parent Bridge#quit (and its QUIT_ERRORS rescue) completes, so stored connection
errors are raised to the user on quit instead of being logged.
Description
BiDiBridge#execute clears and raises a stored error inside its :delete_session branch, which
runs within Bridge#quit's rescue for connection errors. If a handler stored an IOError,
EOFError, or WebSocket::Error and the user's next command is quit, that rescue logs the error
instead of returning it to the user.


Remediation recommended

2. Pre-session status checks crash ✓ Resolved

Resolving commit: 20cde70

Resolution reason
N/A
Description
BiDiBridge#execute unconditionally calls @listener_errors.check for non-deletion commands, but
the store is initialized only in create_session. Calling status on a newly constructed bridge,
before creating a session, now raises NoMethodError instead of sending the session-independent
status request.


Informational

3. A handler error is lost when ending the session fails ✓ Resolved

Resolving commit: cbd0687

Resolution reason
Stored listener errors are now checked in quit's ensure block (after the session-ending call and
outside the QUIT_ERRORS rescue), so a handler error is raised even when delete_session fails with a
connection error. The old tap-on-super check for :delete_session was removed from execute. Specs
were added for both cases.
Description
BiDiBridge#execute runs @listener_errors.check in a tap on the result of super for
:delete_session, so the check never runs if super raises. Bridge#quit catches IOError,
EOFError and WebSocket::Error from delete_session and only writes a debug log, so if a handler
failure comes with a dropped connection, the user's original handler exception is never raised.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #17685
  🌐 PR #18384
  🌐 PR #17776
✅ REVIEW.md
Review mode: Auto: ⚖️ Balanced: Comparison failure: full PR diff.

Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 20cde70

Results up to commit 8d37253 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. Quit silently drops some handler errors ✓ Resolved

Resolving commit: cbd0687

Resolution reason
The stored-error check for delete_session was moved out of execute and into BiDiBridge#quit's ensure
clause, after the parent Bridge#quit (and its QUIT_ERRORS rescue) completes, so stored connection
errors are raised to the user on quit instead of being logged.
Description
BiDiBridge#execute clears and raises a stored error inside its :delete_session branch, which
runs within Bridge#quit's rescue for connection errors. If a handler stored an IOError,
EOFError, or WebSocket::Error and the user's next command is quit, that rescue logs the error
instead of returning it to the user.


Remediation recommended
2. Pre-session status checks crash ✓ Resolved

Resolving commit: 20cde70

Resolution reason
N/A
Description
BiDiBridge#execute unconditionally calls @listener_errors.check for non-deletion commands, but
the store is initialized only in create_session. Calling status on a newly constructed bridge,
before creating a session, now raises NoMethodError instead of sending the session-independent
status request.


Informational
3. A handler error is lost when ending the session fails ✓ Resolved

Resolving commit: cbd0687

Resolution reason
Stored listener errors are now checked in quit's ensure block (after the session-ending call and
outside the QUIT_ERRORS rescue), so a handler error is raised even when delete_session fails with a
connection error. The old tap-on-super check for :delete_session was removed from execute. Specs
were added for both cases.
Description
BiDiBridge#execute runs @listener_errors.check in a tap on the result of super for
:delete_session, so the check never runs if super raises. Bridge#quit catches IOError,
EOFError and WebSocket::Error from delete_session and only writes a debug log, so if a handler
failure comes with a dropped connection, the user's original handler exception is never raised.

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit cbd0687

@selenium-ci

Copy link
Copy Markdown
Member

/agentic_review

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 20cde70

@titusfortner
titusfortner merged commit c814e9d into SeleniumHQ:trunk Nov 25, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

B-devtools Includes everything BiDi or Chrome DevTools related C-rb Ruby Bindings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants