Fix callback worker #2

Merged
annt839 merged 1 commits from feat/kie-extraction into main 2026-09-25 02:34:31 +00:00
5 changed files with 58 additions and 7 deletions
Showing only changes of commit 65c4f44e28 - Show all commits

2
.gitignore vendored
View File

@@ -8,4 +8,4 @@ idp_parsing_service.egg-info/
build/
chandra-dla-api-v2-20260906-024126.tar
hdfs-kbr.zip
.env
.env

View File

@@ -175,6 +175,7 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
| `IDP_MAX_KIE_ATTEMPTS` | `3` | Số lần thử bóc trường mỗi tài liệu |
| `IDP_RUN_WORKER` | `0` | `1` chạy worker ngay trong process API |
| `IDP_OCR_WORKERS` | `64` | Giới hạn tổng request tới GPU, lưu bằng SQLite |
| `IDP_CALLBACK_WORKERS` | `4` | Số luồng gửi callback độc lập; callback lỗi không giữ luồng chuẩn bị/finalize job |
| `IDP_OCR_TIMEOUT` | `180` | Timeout mỗi request OCR, giây |
| `IDP_LEASE_SECONDS` | `1800` | Lease task; phải lớn hơn timeout và thời gian chuẩn bị/finalize |
| `IDP_MAX_PAGE_ATTEMPTS` | `3` | Số lần thử OCR mỗi trang |

View File

@@ -25,6 +25,7 @@ class Settings:
max_kie_attempts: int = int(os.getenv("IDP_MAX_KIE_ATTEMPTS", "3"))
run_worker: bool = os.getenv("IDP_RUN_WORKER", "0").lower() in ("1", "true", "yes")
ocr_workers: int = int(os.getenv("IDP_OCR_WORKERS", "64"))
callback_workers: int = int(os.getenv("IDP_CALLBACK_WORKERS", "4"))
max_queued_jobs: int = int(os.getenv("IDP_MAX_QUEUED_JOBS", "1000"))
max_pdf_bytes: int = int(os.getenv("IDP_MAX_PDF_BYTES", str(1024**3)))
max_pages: int = int(os.getenv("IDP_MAX_PAGES", "5000"))

View File

@@ -35,6 +35,8 @@ class Worker:
settings.work_dir.mkdir(parents=True, exist_ok=True)
if settings.ocr_workers < 1 or settings.lease_seconds <= settings.ocr_timeout:
raise ValueError("OCR workers must be positive and lease must exceed OCR timeout")
if settings.callback_workers < 1:
raise ValueError("IDP_CALLBACK_WORKERS must be positive")
if settings.ocr_backend not in ("http", "pdf_text"):
raise ValueError("IDP_OCR_BACKEND must be http or pdf_text")
if bool(settings.callback_basic_user) != bool(settings.callback_basic_password):
@@ -235,12 +237,20 @@ class Worker:
if job:
self.finalize(job)
did_work = True
job = self.store.claim_callback(self.settings.lease_seconds)
if job:
self.callback(job)
did_work = True
return did_work
def callback_once(self) -> bool:
job = self.store.claim_callback(self.settings.lease_seconds)
if not job:
return False
self.callback(job)
return True
def callback_loop(self):
while not self.stop.is_set():
if not self.callback_once():
self.stop.wait(self.settings.poll_seconds)
def page_loop(self):
while not self.stop.is_set():
page = self.store.claim_page(self.settings.lease_seconds, self.settings.ocr_workers)
@@ -256,9 +266,12 @@ class Worker:
def run(self):
threads = [threading.Thread(target=self.page_loop, name=f"ocr-{i}", daemon=True)
for i in range(self.settings.ocr_workers)]
threads.extend(threading.Thread(target=self.callback_loop, name=f"callback-{i}", daemon=True)
for i in range(self.settings.callback_workers))
for thread in threads:
thread.start()
log.info("Worker started with %s OCR threads", len(threads))
log.info("Worker started with %s OCR threads and %s callback threads",
self.settings.ocr_workers, self.settings.callback_workers)
try:
while not self.stop.is_set():
if not self.coordinator_once():

View File

@@ -3,7 +3,7 @@ import json
from dataclasses import replace
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Thread
from threading import Event, Thread
from uuid import uuid4
import pymupdf
@@ -46,6 +46,7 @@ def drain(worker, settings):
if job:
worker.extract(job)
assert worker.coordinator_once()
worker.callback_once()
def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch):
@@ -460,6 +461,41 @@ def test_global_gpu_limit_and_fairness_across_files(tmp_path):
assert store.claim_page(settings.lease_seconds, global_limit=2) is None
def test_slow_callback_does_not_block_next_job_or_callback(tmp_path, monkeypatch):
settings = replace(settings_for(tmp_path), callback_workers=2)
store = Store(settings.db_path)
source = tmp_path / "input.pdf"
make_pdf(source, count=1)
bad, _ = store.create_job(str(uuid4()), str(source), "http://bad-callback", None, 100)
good, _ = store.create_job(str(uuid4()), str(source), "http://good-callback", None, 100)
later, _ = store.create_job(str(uuid4()), str(source), None, None, 100)
with store.tx() as db:
db.execute("UPDATE jobs SET status='completed', callback_state='pending' WHERE id IN (?, ?)",
(bad["id"], good["id"]))
worker = Worker(settings, store)
started, release = Event(), Event()
def fake_callback(job):
if job["id"] == bad["id"]:
started.set()
assert release.wait(5)
store.callback_done(job["id"], job["callback_attempts"])
monkeypatch.setattr(worker, "callback", fake_callback)
thread = Thread(target=worker.callback_once)
thread.start()
try:
assert started.wait(5)
assert worker.coordinator_once()
assert store.get_job(later["id"])["status"] == "processing"
assert worker.callback_once()
assert store.get_job(good["id"])["callback_state"] == "delivered"
finally:
release.set()
thread.join(timeout=5)
assert not thread.is_alive()
def test_webhdfs_adapter_streams(tmp_path, monkeypatch):
class FakeClient:
def __init__(self):