diff --git a/backend/app/config.py b/backend/app/config.py index e4c36917..e4bde29b 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -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, diff --git a/backend/app/services/knowledge_cleaning/queue_service.py b/backend/app/services/knowledge_cleaning/queue_service.py index b08617ea..8e3f64e8 100644 --- a/backend/app/services/knowledge_cleaning/queue_service.py +++ b/backend/app/services/knowledge_cleaning/queue_service.py @@ -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') diff --git a/backend/app/services/knowledge_cleaning/tasks.py b/backend/app/services/knowledge_cleaning/tasks.py index 650f560d..4708f821 100644 --- a/backend/app/services/knowledge_cleaning/tasks.py +++ b/backend/app/services/knowledge_cleaning/tasks.py @@ -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([ diff --git a/backend/edkb_system/skills/doc_to_pdf.py b/backend/edkb_system/skills/doc_to_pdf.py index 2b94c433..1c3ced67 100644 --- a/backend/edkb_system/skills/doc_to_pdf.py +++ b/backend/edkb_system/skills/doc_to_pdf.py @@ -1,47 +1,35 @@ +""" +backend/edkb_system/skills/doc_to_pdf.py +文件用途:将 Word 文档转换为 PDF,供后续 PDF 解析链路使用 + +说明: +- Windows 优先走 Word COM(word_bridge); +- Linux/容器环境走 LibreOffice,转换超时由 soffice_util 统一控制。 +""" from __future__ import annotations import os -import subprocess from pathlib import Path from edkb_system.contracts import Context +from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice from edkb_system.skills.word_bridge import convert_with_word -def _find_soffice() -> str | None: - candidates = [ - os.environ.get("EDKB_SOFFICE"), - r"C:\Program Files\LibreOffice\program\soffice.exe", - r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", - "soffice", - ] - for c in candidates: - if not c: - continue - if c == "soffice": - return c - if Path(c).exists(): - return c - return None - - def _convert_with_word(path: Path, out_dir: Path) -> Path: output = out_dir / f"{path.stem}.pdf" return convert_with_word(path.resolve(), output.resolve(), 17) def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path: + """通过 soffice 转 PDF;超时抛出 RuntimeError。""" output = out_dir / f"{path.stem}.pdf" - cmd = [ + proc = convert_with_soffice( soffice, - "--headless", - "--convert-to", - "pdf", - str(path), - "--outdir", - str(out_dir), - ] - proc = subprocess.run(cmd, capture_output=True, text=True) + convert_to="pdf", + source_path=path, + out_dir=out_dir, + ) if proc.returncode != 0: stderr = (proc.stderr or "").strip() or "no stderr" raise RuntimeError( @@ -66,7 +54,7 @@ def run(input_data: dict, context: Context) -> dict: except Exception as exc: errors.append(f"word: {exc}") - soffice = _find_soffice() + soffice = find_soffice() if soffice: try: pdf = _convert_with_soffice(file_path, out_dir, soffice) diff --git a/backend/edkb_system/skills/loader_docx.py b/backend/edkb_system/skills/loader_docx.py index d9f59133..96c6b0f9 100644 --- a/backend/edkb_system/skills/loader_docx.py +++ b/backend/edkb_system/skills/loader_docx.py @@ -14,6 +14,7 @@ import xml.etree.ElementTree as ET from pathlib import Path from edkb_system.contracts import Block, Context +from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates from edkb_system.skills.word_bridge import convert_with_word @@ -1583,6 +1584,11 @@ def _convert_doc_with_word(path: Path, out_dir: Path) -> Path: def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path: + """ + 将 .doc 转为 .docx。 + + Windows 优先 Word COM;Linux/容器走 soffice_util(带 EDKB_SOFFICE_TIMEOUT_SEC 超时)。 + """ out_dir.mkdir(parents=True, exist_ok=True) output = out_dir / f"{path.stem}.docx" force_reconvert = str( @@ -1606,29 +1612,24 @@ def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path: except Exception as exc: errors.append(f"Word COM conversion failed: {exc}") - soffice_candidates = [ - os.environ.get("EDKB_SOFFICE"), - r"C:\Program Files\LibreOffice\program\soffice.exe", - r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", - "soffice", - ] - for soffice in soffice_candidates: + # 非 Windows:依次尝试 soffice 候选路径,单次转换受 soffice_util 超时保护 + soffice_candidates_list = soffice_candidates() + for soffice in soffice_candidates_list: if not soffice: continue - cmd = [ - soffice, - "--headless", - "--convert-to", - "docx", - str(path), - "--outdir", - str(out_dir), - ] try: - proc = subprocess.run(cmd, capture_output=True, text=True) + proc = convert_with_soffice( + soffice, + convert_to="docx", + source_path=path, + out_dir=out_dir, + ) except FileNotFoundError: errors.append(f"soffice not found: {soffice}") continue + except RuntimeError as exc: + errors.append(str(exc)) + continue if proc.returncode == 0 and output.exists(): return output diff --git a/backend/edkb_system/skills/loader_excel.py b/backend/edkb_system/skills/loader_excel.py index 588c1427..e060169c 100644 --- a/backend/edkb_system/skills/loader_excel.py +++ b/backend/edkb_system/skills/loader_excel.py @@ -1,44 +1,41 @@ +""" +backend/edkb_system/skills/loader_excel.py +文件用途:加载 Excel 表格为结构化数据 + +说明: +- .xls 旧格式先经 soffice_util 转为 .xlsx,再走 openpyxl 解析。 +""" from __future__ import annotations -import os -import subprocess from pathlib import Path from openpyxl import load_workbook from edkb_system.contracts import Context - - -def _soffice_candidates() -> list[str]: - return [ - os.environ.get("EDKB_SOFFICE", "").strip(), - r"C:\Program Files\LibreOffice\program\soffice.exe", - r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", - "soffice", - ] +from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path: + """将 .xls 转为 .xlsx;soffice 调用带超时,见 EDKB_SOFFICE_TIMEOUT_SEC。""" out_dir.mkdir(parents=True, exist_ok=True) output = out_dir / f"{path.stem}.xlsx" errors: list[str] = [] - for soffice in _soffice_candidates(): + for soffice in soffice_candidates(): if not soffice: continue - cmd = [ - soffice, - "--headless", - "--convert-to", - "xlsx", - str(path), - "--outdir", - str(out_dir), - ] try: - proc = subprocess.run(cmd, capture_output=True, text=True) + proc = convert_with_soffice( + soffice, + convert_to="xlsx", + source_path=path, + out_dir=out_dir, + ) except FileNotFoundError: errors.append(f"soffice not found: {soffice}") continue + except RuntimeError as exc: + errors.append(str(exc)) + continue if proc.returncode == 0 and output.exists(): return output stderr = (proc.stderr or "").strip() diff --git a/backend/edkb_system/skills/loader_pptx.py b/backend/edkb_system/skills/loader_pptx.py index c9566696..edbb5549 100644 --- a/backend/edkb_system/skills/loader_pptx.py +++ b/backend/edkb_system/skills/loader_pptx.py @@ -4,10 +4,10 @@ import base64 import hashlib import io import re -import subprocess from pathlib import Path from edkb_system.contracts import Block, Context +from edkb_system.skills.soffice_util import convert_with_soffice def _to_data_uri(blob: bytes, content_type: str) -> str: @@ -15,17 +15,14 @@ def _to_data_uri(blob: bytes, content_type: str) -> str: def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path: + """将 .ppt 转为 .pptx;soffice 超时由 soffice_util 控制。""" out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ + proc = convert_with_soffice( "soffice", - "--headless", - "--convert-to", - "pptx", - str(path), - "--outdir", - str(out_dir), - ] - proc = subprocess.run(cmd, capture_output=True, text=True) + convert_to="pptx", + source_path=path, + out_dir=out_dir, + ) if proc.returncode != 0: raise RuntimeError("Install LibreOffice to convert .ppt to .pptx") output = out_dir / f"{path.stem}.pptx" @@ -35,20 +32,19 @@ def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path: def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None: + """将演示文稿转为 PDF;失败或超时返回 None,由上层选择其它解析路径。""" out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - "soffice", - "--headless", - "--convert-to", - "pdf", - str(path), - "--outdir", - str(out_dir), - ] try: - proc = subprocess.run(cmd, capture_output=True, text=True) + proc = convert_with_soffice( + "soffice", + convert_to="pdf", + source_path=path, + out_dir=out_dir, + ) except FileNotFoundError: return None + except RuntimeError: + return None if proc.returncode != 0: return None output = out_dir / f"{path.stem}.pdf" diff --git a/backend/edkb_system/skills/soffice_util.py b/backend/edkb_system/skills/soffice_util.py new file mode 100644 index 00000000..c1f11725 --- /dev/null +++ b/backend/edkb_system/skills/soffice_util.py @@ -0,0 +1,92 @@ +""" +backend/edkb_system/skills/soffice_util.py +文件用途:LibreOffice(soffice)转换统一封装 + +说明: +- 为 loader_docx / doc_to_pdf / loader_excel / loader_pptx 等技能提供带超时的 soffice 调用; +- 避免单个 Office 文档转换卡死导致 kb-worker 长期阻塞; +- 超时阈值通过环境变量 EDKB_SOFFICE_TIMEOUT_SEC 配置(默认 120 秒)。 +""" +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + + +def soffice_timeout_sec() -> int: + """读取 soffice 子进程超时秒数,最小 10 秒。""" + raw = str(os.environ.get("EDKB_SOFFICE_TIMEOUT_SEC", "120")).strip() + try: + value = int(raw) + except ValueError: + value = 120 + return max(value, 10) + + +def soffice_candidates() -> list[str]: + """返回 soffice 可执行文件候选路径(环境变量优先,其次 Windows 默认安装路径)。""" + return [ + os.environ.get("EDKB_SOFFICE", "").strip(), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + + +def find_soffice() -> str | None: + """返回第一个可用的 soffice 路径;PATH 中的 `soffice` 不做存在性探测。""" + for candidate in soffice_candidates(): + if not candidate: + continue + if candidate == "soffice": + return candidate + if Path(candidate).exists(): + return candidate + return None + + +def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]: + """ + 执行 soffice 命令并强制超时。 + + 超时时抛出 RuntimeError,供上层清洗任务识别为失败而非无限等待。 + """ + timeout = soffice_timeout_sec() + try: + return subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + label = Path(cmd[-2]).name if len(cmd) >= 2 else "soffice" + raise RuntimeError( + f"soffice timed out after {timeout}s: {label}" + ) from exc + + +def convert_with_soffice( + soffice: str, + *, + convert_to: str, + source_path: Path, + out_dir: Path, +) -> subprocess.CompletedProcess[str]: + """ + 以 headless 模式调用 soffice 做格式转换。 + + :param convert_to: 目标格式,如 docx / pdf / xlsx / pptx + """ + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + soffice, + "--headless", + "--convert-to", + convert_to, + str(source_path), + "--outdir", + str(out_dir), + ] + return run_soffice(cmd) diff --git a/backend/tests/test_kb_queue_recovery.py b/backend/tests/test_kb_queue_recovery.py new file mode 100644 index 00000000..b643b17f --- /dev/null +++ b/backend/tests/test_kb_queue_recovery.py @@ -0,0 +1,123 @@ +""" +backend/tests/test_kb_queue_recovery.py +文件用途:知识库任务队列超时回收与 soffice 超时行为测试 + +覆盖场景: +- recover_stale_running_jobs:回收超时仍处于 running 的 clean 任务; +- _is_clean_timeout_error:识别 soffice / 清洗超时错误; +- soffice_util.run_soffice:子进程超时后抛出 RuntimeError。 +""" +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob, User +from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs +from app.services.knowledge_cleaning.tasks import _is_clean_timeout_error +from edkb_system.skills import soffice_util + + +def _configure_app(app, tmp_path): + app.config.update( + SECRET_KEY='test-secret-key-with-sufficient-length-123456', + KB_STORAGE_ROOT=str(tmp_path / 'kb-storage'), + KB_JOB_RUNNING_TIMEOUT_SECONDS=60, + ) + + +def _seed_clean_job(*, stale: bool) -> KbJob: + user = User(username='kb-queue-user', email='kb-queue@example.com', role='admin', status='active') + user.set_password('password123') + db.session.add(user) + db.session.flush() + + group = KbGroup(name='queue-test-group', created_by_id=user.id) + db.session.add(group) + db.session.flush() + + document = KbDocument( + group_id=group.id, + title='queue-test-doc.doc', + status='uploaded', + source_type='upload', + created_by_id=user.id, + ) + db.session.add(document) + db.session.flush() + + version = KbDocumentVersion( + document_id=document.id, + version_no=1, + status='processing', + is_current=True, + source_file_name='queue-test-doc.doc', + source_file_path='/tmp/queue-test-doc.doc', + uploaded_by_id=user.id, + ) + db.session.add(version) + db.session.flush() + + started_at = datetime.utcnow() - timedelta(seconds=120 if stale else 5) + job = KbJob( + job_type='clean', + status='running', + group_id=group.id, + document_id=document.id, + document_version_id=version.id, + progress=20, + message='开始执行最小清洗任务', + started_at=started_at, + created_by_id=user.id, + ) + db.session.add(job) + db.session.commit() + return job + + +def test_recover_stale_running_jobs_marks_old_running_job_failed(app, tmp_path): + _configure_app(app, tmp_path) + with app.app_context(): + job = _seed_clean_job(stale=True) + recovered_count, message = recover_stale_running_jobs() + assert recovered_count == 1 + assert message == 'recovered_1' + + refreshed_job = db.session.get(KbJob, job.id) + refreshed_version = db.session.get(KbDocumentVersion, job.document_version_id) + assert refreshed_job is not None + assert refreshed_job.status == 'failed' + assert '自动回收' in (refreshed_job.error_message or '') + assert refreshed_version is not None + assert refreshed_version.status == 'failed' + + +def test_recover_stale_running_jobs_ignores_recent_running_job(app, tmp_path): + _configure_app(app, tmp_path) + with app.app_context(): + job = _seed_clean_job(stale=False) + recovered_count, message = recover_stale_running_jobs() + assert recovered_count == 0 + assert message == 'no_stale_jobs' + + refreshed_job = db.session.get(KbJob, job.id) + assert refreshed_job is not None + assert refreshed_job.status == 'running' + + +def test_is_clean_timeout_error_detects_soffice_timeout(): + assert _is_clean_timeout_error(RuntimeError('soffice timed out after 120s: QP-42.doc')) + assert not _is_clean_timeout_error(RuntimeError('edkb_system failed')) + + +def test_run_soffice_raises_on_timeout(monkeypatch): + import subprocess + + def _raise_timeout(*_args, **_kwargs): + raise subprocess.TimeoutExpired(cmd=['soffice'], timeout=120) + + monkeypatch.setattr(soffice_util.subprocess, 'run', _raise_timeout) + monkeypatch.setenv('EDKB_SOFFICE_TIMEOUT_SEC', '120') + + with pytest.raises(RuntimeError, match='soffice timed out after 120s'): + soffice_util.run_soffice(['soffice', '--headless']) diff --git a/docker-compose.yml b/docker-compose.yml index 7965d80f..aa6feda6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -43,6 +43,10 @@ services: - KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb} - KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker} - KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2} + # kb-worker 自动回收长时间 running 的任务(秒) + - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-300} + # LibreOffice 单次格式转换超时(秒) + - EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-120} # 允许容器访问宿主机服务 (如数据库) extra_hosts: @@ -88,6 +92,10 @@ services: - KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb} - KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker} - KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2} + # kb-worker 自动回收长时间 running 的任务(秒) + - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-300} + # LibreOffice 单次格式转换超时(秒) + - EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-120} extra_hosts: - "host.docker.internal:host-gateway" volumes: diff --git a/docs/knowledge_base_runtime_deploy.md b/docs/knowledge_base_runtime_deploy.md index 44ae2c1e..fd04ed30 100644 --- a/docs/knowledge_base_runtime_deploy.md +++ b/docs/knowledge_base_runtime_deploy.md @@ -44,6 +44,8 @@ | `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` | | `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` | | `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 | +| `KB_JOB_RUNNING_TIMEOUT_SECONDS` | running 任务超时回收 | 默认 `300`,应大于单次清洗预期耗时 | +| `EDKB_SOFFICE_TIMEOUT_SEC` | LibreOffice 转换超时 | 默认 `120` | | `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` | | `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 | | `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 |