Skip to content

MQTT publisher is never disconnected (resource leak) #16

Closed

Description

@ritwiktiwari

Reviewing for JOSS (openjournals/joss-reviews#11038) on v0.9.2.

When MQTT is configured, Tracker.__init__ calls _setup_mqtt_publisher(), which calls connect() and starts a background thread via paho's loop_start(). But there is no matching disconnect() call anywhere in the teardown path. The paho network-loop thread keeps running after the tracker stops, and the MQTT DISCONNECT packet is never sent to the broker.

Where in the code:

Steps to reproduce:

from unittest.mock import MagicMock, patch
from wattameter.tracker import Tracker

reader = MagicMock()
reader.tags = ["gpu-0[mW]"]
reader.read.return_value = [100]
reader.derived_tags = []
reader.compute_derived.return_value = []

with patch("wattameter.tracker.MQTT_AVAILABLE", True):
    with patch("wattameter.tracker.MQTTPublisher") as MockPub:
        inst = MockPub.return_value
        inst.connect.return_value = True

        tracker = Tracker(reader, dt_read=0.1, freq_write=10,
                          mqtt_config={"broker_host": "localhost"})
        tracker.__enter__()
        tracker.__exit__(None, None, None)

        inst.disconnect.assert_not_called()  # passes (proves the leak)
        print("disconnect() was never called after tracker exit")

Suggested fix:
Add MQTT cleanup to Tracker.__exit__ (or add a stop() override):

def __exit__(self, exc_type, exc_value, traceback):
    super().stop(self.freq_write)
    if self.mqtt_publisher:
        self.mqtt_publisher.disconnect()
    ...

Activity

  1. added 2 commits that reference this issue on Sep 15, 2026
  2. weslleyspereira commented on Sep 15, 2026

    @weslleyspereira
    Collaborator

    Should be resolved with #32. Please let us know if not.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions