diff --git a/api/models.py b/api/models.py index 485a1a42..c8fa14bb 100644 --- a/api/models.py +++ b/api/models.py @@ -200,6 +200,7 @@ def _session_dir_has_persisted_session_files() -> bool: def _rebuild_session_index_background(expected_session_dir: Path, expected_index_file: Path) -> None: global _SESSION_INDEX_REBUILD_THREAD, _SESSION_INDEX_REBUILD_THREAD_TARGET + current_thread = threading.current_thread() try: with _SESSION_INDEX_REBUILD_LOCK: if SESSION_DIR != expected_session_dir or SESSION_INDEX_FILE != expected_index_file: @@ -213,7 +214,7 @@ def _rebuild_session_index_background(expected_session_dir: Path, expected_index logger.debug("Background session-index rebuild failed", exc_info=True) finally: with _SESSION_INDEX_REBUILD_LOCK: - if _SESSION_INDEX_REBUILD_THREAD_TARGET == ( + if _SESSION_INDEX_REBUILD_THREAD is current_thread and _SESSION_INDEX_REBUILD_THREAD_TARGET == ( expected_session_dir, expected_index_file, ): diff --git a/tests/test_session_index.py b/tests/test_session_index.py index 9ef7acef..9530d8e2 100644 --- a/tests/test_session_index.py +++ b/tests/test_session_index.py @@ -1666,3 +1666,30 @@ def test_background_index_rebuild_skips_after_session_dir_switch(tmp_path, monke assert not new_index_file.exists() rows = _read_index(original_index_file) assert [row["session_id"] for row in rows] == ["late_switch_sid"] + + +def test_background_rebuild_old_thread_finally_preserves_new_same_target_owner(tmp_path, monkeypatch): + session_dir = tmp_path / "sessions" + session_dir.mkdir(exist_ok=True) + index_file = session_dir / "_index.json" + target = (session_dir, index_file) + + monkeypatch.setattr(models, "SESSION_DIR", session_dir) + monkeypatch.setattr(models, "SESSION_INDEX_FILE", index_file) + + old_thread = object() + new_thread = object() + monkeypatch.setattr(models, "_SESSION_INDEX_REBUILD_THREAD", old_thread) + monkeypatch.setattr(models, "_SESSION_INDEX_REBUILD_THREAD_TARGET", target) + monkeypatch.setattr(models.threading, "current_thread", lambda: old_thread) + + def _handoff_then_write(*args, **kwargs): + monkeypatch.setattr(models, "_SESSION_INDEX_REBUILD_THREAD", new_thread) + monkeypatch.setattr(models, "_SESSION_INDEX_REBUILD_THREAD_TARGET", target) + + monkeypatch.setattr(models, "_write_session_index", _handoff_then_write) + + models._rebuild_session_index_background(*target) + + assert models._SESSION_INDEX_REBUILD_THREAD is new_thread + assert models._SESSION_INDEX_REBUILD_THREAD_TARGET == target