fix(B1): Future-Cleanup bei Disconnect — _pending_results werden mit DDPNotConnected aufgelöst

- _cancel_pending_results() löst alle pending Futures mit DDPNotConnected auf
- disconnect() ruft _cancel_pending_results() nach Socket-Close
- _reader_loop Exit-Pfad ruft _cancel_pending_results() nach self.connected=False
- PulseController._pulse_tick_async fängt Exception (inkl. DDPNotConnected) und fällt auf REST zurück
- 2 neue Tests: test_disconnect_clears_pending_futures, test_reader_loop_exit_clears_pending_futures
This commit is contained in:
Bernd (Hermes)
2026-07-24 19:41:25 +02:00
parent 0a05816b68
commit 90c122cc74
2 changed files with 79 additions and 0 deletions
+21
View File
@@ -451,6 +451,9 @@ class DDPClient:
except Exception: except Exception:
break break
self.connected = False self.connected = False
# B1: Reader loop exited — cancel all pending Futures so callers
# (e.g. PulseController) get DDPNotConnected and can fall back to REST.
self._cancel_pending_results()
logger.debug("DDP reader thread exited") logger.debug("DDP reader thread exited")
def is_alive(self, max_silence: float = 300.0) -> bool: def is_alive(self, max_silence: float = 300.0) -> bool:
@@ -768,6 +771,21 @@ class DDPClient:
len(stale_ids), len(stale_ids),
) )
def _cancel_pending_results(self) -> None:
"""B1: Resolve all pending Futures with DDPNotConnected and clear the store.
Called on disconnect and reader-loop exit to prevent memory leaks
from Futures that would otherwise hang forever waiting for a result
message that will never arrive.
"""
with self._result_lock:
for msg_id, future in list(self._pending_results.items()):
if not future.done():
future.set_exception(
DDPNotConnected("DDP connection closed — pending result cancelled")
)
self._pending_results.clear()
def disconnect(self): def disconnect(self):
self._running = False self._running = False
if self.sock: if self.sock:
@@ -777,6 +795,9 @@ class DDPClient:
pass pass
self.sock = None self.sock = None
self.connected = False self.connected = False
# B1: Cancel all pending Futures so callers (e.g. PulseController)
# get DDPNotConnected and can fall back to REST instead of hanging.
self._cancel_pending_results()
self._sub_rooms.clear() self._sub_rooms.clear()
# Bug 7: reconnect_and_restore() ist deprecated — sie umgeht M13 GC. # Bug 7: reconnect_and_restore() ist deprecated — sie umgeht M13 GC.
+58
View File
@@ -481,3 +481,61 @@ class TestLegacyTimerSetStatusRemainsSync:
adapter.ddp.set_status("away") adapter.ddp.set_status("away")
mock_ddp.set_status.assert_called_with("away") mock_ddp.set_status.assert_called_with("away")
# ═══════════════════════════════════════════════════════════════════════════
# Test 11: B1 — disconnect clears pending Futures with DDPNotConnected
# ═══════════════════════════════════════════════════════════════════════════
class TestDisconnectClearsPendingFutures:
"""B1: disconnect() löst alle pending Futures mit DDPNotConnected auf."""
def test_disconnect_clears_pending_futures(self):
"""Engine erstellt, set_status_async aufrufen, disconnect() → DDPNotConnected."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
async def _run():
# Starte set_status_async — registriert einen Future
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
await asyncio.sleep(0.05)
# Verifiziere: Future ist registriert
with client._result_lock:
assert len(client._pending_results) == 1
# Disconnect — muss den Future mit DDPNotConnected auflösen
client.disconnect()
# Der Task sollte jetzt DDPNotConnected werfen
with pytest.raises(DDPNotConnected) as exc_info:
await task
assert "connection closed" in str(exc_info.value).lower()
# _pending_results muss leer sein
with client._result_lock:
assert len(client._pending_results) == 0
asyncio.run(_run())
def test_reader_loop_exit_clears_pending_futures(self):
"""Simuliere reader-loop exit: _cancel_pending_results wird aufgerufen."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
# Registriere einen pending Future manuell
future = concurrent.futures.Future()
with client._result_lock:
client._pending_results["st9999999999_1"] = future
# Simuliere reader-loop exit (wie in _reader_loop nach while-Schleife)
client._cancel_pending_results()
# Future muss DDPNotConnected haben
assert future.done()
with pytest.raises(DDPNotConnected):
future.result()
# Store muss leer sein
with client._result_lock:
assert len(client._pending_results) == 0