Skip to content

Fix reader thread raising exceptions into wrong thread#170

Open
bmorrall wants to merge 2 commits into
njh:mainfrom
sphere-drones:bugfix/reader-thread-errors
Open

Fix reader thread raising exceptions into wrong thread#170
bmorrall wants to merge 2 commits into
njh:mainfrom
sphere-drones:bugfix/reader-thread-errors

Conversation

@bmorrall
Copy link
Copy Markdown

@bmorrall bmorrall commented May 21, 2026

Closes #169

Fixes the bug where reader thread exceptions were delivered via Thread#raise to
whichever thread called connect, rather than the thread actively using the connection.
This made the client unsafe to use with connection pools or in any multi-threaded context.

What changed

Instead of capturing the connect-caller as a "parent" and using Thread#raise to
deliver errors cross-thread, exceptions are now stored on the client instance under
a mutex:

@exception_mutex.synchronize { @last_exception = exp }

Every public method that uses the socket (publish, subscribe, get_packet) calls
check_for_exception! before proceeding. This re-raises the stored exception in
whichever thread is actually doing the work, and clears it atomically so it fires
exactly once.

Behaviour

  • A thread using a broken connection receives the error immediately on its next call
  • No exception is ever injected into an unrelated thread
  • disconnect and connect both clear the stored exception, so reconnect is always a clean slate
  • If the stored exception is raised and the caller rescues it, subsequent calls raise MQTT::NotConnectedException (the normal not-connected path) rather than replaying the stale error

Tests

The two specs that explicitly wired up Thread.current[:parent] and expected
Thread#raise to be called have been updated to verify the new behaviour: that the
exception is stored and re-raised by check_for_exception! in the calling thread.

@bmorrall bmorrall force-pushed the bugfix/reader-thread-errors branch from 2ee8437 to 615fcb7 Compare May 21, 2026 07:46
@bmorrall bmorrall force-pushed the bugfix/reader-thread-errors branch from 615fcb7 to 3ee8b9b Compare May 21, 2026 07:49
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.

Reader thread raises exceptions into the wrong thread, breaking connection pool usage

1 participant