from __future__ import annotations import json import uuid from datetime import timedelta from app.config import get_settings from app.database import SessionLocal from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User from app.services.watchdog_service import ( local_convert_health_summary, local_sync_health_summary, read_watchdog_snapshot, recover_stale_converts, recover_stale_syncs, ) from app.time_utils import utc_now def _seed_stale_sync_version(): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin_id = admin.id group = Group(name=f"watchdog-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title="watchdog-policy", created_by_id=admin_id, is_deleted=False) db.add(document) db.commit() db.refresh(document) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="watchdog.docx", source_ext=".docx", source_path="/tmp/watchdog.docx", source_sha256=uuid.uuid4().hex, file_size=2048, uploader_id=admin_id, convert_status="success", sync_status="syncing", ) db.add(version) db.commit() db.refresh(version) old_time = utc_now() - timedelta(minutes=20) job = Job( id=str(uuid.uuid4()), job_type="sync", status="running", group_id=group.id, document_id=document.id, version_id=version.id, created_by_id=admin_id, created_at=old_time, started_at=old_time, message="Syncing document to Dify", ) db.add(job) db.commit() record = DifySyncRecord( version_id=version.id, dataset_id="dataset-watchdog", remote_document_id="remote-watchdog", batch="batch-watchdog", status="syncing", created_at=old_time, updated_at=old_time, ) db.add(record) db.commit() return version.id, job.id, record.id finally: db.close() def _seed_stale_convert_version(*, queue_job_id: str | None = "rq-convert-stale", status: str = "queued"): db = SessionLocal() try: admin = db.query(User).filter(User.username == "admin").first() assert admin is not None admin_id = admin.id group = Group(name=f"convert-watchdog-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) db.add(group) db.commit() db.refresh(group) document = Document(group_id=group.id, title="convert-watchdog", created_by_id=admin_id, is_deleted=False) db.add(document) db.commit() db.refresh(document) old_time = utc_now() - timedelta(minutes=20) version = DocumentVersion( document_id=document.id, version_no=1, is_current=True, source_filename="convert-watchdog.docx", source_ext=".docx", source_path="/tmp/convert-watchdog.docx", source_sha256=uuid.uuid4().hex, file_size=1024, uploader_id=admin_id, convert_status=status, sync_status="unsynced", uploaded_at=old_time, ) db.add(version) db.commit() db.refresh(version) job = Job( id=str(uuid.uuid4()), job_type="convert", status=status, queue_job_id=queue_job_id, group_id=group.id, document_id=document.id, version_id=version.id, created_by_id=admin_id, created_at=old_time, started_at=old_time if status == "running" else None, message="Converting source document", ) db.add(job) db.commit() return version.id, job.id finally: db.close() def test_recover_stale_syncs_marks_versions_jobs_and_records_failed(db_session): version_id, job_id, record_id = _seed_stale_sync_version() db = SessionLocal() try: result = recover_stale_syncs(db, timeout_seconds=900) assert result["recovered_versions"] == 1 assert result["recovered_jobs"] == 1 assert result["recovered_records"] == 1 finally: db.close() db = SessionLocal() try: version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() job = db.query(Job).filter(Job.id == job_id).first() record = db.query(DifySyncRecord).filter(DifySyncRecord.id == record_id).first() assert version is not None assert job is not None assert record is not None assert version.sync_status == "sync_failed" assert job.status == "failed" assert "watchdog timeout" in (job.error or "") assert record.status == "sync_failed" assert "watchdog timeout" in (record.error or "") finally: db.close() def test_local_sync_health_summary_reports_stale_candidates(db_session): _seed_stale_sync_version() db = SessionLocal() try: payload = local_sync_health_summary(db, timeout_seconds=900) assert payload["syncing_versions"] == 1 assert payload["active_sync_jobs"] == 1 assert payload["stale_candidates"] == 1 assert payload["stale_versions"][0]["remote_document_id"] == "remote-watchdog" finally: db.close() def test_recover_stale_converts_marks_versions_and_jobs_failed_when_queue_job_is_missing(db_session, monkeypatch): version_id, job_id = _seed_stale_convert_version() monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) db = SessionLocal() try: result = recover_stale_converts(db, timeout_seconds=900, orphan_grace_seconds=120) assert result["recovered_versions"] == 1 assert result["recovered_jobs"] == 1 finally: db.close() db = SessionLocal() try: version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() job = db.query(Job).filter(Job.id == job_id).first() assert version is not None assert job is not None assert version.convert_status == "failed" assert "watchdog" in (version.failed_reason or "") assert job.status == "failed" assert "missing from Redis queue" in (job.error or "") finally: db.close() def test_local_convert_health_summary_reports_stale_candidates(db_session, monkeypatch): _seed_stale_convert_version() monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) db = SessionLocal() try: payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120) assert payload["pending_versions"] == 1 assert payload["active_convert_jobs"] == 1 assert payload["stale_candidates"] == 1 assert payload["stale_versions"][0]["reason"].startswith("Convert job is missing") finally: db.close() def test_local_convert_health_summary_keeps_live_queue_jobs_out_of_stale_candidates(db_session, monkeypatch): _seed_stale_convert_version(queue_job_id="rq-convert-live") monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: {"rq-convert-live"}) db = SessionLocal() try: payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120) assert payload["pending_versions"] == 1 assert payload["stale_candidates"] == 0 finally: db.close() def test_read_watchdog_snapshot_reads_json_from_data_root(db_session): path = get_settings().data_root / "watchdog" / "dify-health.json" path.parent.mkdir(parents=True, exist_ok=True) payload = { "status": "ok", "worker": {"concurrency": 2}, "queue_lengths": {"priority_dataset": 0}, } path.write_text(json.dumps(payload), encoding="utf-8") loaded = read_watchdog_snapshot() assert loaded is not None assert loaded["available"] is True assert loaded["worker"]["concurrency"] == 2