Files
syops/backend/app/services/watchdog_service.py
2026-04-27 17:03:56 +08:00

496 lines
18 KiB
Python

from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import timedelta, timezone
from pathlib import Path
from typing import Any
from redis import Redis
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.models import DifySyncRecord, DocumentVersion, Job
from app.time_utils import utc_now
SNAPSHOT_RELATIVE_PATH = Path("watchdog/dify-health.json")
@dataclass
class StaleSyncCandidate:
version: DocumentVersion
active_job: Job | None
sync_record: DifySyncRecord | None
reason: str
age_seconds: int
@dataclass
class StaleConvertCandidate:
version: DocumentVersion
active_job: Job | None
reason: str
age_seconds: int
def _as_aware_utc(value):
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _live_queue_job_ids(settings: Settings | None = None) -> set[str] | None:
resolved = settings or get_settings()
try:
redis = Redis.from_url(resolved.redis_url)
raw_ids = redis.lrange(f"rq:queue:{resolved.rq_queue_name}", 0, -1)
return {item.decode("utf-8") if isinstance(item, bytes) else str(item) for item in raw_ids}
except Exception:
return None
def watchdog_snapshot_path(settings: Settings | None = None) -> Path:
resolved = settings or get_settings()
path = resolved.data_root / SNAPSHOT_RELATIVE_PATH
path.parent.mkdir(parents=True, exist_ok=True)
return path
def read_watchdog_snapshot(settings: Settings | None = None) -> dict[str, Any] | None:
path = watchdog_snapshot_path(settings)
if not path.exists():
return None
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
return {
"available": False,
"status": "invalid_snapshot",
"path": str(path),
"error": str(exc),
}
if isinstance(payload, dict):
payload.setdefault("available", True)
payload.setdefault("path", str(path))
return payload
return {
"available": False,
"status": "invalid_snapshot",
"path": str(path),
"error": "Snapshot must be a JSON object.",
}
def local_sync_health_summary(db: Session, *, timeout_seconds: int) -> dict[str, Any]:
stale_candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds)
recent_failures = (
db.query(Job)
.filter(Job.job_type == "sync", Job.status == "failed")
.order_by(Job.created_at.desc())
.limit(5)
.all()
)
active_jobs = (
db.query(Job)
.filter(Job.job_type == "sync", Job.status.in_(("queued", "running")))
.order_by(Job.created_at.desc())
.all()
)
syncing_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").count()
sync_failed_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "sync_failed").count()
return {
"timeout_seconds": timeout_seconds,
"syncing_versions": syncing_versions,
"sync_failed_versions": sync_failed_versions,
"active_sync_jobs": len(active_jobs),
"stale_candidates": len(stale_candidates),
"active_jobs": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"status": job.status,
"created_at": job.created_at.isoformat() if job.created_at else None,
"started_at": job.started_at.isoformat() if job.started_at else None,
"message": job.message,
}
for job in active_jobs[:10]
],
"recent_failures": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"finished_at": job.finished_at.isoformat() if job.finished_at else None,
"error": job.error,
}
for job in recent_failures
],
"stale_versions": [
{
"document_id": candidate.version.document_id,
"version_id": candidate.version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"sync_record_id": candidate.sync_record.id if candidate.sync_record else None,
"remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
for candidate in stale_candidates[:20]
],
}
def local_convert_health_summary(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
settings: Settings | None = None,
) -> dict[str, Any]:
stale_candidates = find_stale_convert_candidates(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
settings=settings,
)
recent_failures = (
db.query(Job)
.filter(Job.job_type == "convert", Job.status == "failed")
.order_by(Job.created_at.desc())
.limit(5)
.all()
)
active_jobs = (
db.query(Job)
.filter(Job.job_type == "convert", Job.status.in_(("queued", "running")))
.order_by(Job.created_at.desc())
.all()
)
pending_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).count()
failed_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status == "failed").count()
return {
"timeout_seconds": timeout_seconds,
"orphan_grace_seconds": orphan_grace_seconds,
"pending_versions": pending_versions,
"failed_versions": failed_versions,
"active_convert_jobs": len(active_jobs),
"stale_candidates": len(stale_candidates),
"active_jobs": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"status": job.status,
"queue_job_id": job.queue_job_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"started_at": job.started_at.isoformat() if job.started_at else None,
"message": job.message,
}
for job in active_jobs[:10]
],
"recent_failures": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"finished_at": job.finished_at.isoformat() if job.finished_at else None,
"error": job.error,
}
for job in recent_failures
],
"stale_versions": [
{
"document_id": candidate.version.document_id,
"version_id": candidate.version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
for candidate in stale_candidates[:20]
],
}
def find_stale_sync_candidates(db: Session, *, timeout_seconds: int) -> list[StaleSyncCandidate]:
cutoff = utc_now() - timedelta(seconds=timeout_seconds)
versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").all()
candidates: list[StaleSyncCandidate] = []
for version in versions:
active_job = (
db.query(Job)
.filter(
Job.version_id == version.id,
Job.job_type == "sync",
Job.status.in_(("queued", "running")),
)
.order_by(Job.created_at.desc())
.first()
)
sync_record = (
db.query(DifySyncRecord)
.filter(
DifySyncRecord.version_id == version.id,
DifySyncRecord.status == "syncing",
)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
.first()
)
candidate: StaleSyncCandidate | None = None
active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None
sync_record_updated_at = _as_aware_utc(sync_record.updated_at) if sync_record else None
sync_record_created_at = _as_aware_utc(sync_record.created_at) if sync_record else None
uploaded_at = _as_aware_utc(version.uploaded_at)
if active_job and active_job_created_at and active_job_created_at <= cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=active_job,
sync_record=sync_record,
reason="Sync job exceeded watchdog timeout.",
age_seconds=age_seconds,
)
elif sync_record and sync_record_updated_at and sync_record_updated_at <= cutoff:
age_seconds = int((utc_now() - sync_record_updated_at).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=active_job,
sync_record=sync_record,
reason="Sync record exceeded watchdog timeout without completion.",
age_seconds=age_seconds,
)
elif not active_job:
baseline = None
if sync_record_created_at:
baseline = sync_record_created_at
elif uploaded_at:
baseline = uploaded_at
if baseline and baseline <= cutoff:
age_seconds = int((utc_now() - baseline).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=None,
sync_record=sync_record,
reason="Sync status has no active job and exceeded watchdog timeout.",
age_seconds=age_seconds,
)
if candidate is not None:
candidates.append(candidate)
return candidates
def find_stale_convert_candidates(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
settings: Settings | None = None,
) -> list[StaleConvertCandidate]:
cutoff = utc_now() - timedelta(seconds=timeout_seconds)
orphan_cutoff = utc_now() - timedelta(seconds=orphan_grace_seconds)
live_queue_job_ids = _live_queue_job_ids(settings)
versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).all()
candidates: list[StaleConvertCandidate] = []
for version in versions:
active_job = (
db.query(Job)
.filter(
Job.version_id == version.id,
Job.job_type == "convert",
Job.status.in_(("queued", "running")),
)
.order_by(Job.created_at.desc())
.first()
)
candidate: StaleConvertCandidate | None = None
active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None
active_job_started_at = _as_aware_utc(active_job.started_at) if active_job else None
uploaded_at = _as_aware_utc(version.uploaded_at)
queue_job_present = (
bool(active_job and active_job.queue_job_id)
and live_queue_job_ids is not None
and active_job.queue_job_id in live_queue_job_ids
)
if active_job and active_job.status == "running":
baseline = active_job_started_at or active_job_created_at
if baseline and baseline <= cutoff:
age_seconds = int((utc_now() - baseline).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job exceeded watchdog timeout while running.",
age_seconds=age_seconds,
)
elif active_job and active_job.status == "queued":
if active_job.queue_job_id and live_queue_job_ids is not None and not queue_job_present and active_job_created_at and active_job_created_at <= orphan_cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job is missing from Redis queue beyond watchdog grace period.",
age_seconds=age_seconds,
)
elif not active_job.queue_job_id and active_job_created_at and active_job_created_at <= orphan_cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job has no queue id and exceeded watchdog grace period.",
age_seconds=age_seconds,
)
elif not active_job and uploaded_at and uploaded_at <= orphan_cutoff:
age_seconds = int((utc_now() - uploaded_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=None,
reason="Convert status has no active job and exceeded watchdog grace period.",
age_seconds=age_seconds,
)
if candidate is not None:
candidates.append(candidate)
return candidates
def recover_stale_syncs(
db: Session,
*,
timeout_seconds: int,
reason_prefix: str = "Marked stale by watchdog after timeout.",
) -> dict[str, Any]:
candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds)
now = utc_now()
recovered_versions = 0
recovered_jobs = 0
recovered_records = 0
documents: list[dict[str, Any]] = []
seen_versions: set[int] = set()
for candidate in candidates:
version = candidate.version
if version.id in seen_versions:
continue
seen_versions.add(version.id)
if version.sync_status == "syncing":
version.sync_status = "sync_failed"
recovered_versions += 1
if candidate.active_job and candidate.active_job.status in {"queued", "running"}:
candidate.active_job.status = "failed"
candidate.active_job.message = "Dify sync failed"
candidate.active_job.error = f"{reason_prefix} {candidate.reason}"
candidate.active_job.finished_at = now
recovered_jobs += 1
syncing_records = db.query(DifySyncRecord).filter(
DifySyncRecord.version_id == version.id,
DifySyncRecord.status == "syncing",
)
for record in syncing_records:
record.status = "sync_failed"
record.error = record.error or f"{reason_prefix} {candidate.reason}"
recovered_records += 1
documents.append(
{
"document_id": version.document_id,
"version_id": version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"sync_record_id": candidate.sync_record.id if candidate.sync_record else None,
"remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
)
if recovered_versions or recovered_jobs or recovered_records:
db.commit()
return {
"timeout_seconds": timeout_seconds,
"recovered_versions": recovered_versions,
"recovered_jobs": recovered_jobs,
"recovered_records": recovered_records,
"documents": documents,
}
def recover_stale_converts(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
reason_prefix: str = "Marked convert as failed by watchdog.",
settings: Settings | None = None,
) -> dict[str, Any]:
candidates = find_stale_convert_candidates(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
settings=settings,
)
now = utc_now()
recovered_versions = 0
recovered_jobs = 0
documents: list[dict[str, Any]] = []
seen_versions: set[int] = set()
for candidate in candidates:
version = candidate.version
if version.id in seen_versions:
continue
seen_versions.add(version.id)
if version.convert_status in {"queued", "running"}:
version.convert_status = "failed"
version.failed_reason = f"{reason_prefix} {candidate.reason}"
recovered_versions += 1
if candidate.active_job and candidate.active_job.status in {"queued", "running"}:
candidate.active_job.status = "failed"
candidate.active_job.message = "Conversion failed"
candidate.active_job.error = f"{reason_prefix} {candidate.reason}"
candidate.active_job.finished_at = now
recovered_jobs += 1
documents.append(
{
"document_id": version.document_id,
"version_id": version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
)
if recovered_versions or recovered_jobs:
db.commit()
return {
"timeout_seconds": timeout_seconds,
"orphan_grace_seconds": orphan_grace_seconds,
"recovered_versions": recovered_versions,
"recovered_jobs": recovered_jobs,
"documents": documents,
}