Files
DeepTutor/tests/knowledge/test_manager_update_kb_status_failures.py
evan188199-tech 50a3ba4e4d fix(knowledge): surface swallowed KB status, progress and folder-sync failures (#1706)
* fix(knowledge): make update_kb_status write failures observable

The ready-transition metadata refresh swallowed every exception
(`except Exception: pass`), and a kb_config.json persist failure
surfaced only as an opaque raise inside fire-and-forget callers, so
a lost status update left the persisted KB state stale with no
diagnostic.

- Log a warning naming the KB when the best-effort ready-transition
  metadata refresh fails, instead of silently passing.
- Log an error with the KB name and status when persisting the
  config fails, then re-raise so callers still receive the exception
  (the write is authoritative, not best-effort).

Tests: a persist failure is logged and re-raised; a metadata refresh
failure is logged and does not propagate.

* fix(knowledge): make progress WS failures visible instead of silent

The websocket_progress endpoint swallowed five failure points with
`except Exception: pass`: timestamp parsing (x2), error-frame delivery,
socket close, and user-context reset. A corrupt progress snapshot or a
broken teardown path therefore vanished without a trace.

- Share a _progress_age_seconds helper for both freshness checks: narrow
  the catch to (TypeError, ValueError), keep the inactive/stale fallback,
  and log unparseable timestamps at warning level.
- Reuse the already-parsed snapshot age in the replay decision, so one
  corrupt timestamp warns once per connection instead of once per
  freshness check.
- Trace failed error-frame delivery and failed close at debug level
  (usually an already-disconnected client, not a fault).
- Log a failed reset_current_user at warning level: leaking the user
  context is a real fault, not a disconnect.

Tests: malformed timestamp degrades with a warning; cleanup failures are
logged and never propagate; normal disconnects stay silent.

* fix(knowledge): stop swallowing a failed reindex error-progress write

The reindex failure path wrapped its ProgressTracker ERROR update in
`except Exception: pass`, so when that write itself failed the rebuild's
failure alert disappeared and the KB progress view silently stayed stale.
Log a warning instead; the task-level error status remains authoritative.

* fix(knowledge): log folder sync state recording failures

update_folder_sync_state() swallowed per-file mtime recording errors
with 'except Exception: pass', so a file whose state could not be
recorded silently degraded the persisted sync state while last_sync
still advanced. Log the failure at WARNING and keep the un-recorded
fallback so the next scan re-syncs the file.

* test(codebuddy): make credential fixture expiry relative to now

test_load_credentials_parses_session wrote a hard-coded expiresAt of
1791055241000 (2026-10-03 15:40:41 UTC) and asserted is_expired() is
False. Once that instant passed the assertion flipped, so the test now
fails on every Python version for every branch.

Derive expiresAt / refreshExpiresAt from time.time() so the fixture
always describes a live session, and assert against the value written.

---------

Co-authored-by: XZH <cto@xzh.ai>
2026-10-07 20:22:32 +08:00

73 lines
2.5 KiB
Python

"""Failure-visibility tests for ``KnowledgeBaseManager.update_kb_status``.
A bare ``except Exception: pass`` around the ready-transition metadata
refresh meant that when refreshing embedding signatures or
``index_versions`` failed, the failure left no trace and the persisted KB
entry silently diverged from the on-disk index state that the UI renders.
These tests pin the contract that (a) a metadata refresh failure is logged
but stays best-effort, (b) a config-persist failure is logged at error level
and still reaches the caller as an exception, and (c) a successful update
persists the new status.
"""
from __future__ import annotations
import logging
from pathlib import Path
import pytest
from deeptutor.knowledge.manager import KnowledgeBaseManager
def test_successful_update_persists_status(tmp_path: Path) -> None:
manager = KnowledgeBaseManager(base_dir=str(tmp_path))
manager.update_kb_status(name="kb1", status="processing")
assert manager.get_kb_status("kb1")["status"] == "processing"
def test_persist_failure_is_logged_and_raised(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
manager = KnowledgeBaseManager(base_dir=str(tmp_path))
def _fail_save() -> None:
raise OSError("disk full")
monkeypatch.setattr(manager, "_save_config", _fail_save)
with caplog.at_level(logging.ERROR, logger="deeptutor.knowledge.manager"):
with pytest.raises(OSError, match="disk full"):
manager.update_kb_status(name="kb1", status="error")
assert any(
"kb1" in record.message and record.levelno == logging.ERROR for record in caplog.records
)
def test_ready_metadata_failure_is_logged(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
from deeptutor.knowledge import manager as manager_module
manager = KnowledgeBaseManager(base_dir=str(tmp_path))
(tmp_path / "kb1").mkdir()
(tmp_path / "kb1" / "version-1").mkdir()
def _boom(kb_dir: Path, provider: str) -> list[dict]:
raise RuntimeError("docstore exploded")
monkeypatch.setattr(manager_module, "inspect_kb_versions", _boom)
with caplog.at_level(logging.WARNING, logger="deeptutor.knowledge.manager"):
manager.update_kb_status(name="kb1", status="ready")
# The metadata refresh is best-effort: the status write itself still lands.
assert manager.get_kb_status("kb1")["status"] == "ready"
assert any(
"kb1" in record.message and record.levelno == logging.WARNING for record in caplog.records
)