Compare commits
2 Commits
e9d7c6d391
...
feat/kie-e
| Author | SHA1 | Date | |
|---|---|---|---|
| 65c4f44e28 | |||
| 79b70bed12 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -7,4 +7,5 @@ export/
|
||||
idp_parsing_service.egg-info/
|
||||
build/
|
||||
chandra-dla-api-v2-20260906-024126.tar
|
||||
hdfs-kbr.zip
|
||||
hdfs-kbr.zip
|
||||
.env
|
||||
|
||||
10
SERVICE.md
10
SERVICE.md
@@ -161,6 +161,8 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
|
||||
| `KRB5_CONFIG` | `native-hdfs/conf/krb5.conf` | Đường dẫn cấu hình Kerberos |
|
||||
| `IDP_API_KEY` | rỗng | Khóa API; **bắt buộc cấu hình khi mở API ra mạng** |
|
||||
| `IDP_CALLBACK_HOSTS` | rỗng | Danh sách hostname callback được phép, cách nhau bằng dấu phẩy |
|
||||
| `IDP_CALLBACK_BASIC_USER` | rỗng | Username Basic Auth khi worker gọi callback |
|
||||
| `IDP_CALLBACK_BASIC_PASSWORD` | rỗng | Password Basic Auth khi worker gọi callback |
|
||||
| `IDP_OCR_URL` | `http://localhost:9222/v1/chat/completions` | API vLLM |
|
||||
| `IDP_OCR_MODEL` | `chandra` | Tên model |
|
||||
| `IDP_OCR_BACKEND` | `http` | `http` gọi model; `pdf_text` dựng bundle từ text layer, chỉ để chạy thử |
|
||||
@@ -169,9 +171,11 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
|
||||
| `IDP_KIE_MODEL` | theo `IDP_OCR_MODEL` | Tên model KIE |
|
||||
| `IDP_KIE_MAX_PAGES` | `5` | Số ảnh tối đa gửi một lượt KIE; quá thì lấy các trang đầu và trang cuối |
|
||||
| `IDP_KIE_TIMEOUT` | `300` | Timeout một lượt KIE, giây |
|
||||
| `IDP_KIE_MAX_TOKENS` | `2048` | Giới hạn số token đầu ra của mỗi request KIE; độc lập với `--max-model-len` của vLLM |
|
||||
| `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 |
|
||||
@@ -250,6 +254,12 @@ Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id":
|
||||
header `Idempotency-Key: job_id`. Nếu không truyền `dag_run_id`, service dùng
|
||||
`job_id` làm giá trị ổn định khi retry. Callback được retry độc lập với OCR, tối đa
|
||||
`IDP_MAX_CALLBACK_ATTEMPTS` lần; Airflow nên xử lý callback lặp idempotently.
|
||||
Nếu Airflow trả `409` vì DAG run đã tồn tại, worker gọi GET DAG run đó và chỉ
|
||||
đánh dấu callback đã giao khi `dag_run_id`, `job_id` và `request_id` đều khớp.
|
||||
Xung đột với job khác vẫn được ghi là lỗi callback.
|
||||
Nếu Airflow yêu cầu Basic Auth, đặt cả `IDP_CALLBACK_BASIC_USER` và
|
||||
`IDP_CALLBACK_BASIC_PASSWORD` trong `.env` của API/worker; worker gửi header
|
||||
`Authorization: Basic ...` cùng request callback.
|
||||
Trạng thái `callback_state=exhausted` cho biết cần xử lý thủ công; bundle vẫn
|
||||
đọc được qua `GET /jobs/{job_id}/result`.
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ class Settings:
|
||||
hdfs_native_uri: str = os.getenv("IDP_HDFS_NATIVE_URI", "")
|
||||
api_key: str = os.getenv("IDP_API_KEY", "")
|
||||
callback_hosts: str = os.getenv("IDP_CALLBACK_HOSTS", "")
|
||||
callback_basic_user: str = os.getenv("IDP_CALLBACK_BASIC_USER", "")
|
||||
callback_basic_password: str = os.getenv("IDP_CALLBACK_BASIC_PASSWORD", "")
|
||||
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")
|
||||
ocr_model: str = os.getenv("IDP_OCR_MODEL", "chandra")
|
||||
ocr_backend: str = os.getenv("IDP_OCR_BACKEND", "http") # http hoặc pdf_text
|
||||
@@ -19,9 +21,11 @@ class Settings:
|
||||
kie_model: str = os.getenv("IDP_KIE_MODEL") or os.getenv("IDP_OCR_MODEL", "chandra")
|
||||
kie_max_pages: int = int(os.getenv("IDP_KIE_MAX_PAGES", "5"))
|
||||
kie_timeout: int = int(os.getenv("IDP_KIE_TIMEOUT", "300"))
|
||||
kie_max_tokens: int = int(os.getenv("IDP_KIE_MAX_TOKENS", "2048"))
|
||||
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"))
|
||||
|
||||
@@ -140,7 +140,7 @@ def extract_document(settings: Settings, pdf_path: Path, page_count: int) -> dic
|
||||
payload = {
|
||||
"model": settings.kie_model,
|
||||
"messages": [{"role": "user", "content": content}],
|
||||
"max_tokens": 2048,
|
||||
"max_tokens": settings.kie_max_tokens,
|
||||
"temperature": 0.0,
|
||||
"top_p": 0.1,
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import pymupdf
|
||||
@@ -33,8 +35,12 @@ 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):
|
||||
raise ValueError("Set both IDP_CALLBACK_BASIC_USER and IDP_CALLBACK_BASIC_PASSWORD")
|
||||
if settings.ocr_backend == "pdf_text":
|
||||
log.warning("IDP_OCR_BACKEND=pdf_text: bundle dựng từ text layer của PDF, không gọi model")
|
||||
|
||||
@@ -179,12 +185,20 @@ class Worker:
|
||||
},
|
||||
},
|
||||
}
|
||||
headers = {"Content-Type": "application/json", "Idempotency-Key": job["id"]}
|
||||
if self.settings.callback_basic_user:
|
||||
credentials = f"{self.settings.callback_basic_user}:{self.settings.callback_basic_password}"
|
||||
headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("ascii")
|
||||
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json",
|
||||
"Idempotency-Key": job["id"]}, method="POST")
|
||||
with urlopen(request, timeout=10) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise RuntimeError(f"Callback HTTP {response.status}")
|
||||
headers=headers, method="POST")
|
||||
try:
|
||||
with urlopen(request, timeout=10) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise RuntimeError(f"Callback HTTP {response.status}")
|
||||
except HTTPError as exc:
|
||||
if exc.code != 409 or not self.airflow_run_matches(job["callback_url"], payload, headers):
|
||||
raise
|
||||
log.info("Airflow DAG run already exists for %s; callback confirmed", job["id"])
|
||||
self.store.callback_done(job["id"], job["callback_attempts"])
|
||||
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
|
||||
except Exception as exc:
|
||||
@@ -194,6 +208,25 @@ class Worker:
|
||||
if job["callback_attempts"] >= self.settings.max_callback_attempts:
|
||||
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
|
||||
|
||||
@staticmethod
|
||||
def airflow_run_matches(callback_url: str, payload: dict, headers: dict) -> bool:
|
||||
"""A 409 confirms delivery only when Airflow has this same job's DAG run."""
|
||||
parsed = urlsplit(callback_url)
|
||||
path = parsed.path.rstrip("/")
|
||||
segments = path.split("/")
|
||||
if len(segments) != 6 or segments[:4] != ["", "api", "v1", "dags"] or segments[5] != "dagRuns":
|
||||
return False
|
||||
run_url = urlunsplit((parsed.scheme, parsed.netloc,
|
||||
path + "/" + quote(payload["dag_run_id"], safe=""), "", ""))
|
||||
get_headers = {"Authorization": headers["Authorization"]} if "Authorization" in headers else {}
|
||||
with urlopen(Request(run_url, headers=get_headers, method="GET"), timeout=10) as response:
|
||||
existing = json.load(response)
|
||||
conf = existing.get("conf") or {}
|
||||
expected = payload["conf"]
|
||||
return (existing.get("dag_run_id") == payload["dag_run_id"]
|
||||
and conf.get("job_id") == expected["job_id"]
|
||||
and conf.get("request_id") == expected["request_id"])
|
||||
|
||||
def coordinator_once(self) -> bool:
|
||||
did_work = False
|
||||
job = self.store.claim_prepare(self.settings.lease_seconds)
|
||||
@@ -204,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)
|
||||
@@ -225,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():
|
||||
|
||||
@@ -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):
|
||||
@@ -230,7 +231,8 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
|
||||
thread.start()
|
||||
try:
|
||||
url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions"
|
||||
settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url)
|
||||
settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url,
|
||||
kie_max_tokens=4096)
|
||||
source = tmp_path / "quyet-dinh.pdf"
|
||||
make_pdf(source, count=2)
|
||||
app = create_app(settings)
|
||||
@@ -246,6 +248,7 @@ def test_extract_fixed_schema_end_to_end_and_callback(tmp_path):
|
||||
assert len(kie_requests) == 1
|
||||
assert len(kie_requests[0]["messages"][0]["content"]) == 3
|
||||
assert kie_requests[0]["model"] == settings.kie_model
|
||||
assert kie_requests[0]["max_tokens"] == 4096
|
||||
|
||||
extraction = client.get(f"/jobs/{job_id}/extraction").json()
|
||||
assert extraction["status"] == "done"
|
||||
@@ -359,6 +362,7 @@ def test_rejects_truncated_plain_text_and_invalid_bbox():
|
||||
|
||||
def test_real_http_ocr_and_callback(tmp_path):
|
||||
callbacks = []
|
||||
auth_headers = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
@@ -370,8 +374,20 @@ def test_real_http_ocr_and_callback(tmp_path):
|
||||
'<div data-label="Paragraph" data-bbox="1 1 500 500">Test</div>'}}]}
|
||||
else:
|
||||
callbacks.append(body)
|
||||
answer = {"ok": True}
|
||||
auth_headers.append(self.headers.get("Authorization"))
|
||||
answer = {"detail": "DAG Run already exists"}
|
||||
data = json.dumps(answer).encode()
|
||||
self.send_response(200 if self.path == "/v1/chat/completions" else 409)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
assert self.path == "/api/v1/dags/test/dagRuns/callback_test_001"
|
||||
assert self.headers.get("Authorization") == auth_headers[0]
|
||||
data = json.dumps({"dag_run_id": callbacks[0]["dag_run_id"],
|
||||
"conf": callbacks[0]["conf"]}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
@@ -386,18 +402,21 @@ def test_real_http_ocr_and_callback(tmp_path):
|
||||
thread.start()
|
||||
try:
|
||||
settings = replace(settings_for(tmp_path),
|
||||
ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions")
|
||||
ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions",
|
||||
callback_basic_user="callback_handler",
|
||||
callback_basic_password="callback_handler")
|
||||
source = tmp_path / "input.pdf"
|
||||
make_pdf(source, count=1)
|
||||
app = create_app(settings)
|
||||
with TestClient(app) as client:
|
||||
reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source),
|
||||
"dag_run_id": "callback_test_001",
|
||||
"callback_url": f"http://127.0.0.1:{server.server_port}/callback"})
|
||||
"callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"})
|
||||
assert reply.status_code == 202
|
||||
drain(Worker(settings), settings)
|
||||
assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered"
|
||||
assert callbacks[0]["dag_run_id"] == "callback_test_001"
|
||||
assert auth_headers == ["Basic " + base64.b64encode(b"callback_handler:callback_handler").decode("ascii")]
|
||||
assert set(callbacks[0]) == {"dag_run_id", "conf"}
|
||||
conf = callbacks[0]["conf"]
|
||||
assert conf["request_id"] == reply.json()["request_id"]
|
||||
@@ -410,6 +429,16 @@ def test_real_http_ocr_and_callback(tmp_path):
|
||||
assert images[0]["page_no"] == 1
|
||||
assert images[0]["media_type"] == "image/png"
|
||||
assert base64.b64decode(images[0]["data_base64"]).startswith(b"\x89PNG\r\n\x1a\n")
|
||||
|
||||
# Cùng dag_run_id nhưng job khác phải giữ lỗi 409, không đánh dấu delivered.
|
||||
second = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source),
|
||||
"dag_run_id": "callback_test_001",
|
||||
"callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"})
|
||||
assert second.status_code == 202
|
||||
drain(Worker(settings), settings)
|
||||
second_status = client.get(f"/jobs/{second.json()['job_id']}").json()
|
||||
assert second_status["callback_state"] == "pending"
|
||||
assert "409" in second_status["callback_error"]
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
@@ -432,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):
|
||||
|
||||
Reference in New Issue
Block a user