fix: 给 soffice 加超时(120s)机制、worker 自动回收超时 running 任务,避免任务挂死阻塞队列

This commit is contained in:
sophie committed 2026-05-29 11:37:02 +08:00
1 parent 1d72018eb7
commit 0eb577df1a
11 files changed
+379 -88

No files matched your search

+2
View File
@@ -57,6 +57,8 @@ class Config:
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower()
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
@@ -1,13 +1,74 @@
"""
backend/app/services/knowledge_cleaning/queue_service.py
文件用途:知识库任务调度最小实现
补充能力(2026-05):
- recover_stale_running_jobs:回收超时仍处于 running 的后台任务,防止单条卡死阻塞 worker;
- process_next_kb_job 在取 queued 任务前会先执行一次超时回收。
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta
from flask import current_app
from app import db
from app.models import KbJob
from app.models import KbDocumentVersion, KbJob
logger = logging.getLogger('kb-worker')
def recover_stale_running_jobs() -> tuple[int, str]:
"""
回收长时间停留在 running 的任务,避免单条卡死阻塞 worker 队列。
阈值读取 KB_JOB_RUNNING_TIMEOUT_SECONDS(默认 300 秒),
应大于单次清洗的预期耗时(含多次 soffice 转换)。
"""
timeout_sec = float(current_app.config.get('KB_JOB_RUNNING_TIMEOUT_SECONDS', 300))
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
stale_jobs = (
db.session.query(KbJob)
.filter(
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
KbJob.status == 'running',
KbJob.started_at.isnot(None),
KbJob.started_at < cutoff,
)
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
.all()
)
if not stale_jobs:
return 0, 'no_stale_jobs'
now = datetime.utcnow()
message = f'任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
for job in stale_jobs:
job.status = 'failed'
job.error_message = message
job.message = message
job.finished_at = now
job.progress = 100
if not job.document_version_id:
continue
version = db.session.get(KbDocumentVersion, job.document_version_id)
if not version:
continue
if job.job_type == 'clean' and version.status in ('processing', 'uploaded'):
version.status = 'failed'
version.error_message = message
elif job.job_type == 'sync_dify' and version.status == 'syncing':
version.status = 'ready'
version.error_message = message
db.session.commit()
logger.warning('recovered %s stale running kb job(s)', len(stale_jobs))
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
@@ -46,6 +107,9 @@ def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
def process_next_kb_job() -> tuple[bool, str]:
# 先回收历史卡死的 running 任务,再领取下一条 queued 任务
recover_stale_running_jobs()
job = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
@@ -325,6 +325,12 @@ def run_path_upload_job(job_id: int) -> tuple[bool, str]:
return True, 'ok'
def _is_clean_timeout_error(exc: Exception) -> bool:
"""判断清洗异常是否由 soffice / 子进程超时引起(与 soffice_util 错误文案对齐)。"""
message = str(exc).lower()
return 'timed out' in message or 'timeout' in message
def run_clean_job(job_id: int) -> tuple[bool, str]:
"""
第一版最小清洗任务执行器。
@@ -378,6 +384,18 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
result = build_clean_result(source_path, target_dir)
job_message = '真实清洗结果已生成'
except Exception as exc:
# soffice 超时等不可恢复错误:直接失败,避免回退占位结果掩盖问题
if _is_clean_timeout_error(exc):
job.status = 'failed'
job.progress = 100
job.message = '清洗超时'
job.error_message = str(exc)
job.finished_at = _utc_now()
version.status = 'failed'
version.error_message = str(exc)
db.session.commit()
return False, 'timeout'
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
preview_path.write_text(
'\n'.join([