Update rule + flow hdfs new

This commit is contained in:
2026-09-23 11:36:34 +07:00
parent c79ea9f05f
commit 0e15bc89a8
10 changed files with 159 additions and 35 deletions

4
.gitignore vendored
View File

@@ -5,4 +5,6 @@ __pycache__/
*.egg-info/
export/
idp_parsing_service.egg-info/
build/
build/
chandra-dla-api-v2-20260906-024126.tar
hdfs-kbr.zip

View File

@@ -103,8 +103,12 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
| Biến | Mặc định | Ý nghĩa |
|---|---|---|
| `IDP_DATA_DIR` | `./data` | SQLite và file làm việc; API và worker phải dùng cùng thư mục |
| `IDP_STORAGE` | `local` | `local` để thử; `hdfs` dùng WebHDFS; `hdfs_cli` dùng lệnh `hdfs dfs` |
| `IDP_STORAGE` | `local` | `local` để thử; `hdfs` dùng WebHDFS; `hdfs_cli` dùng HDFS native RPC |
| `IDP_HDFS_URL` | `http://namenode:9870` | WebHDFS NameNode URL khi dùng `IDP_STORAGE=hdfs` |
| `IDP_HDFS_NATIVE_URI` | rỗng | Native HDFS URI; với bộ cấu hình triển khai hiện tại dùng `hdfs://vptwd` |
| `HDFS_PRINCIPAL` | rỗng | Kerberos principal dùng đăng nhập bằng keytab |
| `HDFS_KEYTAB` | keytab trong gói portable | Đường dẫn keytab HDFS |
| `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_OCR_URL` | `http://localhost:9222/v1/chat/completions` | API vLLM |
@@ -121,12 +125,27 @@ Khi đặt `IDP_API_KEY`, mọi endpoint job cần header `X-API-Key`.
Chế độ WebHDFS dùng ví dụ `InsecureClient` đã có trong repo, đã chuyển vào
`idp_service/webhdfs.py` vì tên `hdfs.py` cũ trùng tên package `hdfs` và gây lỗi
import. Cài bằng `uv sync --extra hdfs` và đặt `IDP_HDFS_URL` trên worker.
Worker tải PDF xuống file tạm, không đọc toàn bộ vào RAM. Nếu cluster chỉ cho
truy cập qua Hadoop CLI, chọn `IDP_STORAGE=hdfs_cli` và cài binary `hdfs` cùng
cấu hình Hadoop trên worker. API và worker phải có quyền
Worker tải PDF xuống file tạm, không đọc toàn bộ vào RAM. Cụm triển khai dùng
native RPC, Kerberos và HA nên chọn `IDP_STORAGE=hdfs_cli`, đặt
`IDP_HDFS_NATIVE_URI=hdfs://vptwd` và
`HDFS_PRINCIPAL=searchengine@DATALAKE.DCS.VN`. Gói portable đã kèm Java, Hadoop
client, `core-site.xml`, `hdfs-site.xml`, `krb5.conf` và keytab;
`run-worker.sh` tự thêm client vào `PATH` và đăng nhập bằng keytab. Giữ quyền
đọc keytab ở mức `600`. API và worker phải có quyền
truy cập cùng SQLite; chỉ đặt SQLite trên **một host với đĩa bền vững**, không đặt
trên HDFS/NFS. Nếu cần chạy nhiều host, thay job store bằng PostgreSQL trước.
Kiểm tra HDFS native ngay trên máy triển khai trước khi chạy worker:
```bash
./test-hdfs.sh /
./test-hdfs.sh /data/bronze/incoming
```
Máy triển khai phải phân giải được hostname trong file cấu hình, kết nối được
KDC `master1.datalake.dcs.vn` và hai NameNode trên cổng `8020`. Đồng hồ hệ thống
phải được đồng bộ để Kerberos không từ chối vé do lệch giờ.
Luồng chuẩn bị file là `HDFS → downloaded.bin → nhận diện/giải mã → source.pdf`.
File sau giải mã phải có header PDF hợp lệ; sai key, sai padding hoặc dữ liệu
không phải PDF làm bước `preparing` retry rồi chuyển job sang `failed`.
@@ -140,6 +159,7 @@ Content-Type: multipart/form-data
file=@input.pdf # bắt buộc, phần mở rộng .pdf
request_id=<uuid> # optional, mặc định service tự sinh
callback_url=<url> # optional
dag_run_id=<string> # optional; nếu bỏ trống dùng job_id trong callback
batch_id=<string> # optional
```
@@ -155,6 +175,7 @@ POST /process
"file_path": "/data/bronze/incoming/input.pdf",
"file_type": "application/pdf",
"batch_id": "optional-batch-identifier",
"dag_run_id": "callback_test_001",
"callback_url": "http://airflow-webserver:8080/your-callback-endpoint"
}
```
@@ -166,8 +187,11 @@ job: `queued`, `preparing`, `processing`, `finalizing`, `completed`,
`GET /jobs/{job_id}/pages` trả lỗi từng trang và `GET /jobs/{job_id}/result`
trả bundle sau khi hoàn tất.
Callback gửi `request_id`, `job_id`, `batch_id`, `status`, toàn bộ bundle trong
`output`, `error` và header `Idempotency-Key: job_id`. Callback được retry độc lập với OCR, tối đa
Callback gửi `{ "dag_run_id": "...", "conf": { "request_id": "...", "job_id": "...",
"status": "done", "output": { "extraction": { "pages": [<ảnh PNG Base64>] },
"canonical": <bundle> } } }` và
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.
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`.

42
docker-compose.yaml Normal file
View File

@@ -0,0 +1,42 @@
services:
chandra:
image: ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
container_name: chandra-ocr
restart: unless-stopped
gpus:
- driver: cdi
device_ids: ["nvidia.com/gpu=${GPU_UUID:?dat GPU_UUID trong .env}"]
ipc: host
shm_size: "16gb"
ports:
- "${PORT:-9222}:8000"
environment:
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
VLLM_LOGGING_LEVEL: "${VLLM_LOG_LEVEL:-INFO}"
command:
- --model=/model
- --served-model-name=chandra
- --host=0.0.0.0
- --port=8000
- --dtype=bfloat16
- --max-model-len=${MAX_MODEL_LEN:-32768}
- --max-num-seqs=${MAX_NUM_SEQS:-128}
- --max-num-batched-tokens=${MAX_BATCHED_TOKENS:-65536}
- --gpu-memory-utilization=${GPU_UTIL:-0.28}
- --enable-prefix-caching
- --seed=42
# PHẢI khớp lúc train (IMAGE_MAX_TOKEN_NUM=1792) — đổi là bbox lệch.
- --mm-processor-kwargs={"min_pixels":65536,"max_pixels":1835008}
healthcheck:
test: ["CMD-SHELL", "python3 -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health')\""]
interval: 30s
timeout: 5s
retries: 20
start_period: 600s

View File

@@ -26,6 +26,7 @@ class ProcessRequest(BaseModel):
file_path: str = Field(min_length=1, max_length=2048)
file_type: str = "application/pdf"
callback_url: str | None = None
dag_run_id: str | None = Field(default=None, min_length=1, max_length=250)
batch_id: str | None = Field(default=None, max_length=128)
@@ -71,7 +72,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
def public_job(job: dict) -> dict:
result = {key: job[key] for key in (
"id", "request_id", "batch_id", "status", "file_path", "filename", "source_kind",
"id", "request_id", "dag_run_id", "batch_id", "status", "file_path", "filename", "source_kind",
"total_pages", "completed_pages", "failed_pages", "error",
"callback_state", "callback_error", "created_at", "updated_at")}
result["result_available"] = job["result_json"] is not None
@@ -100,6 +101,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
file: UploadFile = File(...),
request_id: UUID | None = Form(default=None),
callback_url: str | None = Form(default=None),
dag_run_id: str | None = Form(default=None, min_length=1, max_length=250),
batch_id: str | None = Form(default=None, max_length=128)):
"""Nhận thẳng file PDF qua multipart/form-data và trả job_id ngay."""
filename = Path(file.filename or "").name
@@ -127,7 +129,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
try:
job, created = store.create_job(str(request_id or uuid4()), str(stored), callback_url,
batch_id, settings.max_queued_jobs, filename, "upload")
batch_id, settings.max_queued_jobs, filename, "upload", dag_run_id)
except ValueError as exc:
discard_upload(stored)
raise HTTPException(status_code=409, detail=str(exc)) from exc
@@ -146,7 +148,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
try:
job, created = store.create_job(str(request.request_id), request.file_path,
request.callback_url, request.batch_id,
settings.max_queued_jobs)
settings.max_queued_jobs, dag_run_id=request.dag_run_id)
except ValueError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except OverflowError as exc:

View File

@@ -8,6 +8,7 @@ class Settings:
data_dir: Path = Path(os.getenv("IDP_DATA_DIR", "./data")).resolve()
storage: str = os.getenv("IDP_STORAGE", "local") # local, hdfs, or hdfs_cli
hdfs_url: str = os.getenv("IDP_HDFS_URL", "http://namenode:9870")
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", "")
ocr_url: str = os.getenv("IDP_OCR_URL", "http://localhost:9222/v1/chat/completions")

View File

@@ -30,7 +30,7 @@ class Store:
db.executescript("""
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT,
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT, dag_run_id TEXT,
filename TEXT, source_kind TEXT NOT NULL DEFAULT 'path',
status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
total_pages INTEGER NOT NULL DEFAULT 0,
@@ -63,6 +63,8 @@ class Store:
db.execute("ALTER TABLE jobs ADD COLUMN filename TEXT")
if "source_kind" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN source_kind TEXT NOT NULL DEFAULT 'path'")
if "dag_run_id" not in columns:
db.execute("ALTER TABLE jobs ADD COLUMN dag_run_id TEXT")
@contextmanager
def tx(self):
@@ -83,24 +85,25 @@ class Store:
def create_job(self, request_id: str, file_path: str, callback_url: str | None,
batch_id: str | None, max_queued: int, filename: str | None = None,
source_kind: str = "path"):
source_kind: str = "path", dag_run_id: str | None = None):
now = time.time()
filename = filename or Path(file_path).name
with self.tx() as db:
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
if prior:
if (prior["file_path"], prior["callback_url"], prior["batch_id"],
prior["filename"]) != (file_path, callback_url, batch_id, filename):
prior["filename"], prior["dag_run_id"]) != (file_path, callback_url, batch_id,
filename, dag_run_id):
raise ValueError("request_id already exists with different inputs")
return self.as_dict(prior), False
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
if queued >= max_queued:
raise OverflowError("Job queue is full")
job_id = "job_" + uuid4().hex
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,filename,
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,dag_run_id,filename,
source_kind,status,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,'queued',?,?)""",
(job_id, request_id, file_path, callback_url, batch_id, filename,
VALUES(?,?,?,?,?,?,?,?,'queued',?,?)""",
(job_id, request_id, file_path, callback_url, batch_id, dag_run_id, filename,
source_kind, now, now))
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True

View File

@@ -10,9 +10,12 @@ class StorageError(Exception):
pass
def _hdfs(*args: str) -> None:
def _hdfs(settings: Settings, *args: str) -> None:
command = ["hdfs", "dfs"]
if settings.hdfs_native_uri:
command.extend(["-fs", settings.hdfs_native_uri])
try:
subprocess.run(["hdfs", "dfs", *args], check=True, capture_output=True, text=True, timeout=600)
subprocess.run([*command, *args], check=True, capture_output=True, text=True, timeout=600)
except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
detail = getattr(exc, "stderr", None) or str(exc)
raise StorageError(f"HDFS operation failed: {detail[:500]}") from exc
@@ -26,7 +29,7 @@ def fetch_pdf(settings: Settings, source: str, destination: Path) -> None:
from .webhdfs import download_pdf
download_pdf(settings.hdfs_url, source, temporary, settings.max_pdf_bytes)
elif settings.storage == "hdfs_cli":
_hdfs("-get", source, str(temporary))
_hdfs(settings, "-get", source, str(temporary))
elif settings.storage == "local":
source_path = Path(source).resolve()
if not source_path.is_file():

View File

@@ -1,5 +1,6 @@
"""Run separately from the API: python -m idp_service.worker."""
import hashlib
import base64
import json
import logging
import shutil
@@ -16,7 +17,7 @@ from .config import Settings
from .db import Store
from .decrypt import prepare_pdf
from .dla import build_outline
from .ocr import InvalidOutput, infer_page
from .ocr import InvalidOutput, infer_page, render_page
from .storage import fetch_pdf
@@ -122,7 +123,8 @@ class Worker:
result_json = json.dumps(bundle, ensure_ascii=False, separators=(",", ":"))
has_failures = any(p["status"] == "failed" for p in pages)
if self.store.finalized(job_id, job["finalize_attempts"], result_json, has_failures):
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
if not job["callback_url"]:
shutil.rmtree(self.job_dir(job_id), ignore_errors=True)
self.cleanup_source(job)
log.info("Finalized %s for callback", job_id)
except Exception as exc:
@@ -131,12 +133,28 @@ class Worker:
def callback(self, job: dict):
try:
canonical = json.loads(job["result_json"]) if job["result_json"] else None
extraction = None
if canonical is not None:
source = self.job_dir(job["id"]) / "source.pdf"
extraction = {"pages": []}
for page_no in range(1, canonical["source"]["page_count"] + 1):
image, _, _ = render_page(source, page_no)
extraction["pages"].append({
"page_no": page_no,
"media_type": "image/png",
"data_base64": base64.b64encode(image).decode("ascii"),
})
payload = {
"request_id": job["request_id"], "job_id": job["id"],
"batch_id": job["batch_id"],
"status": "done" if job["status"] == "completed" else job["status"],
"output": json.loads(job["result_json"]) if job["result_json"] else None,
"error": job["error"],
"dag_run_id": job["dag_run_id"] or job["id"],
"conf": {
"request_id": job["request_id"], "job_id": job["id"],
"status": "done" if job["status"] == "completed" else job["status"],
"output": {
"extraction": extraction,
"canonical": canonical,
},
},
}
request = Request(job["callback_url"], data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json",
@@ -145,10 +163,13 @@ class Worker:
if not 200 <= response.status < 300:
raise RuntimeError(f"Callback HTTP {response.status}")
self.store.callback_done(job["id"], job["callback_attempts"])
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
except Exception as exc:
log.warning("Callback failed for %s: %s", job["id"], exc)
self.store.callback_failed(job["id"], job["callback_attempts"],
str(exc), self.settings.max_callback_attempts)
if job["callback_attempts"] >= self.settings.max_callback_attempts:
shutil.rmtree(self.job_dir(job["id"]), ignore_errors=True)
def coordinator_once(self) -> bool:
did_work = False

View File

@@ -9,6 +9,7 @@ Content-Type: multipart/form-data
file=@input.pdf
request_id=550e8400-e29b-41d4-a716-446655440000 # optional
callback_url=http://airflow-webserver:8080/... # optional
dag_run_id=callback_test_001 # optional; ID cho callback
batch_id=... # optional
```
@@ -25,6 +26,7 @@ Content-Type: application/json
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"file_path": "/data/bronze/incoming/qudtw216_signed_7829c.pdf",
"file_type": "application/pdf",
"dag_run_id": "callback_test_001",
"callback_url": "http://airflow-webserver:8080/api/v1/dags/bronze_ingest_trigger/dagRuns/{run_id}/taskInstances/trigger_idp/callback"
}
```
@@ -36,6 +38,7 @@ Content-Type: application/json
| `file_path` | ✓ | Path tuyệt đối trên HDFS |
| `file_type` | optional | mime pdf/audio/json... |
| `callback_url` | optional | Callback response |
| `dag_run_id` | optional | ID gửi trong callback; nếu bỏ trống dùng `job_id` |
---
@@ -58,14 +61,25 @@ POST {callback_url}
Content-Type: application/json
{
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"job_id": "job-98765",
"status": "done",
"output": { ... },
"dag_run_id": "callback_test_001",
"conf": {
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"job_id": "job-98765",
"status": "done",
"output": {
"extraction": {
"pages": [{ "page_no": 1, "media_type": "image/png", "data_base64": "..." }]
},
"canonical": { "schema": "dla-document-bundle", "pages": [] }
}
}
}
```
`output` là `dla-document-bundle`, cùng schema với `GET /jobs/{job_id}/result`.
`output.extraction.pages` chứa ảnh PNG 200 DPI từng trang, mã hóa Base64.
`output.canonical` là toàn bộ `dla-document-bundle` từ `GET /jobs/{job_id}/result`.
Callback thất bại trước khi có kết quả có `status: "failed"` và cả hai trường
`extraction`, `canonical` là `null`.
---
@@ -77,4 +91,4 @@ Content-Type: application/json
| `FILE_READ_ERROR` | Lỗi network/permission khi đọc |
| `FILE_STILL_WRITING` | File chưa ghi xong |
| `PARSE_ERROR` | File đọc được nhưng lỗi khi xử lý nội dung |
| `TIMEOUT` | Xử lý quá thời gian cho phép |
| `TIMEOUT` | Xử lý quá thời gian cho phép |

View File

@@ -1,3 +1,4 @@
import base64
import json
from dataclasses import replace
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -228,6 +229,7 @@ def test_real_http_ocr_and_callback(tmp_path):
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"})
assert reply.status_code == 202
worker = Worker(settings)
@@ -236,9 +238,19 @@ def test_real_http_ocr_and_callback(tmp_path):
worker.process_page(page)
worker.coordinator_once()
assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered"
assert callbacks[0]["status"] == "done"
assert callbacks[0]["output"]["schema"] == "dla-document-bundle"
assert callbacks[0]["output"]["pages"][0]["status"] == "done"
assert callbacks[0]["dag_run_id"] == "callback_test_001"
assert set(callbacks[0]) == {"dag_run_id", "conf"}
conf = callbacks[0]["conf"]
assert conf["request_id"] == reply.json()["request_id"]
assert conf["job_id"] == reply.json()["job_id"]
assert conf["status"] == "done"
assert conf["output"]["canonical"]["schema"] == "dla-document-bundle"
assert conf["output"]["canonical"]["pages"][0]["status"] == "done"
images = conf["output"]["extraction"]["pages"]
assert len(images) == 1
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")
finally:
server.shutdown()
server.server_close()