Skip to content

The agent that grows with you

fix(kanban): reuse event stream database connection

Gille2ebb1cb41400
diff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.py
index ade9fa140e7..83fe126eb33 100644
--- a/plugins/kanban/dashboard/plugin_api.py
+++ b/plugins/kanban/dashboard/plugin_api.py
@@ -40,6 +40,7 @@ import json
import logging
import sqlite3
import time
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
from typing import Any, Optional
@@ -2900,6 +2901,21 @@ async def stream_events(ws: WebSocket):
await ws.close(code=http_status.WS_1008_POLICY_VIOLATION)
return
await ws.accept()
+
+ # Keep one connection alive for this socket after its first poll. SQLite
+ # connections are thread-affine by default, so every operation (including
+ # close) runs on the same dedicated worker. Besides preserving that safety
+ # contract, this avoids repeatedly creating and deleting the WAL/SHM
+ # sidecars while an idle dashboard polls for events.
+ event_conn: Optional[sqlite3.Connection] = None
+ event_executor: Optional[ThreadPoolExecutor] = None
+
+ def _close_event_conn() -> None:
+ nonlocal event_conn
+ if event_conn is not None:
+ event_conn.close()
+ event_conn = None
+
try:
since_raw = ws.query_params.get("since", "0")
try:
@@ -2918,32 +2934,31 @@ async def stream_events(ws: WebSocket):
ws_board = None
def _fetch_new(cursor_val: int) -> tuple[int, list[dict]]:
- conn = kanban_db.connect(board=ws_board)
- try:
- rows = conn.execute(
- "SELECT id, task_id, run_id, kind, payload, created_at "
- "FROM task_events WHERE id > ? ORDER BY id ASC LIMIT 200",
- (cursor_val,),
- ).fetchall()
- out: list[dict] = []
- new_cursor = cursor_val
- for r in rows:
- try:
- payload = json.loads(r["payload"]) if r["payload"] else None
- except Exception:
- payload = None
- out.append({
- "id": r["id"],
- "task_id": r["task_id"],
- "run_id": r["run_id"],
- "kind": r["kind"],
- "payload": payload,
- "created_at": r["created_at"],
- })
- new_cursor = r["id"]
- return new_cursor, out
- finally:
- conn.close()
+ nonlocal event_conn
+ if event_conn is None:
+ event_conn = kanban_db.connect(board=ws_board)
+ rows = event_conn.execute(
+ "SELECT id, task_id, run_id, kind, payload, created_at "
+ "FROM task_events WHERE id > ? ORDER BY id ASC LIMIT 200",
+ (cursor_val,),
+ ).fetchall()
+ out: list[dict] = []
+ new_cursor = cursor_val
+ for r in rows:
+ try:
+ payload = json.loads(r["payload"]) if r["payload"] else None
+ except Exception:
+ payload = None
+ out.append({
+ "id": r["id"],
+ "task_id": r["task_id"],
+ "run_id": r["run_id"],
+ "kind": r["kind"],
+ "payload": payload,
+ "created_at": r["created_at"],
+ })
+ new_cursor = r["id"]
+ return new_cursor, out
while True:
# Race receive() against the poll interval to detect client
@@ -2961,7 +2976,16 @@ async def stream_events(ws: WebSocket):
except asyncio.TimeoutError:
pass # no client message — poll the DB
- cursor, events = await asyncio.to_thread(_fetch_new, cursor)
+ if event_executor is None:
+ event_executor = ThreadPoolExecutor(
+ max_workers=1,
+ thread_name_prefix="kanban-events",
+ )
+ cursor, events = await asyncio.get_running_loop().run_in_executor(
+ event_executor,
+ _fetch_new,
+ cursor,
+ )
if events:
await ws.send_json({"events": events, "cursor": cursor})
except WebSocketDisconnect:
@@ -2979,3 +3003,14 @@ async def stream_events(ws: WebSocket):
await ws.close()
except Exception:
pass
+ finally:
+ if event_executor is not None:
+ try:
+ await asyncio.get_running_loop().run_in_executor(
+ event_executor,
+ _close_event_conn,
+ )
+ except Exception as exc:
+ log.warning("Kanban event stream connection cleanup failed: %s", exc)
+ finally:
+ event_executor.shutdown(wait=True, cancel_futures=True)
diff --git a/tests/plugins/test_kanban_ws_idle_disconnect.py b/tests/plugins/test_kanban_ws_idle_disconnect.py
index 1c7e107f857..8f53692cc1c 100644
--- a/tests/plugins/test_kanban_ws_idle_disconnect.py
+++ b/tests/plugins/test_kanban_ws_idle_disconnect.py
@@ -1,9 +1,13 @@
-"""Regression: kanban events WS must notice client disconnect on an idle board.
+"""Regressions for the kanban events WebSocket connection lifecycle.
Before the fix (#77833), ``stream_events`` only awaited ``asyncio.sleep``
between DB polls, so a disconnect was detected solely when ``send_json``
raised — which never happens on a board with no new events. Every closed
dashboard tab therefore left a zombie poll task querying SQLite forever.
+
+The event tail must also reuse one SQLite connection instead of opening and
+closing the last WAL connection on every idle poll. On Windows that repeatedly
+deletes and recreates ``kanban.db-wal`` and ``kanban.db-shm``.
"""
from __future__ import annotations
@@ -11,6 +15,7 @@ from __future__ import annotations
import asyncio
import importlib.util
import sys
+import threading
from pathlib import Path
import pytest
@@ -53,6 +58,57 @@ class _IdleDisconnectingWebSocket:
pass
+class _PollingWebSocket:
+ def __init__(self):
+ self.accepted = False
+ self.sent: list[dict] = []
+ self.query_params: dict[str, str] = {}
+ self._disconnect = asyncio.Event()
+
+ async def accept(self):
+ self.accepted = True
+
+ async def receive(self):
+ await self._disconnect.wait()
+ return {"type": "websocket.disconnect"}
+
+ async def send_json(self, payload):
+ self.sent.append(payload)
+
+ async def close(self, code=None):
+ pass
+
+
+class _TrackingConnection:
+ def __init__(self, rows_by_poll=None, on_execute=None):
+ self.rows_by_poll = list(rows_by_poll or [])
+ self.on_execute = on_execute
+ self.execute_calls = 0
+ self.close_calls = 0
+ self.thread_ids: list[int] = []
+ self._rows: list[dict] = []
+
+ def execute(self, sql, params):
+ self.execute_calls += 1
+ self.thread_ids.append(threading.get_ident())
+ if self.on_execute is not None:
+ self.on_execute()
+ poll_index = self.execute_calls - 1
+ self._rows = (
+ self.rows_by_poll[poll_index]
+ if poll_index < len(self.rows_by_poll)
+ else []
+ )
+ return self
+
+ def fetchall(self):
+ return self._rows
+
+ def close(self):
+ self.close_calls += 1
+ self.thread_ids.append(threading.get_ident())
+
+
@pytest.mark.asyncio
async def test_stream_events_exits_on_idle_disconnect(monkeypatch, tmp_path):
mod = _load_plugin_module()
@@ -68,3 +124,103 @@ async def test_stream_events_exits_on_idle_disconnect(monkeypatch, tmp_path):
assert ws.accepted
assert ws.receive_calls == 1
assert ws.sent == [] # returned before any poll, no zombie loop
+
+
+async def test_stream_events_reuses_connection_and_closes_after_disconnect(
+ monkeypatch,
+):
+ mod = _load_plugin_module()
+ monkeypatch.setattr(mod, "_ws_upgrade_authorized", lambda ws: True)
+
+ event_row = {
+ "id": 7,
+ "task_id": "task-1",
+ "run_id": None,
+ "kind": "updated",
+ "payload": '{"status": "running"}',
+ "created_at": 1234,
+ }
+ conn = _TrackingConnection(rows_by_poll=[[], [event_row]])
+ connect_threads: list[int] = []
+
+ def _connect(*, board=None):
+ connect_threads.append(threading.get_ident())
+ return conn
+
+ monkeypatch.setattr(mod.kanban_db, "connect", _connect)
+
+ wait_calls = 0
+
+ async def _poll_twice_then_disconnect(awaitable, timeout):
+ nonlocal wait_calls
+ wait_calls += 1
+ awaitable.close()
+ if wait_calls <= 2:
+ raise asyncio.TimeoutError
+ return {"type": "websocket.disconnect"}
+
+ monkeypatch.setattr(mod.asyncio, "wait_for", _poll_twice_then_disconnect)
+ ws = _PollingWebSocket()
+
+ await mod.stream_events(ws)
+
+ assert ws.accepted
+ assert len(connect_threads) == 1
+ assert conn.execute_calls == 2
+ assert conn.close_calls == 1
+ assert len(set(connect_threads + conn.thread_ids)) == 1
+ assert ws.sent == [{
+ "events": [{
+ "id": 7,
+ "task_id": "task-1",
+ "run_id": None,
+ "kind": "updated",
+ "payload": {"status": "running"},
+ "created_at": 1234,
+ }],
+ "cursor": 7,
+ }]
+
+
+async def test_stream_events_closes_connection_when_cancelled(monkeypatch):
+ mod = _load_plugin_module()
+ monkeypatch.setattr(mod, "_ws_upgrade_authorized", lambda ws: True)
+
+ loop = asyncio.get_running_loop()
+ first_fetch_done = asyncio.Event()
+ conn = _TrackingConnection(
+ on_execute=lambda: loop.call_soon_threadsafe(first_fetch_done.set),
+ )
+ connect_threads: list[int] = []
+
+ def _connect(*, board=None):
+ connect_threads.append(threading.get_ident())
+ return conn
+
+ monkeypatch.setattr(mod.kanban_db, "connect", _connect)
+
+ real_wait_for = asyncio.wait_for
+ wait_calls = 0
+
+ async def _poll_once_then_wait(awaitable, timeout):
+ nonlocal wait_calls
+ wait_calls += 1
+ if wait_calls == 1:
+ awaitable.close()
+ raise asyncio.TimeoutError
+ return await awaitable
+
+ monkeypatch.setattr(mod.asyncio, "wait_for", _poll_once_then_wait)
+ ws = _PollingWebSocket()
+ task = asyncio.create_task(mod.stream_events(ws))
+
+ await real_wait_for(first_fetch_done.wait(), timeout=5)
+ task.cancel()
+ await task
+
+ assert len(connect_threads) == 1
+ assert conn.execute_calls == 1
+ assert conn.close_calls == 1
+ assert len(set(connect_threads + conn.thread_ids)) == 1