Fix worker db #4

Merged
annt839 merged 1 commits from feat/kie-qwen-page-routing into main 2026-09-29 05:49:28 +00:00
8 changed files with 241 additions and 43 deletions

View File

@@ -2,14 +2,15 @@
# --- Model (compose) ---
GPU_DEVICE=0 # index hoặc UUID card, như `docker run --gpus device=0`
CHANDRA_MODEL_DIR=/path/to/chandra-dla-v2 # thư mục weights trên host
KIE_MODEL_DIR=/path/to/Qwen3.5-4B # snapshot HF đã bung (không để symlink trỏ ra ngoài)
KIE_MODEL_DIR=./qwen35-4b-model # mkdir -p qwen35-4b-model; tar -xf qwen35-4b-weights.tar -C qwen35-4b-model
GPU_UTIL=0.55 # chandra; GPU_UTIL + KIE_GPU_UTIL < phần card còn trống
KIE_GPU_UTIL=0.3
MAX_MODEL_LEN=32768 # chandra; cấu hình cũ 98304 cần thêm KV cache GPU
MAX_NUM_SEQS=128
MAX_BATCHED_TOKENS=65536
PORT=9222
KIE_PORT=9224
# IMAGE_TAG=chandra-dla-api:v2-20260906-024126
# KIE_IMAGE=vllm/vllm-openai:v0.23.0
# APP_IMAGE=idp-parsing-service:0.2.0
# --- HDFS native (worker) ---

1
.gitignore vendored
View File

@@ -4,6 +4,7 @@ __pycache__/
.pytest_cache/
*.egg-info/
export/
qwen35-4b-model/
idp_parsing_service.egg-info/
build/
chandra-dla-api-v2-20260906-024126.tar

View File

@@ -133,15 +133,70 @@ Một file `docker-compose.yaml` dựng đủ 4 container trên **một host, m
| Service | Container | Việc | Cổng |
|---|---|---|---|
| `chandra` | `chandra-ocr` | DLA/OCR từng trang (vLLM, image `IMAGE_TAG`) | `PORT` (9222) |
| `kie` | `qwen-kie` | Bóc trường Qwen3.5-4B (vLLM, image `KIE_IMAGE`) | `KIE_PORT` (9224) |
| `kie` | `qwen-kie` | Bóc trường Qwen3.5-4B (cùng image vLLM với Chandra) | `KIE_PORT` (9224) |
| `api` | `idp-api` | HTTP API (image build từ `Dockerfile`) | `IDP_PORT` (8001) |
| `worker` | `idp-worker` | Hàng đợi trang, KIE, finalize, callback, tải PDF từ HDFS | — |
Image `chandra-dla-api:v2-20260906-024126` đã chứa vLLM 0.23.0 và weight Chandra.
Service `kie` cũng dùng image này, nhưng mount weight Qwen3.5-4B từ host lên `/model`.
Vì `qwen35-4b-weights.tar` đã được tải lên server riêng, thư mục dự án mang đi
không chứa 8.8 GB weight. `deploy-offline.sh` sẽ kiểm tra SHA-256 và giải nén
archive trên server vào `qwen35-4b-model/`. Thư mục dự án có sẵn archive image
API trong `export/` và file `.env`; hai mục này bị Git bỏ qua, vì vậy hãy chuyển
**cả thư mục trên đĩa** (ví dụ bằng `rsync`), không chỉ `git clone`.
Trước khi chạy, kiểm tra `.env`, đặc biệt `KIE_MODEL_DIR=./qwen35-4b-model`, GPU,
API key và `HDFS_NATIVE_DIR`. Gói HDFS native không có trong thư mục dự án: server
phải có thư mục `/root/idp-portable/native-hdfs` (hoặc chỉnh `HDFS_NATIVE_DIR` trong
`.env`) chứa `bin/hdfs`, `conf/krb5.conf` và keytab.
Nếu `chandra-ocr` đang chạy từ compose cũ, dừng stack cũ trước khi khởi động
compose mới để giải phóng tên container và cổng 9222.
Sau khi chuyển thư mục, chạy một lệnh trên server (thay đường dẫn bằng vị trí
archive Qwen đã upload):
```bash
cp .env.example .env # sửa đường dẫn weights, GPU, HDFS, khóa; chmod 600 .env
docker compose up -d --build # máy không có mạng: xem mục offline bên dưới
docker compose ps # chandra/kie healthy thì worker mới khởi động
docker compose logs -f worker
bash deploy-offline.sh /duong/dan/qwen35-4b-weights.tar
```
Script nạp image API từ `export/`, giải nén Qwen nếu cần, rồi chạy Compose với
`--wait` để chỉ báo thành công khi cả bốn container healthy. Mặc định chờ tối đa
30 phút cho hai model tải lên GPU; có thể đổi bằng `DEPLOY_WAIT_SECONDS`. Các lần
sau có thể chạy trực tiếp `docker compose up -d --no-build --pull never --wait`.
Cả bốn service dùng `restart: unless-stopped`: Docker tự khởi động lại container
khi tiến trình chính thoát hoặc daemon khởi động lại. API có healthcheck kiểm tra
HTTP và SQLite; worker kiểm tra SQLite cùng HDFS client/keytab; hai model kiểm tra
`/health`. Healthcheck chuyển trạng thái sang `unhealthy` nhưng Docker Compose
**không tự restart container chỉ vì unhealthy**. Nếu service bị treo mà tiến trình
chưa thoát, cần cảnh báo/giám sát bên ngoài. Worker sẽ thoát nếu một luồng xử lý
chết bất thường để Docker có thể khởi động lại container. Job đang chạy được lưu
trong SQLite và thử lại sau khi lease hết hạn (`IDP_LEASE_SECONDS`, mặc định 1800 giây).
Nếu server có mạng và muốn build lại image API từ source, sau khi Qwen đã giải
nén thì dùng:
```bash
docker compose up -d --build
```
Nếu muốn tự giải nén Qwen trước khi chạy Compose, dùng:
```bash
# Chạy trong thư mục parsing-service; archive có thể nằm ở nơi khác trên server.
echo '65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13 /duong/dan/qwen35-4b-weights.tar' | sha256sum -c -
mkdir -p qwen35-4b-model
tar -xf /duong/dan/qwen35-4b-weights.tar -C qwen35-4b-model
test -f qwen35-4b-model/config.json
test -f qwen35-4b-model/model.safetensors.index.json
```
Sau khi chạy Compose:
```bash
docker compose ps # chandra/kie healthy thì worker mới khởi động
curl -f http://127.0.0.1:9222/health
curl -f http://127.0.0.1:9224/health
```
`.env` vừa cấp biến cho compose vừa là env của `api`/`worker`, nên các biến `IDP_*`
@@ -150,8 +205,9 @@ giữ nguyên như khi chạy `run-api.sh`/`run-worker.sh`. Những biến riên
- `GPU_DEVICE`: index hoặc UUID card (như `docker run --gpus device=0`). Hai model
chia card bằng `GPU_UTIL` (0.55) và `KIE_GPU_UTIL` (0.3), thực đo ~80% card H200;
`kie` chỉ khởi động sau khi `chandra` healthy để hai vLLM không đo bộ nhớ cùng lúc.
- `CHANDRA_MODEL_DIR`, `KIE_MODEL_DIR`: thư mục weights trên host, mount chỉ đọc vào
`/model`. Weights Qwen là snapshot HF đã bung, không để symlink trỏ ra ngoài thư mục.
- `KIE_MODEL_DIR`: thư mục weight Qwen trên host, mount chỉ đọc vào `/model` của
container `kie`. Thư mục giải nén từ `qwen35-4b-weights.tar` không chứa symlink
ra ngoài. Chandra dùng weight đã nhúng trong image, không cần mount từ host.
- `HDFS_NATIVE_DIR`: thư mục `native-hdfs` của gói portable (Java, Hadoop client,
`conf/krb5.conf`, keytab), mount chỉ đọc vào worker ở `/opt/native-hdfs`; image
đã có `kinit`. Chỉ cần khi `IDP_STORAGE=hdfs_cli`.
@@ -162,19 +218,16 @@ giữ nguyên như khi chạy `run-api.sh`/`run-worker.sh`. Những biến riên
và phân giải namenode/KDC theo `/etc/hosts` của host, y như khi chạy bằng script.
Kiểm tra HDFS trong container: `docker compose exec worker hdfs dfs -ls /`.
Máy đích không có Internet: `build` cần mạng (base `python:3.11-slim`, apt, PyPI),
nên build ở máy có mạng rồi mang image sang. Cả 3 image phải có sẵn trên máy đích,
thiếu cái nào compose sẽ cố pull và lỗi.
Máy đích không có Internet: `build` service API cần mạng (base `python:3.11-slim`, apt,
PyPI), nên build ở máy có mạng rồi mang image sang. Máy đích cần hai image:
`idp-parsing-service:0.2.0` (đã đóng trong `export/`) và
`chandra-dla-api:v2-20260906-024126` (đã mang sang trước đó), cộng với thư mục
`qwen35-4b-weights.tar` đã upload riêng trên server.
```bash
# máy có mạng
docker compose build api
docker save idp-parsing-service:0.2.0 | gzip > idp-parsing-service-0.2.0.tar.gz
docker save vllm/vllm-openai:v0.23.0 | gzip > vllm-openai-v0.23.0.tar.gz # nếu máy đích chưa có
# máy đích (image chandra-dla-api đã load từ trước)
docker load -i idp-parsing-service-0.2.0.tar.gz
docker load -i vllm-openai-v0.23.0.tar.gz
docker images | grep -E 'idp-parsing-service|vllm-openai|chandra-dla-api'
# Nếu không dùng deploy-offline.sh, nạp image API từ thư mục dự án:
cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256 && cd ..
docker load -i export/idp-parsing-service-0.2.0.tar.gz
docker compose up -d --no-build --pull never
```

51
deploy-offline.sh Executable file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Run all services on a server that already has the Chandra image loaded.
set -euo pipefail
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "${ROOT}"
test -f .env || { echo "Missing .env (copy and configure .env.example)" >&2; exit 1; }
MODEL_DIR="${ROOT}/qwen35-4b-model"
ARCHIVE="${1:-${KIE_WEIGHTS_ARCHIVE:-${ROOT}/qwen35-4b-weights.tar}}"
EXPECTED_SHA256="65efebd5f15f4db7dac8053bedbb8f38a75d1ac1c11b410db7691d308802bd13"
if [[ ! -d "${MODEL_DIR}" ]]; then
test -f "${ARCHIVE}" || { echo "Missing Qwen archive: ${ARCHIVE}" >&2; exit 1; }
actual_sha256="$(sha256sum "${ARCHIVE}" | cut -d ' ' -f 1)"
[[ "${actual_sha256}" == "${EXPECTED_SHA256}" ]] || {
echo "Qwen archive checksum mismatch: ${ARCHIVE}" >&2
exit 1
}
staging_dir="$(mktemp -d "${ROOT}/.qwen35-stage.XXXXXX")"
cleanup() { rm -rf -- "${staging_dir}"; }
trap cleanup EXIT
tar -xf "${ARCHIVE}" -C "${staging_dir}"
for required in config.json model.safetensors.index.json \
model.safetensors-00001-of-00002.safetensors \
model.safetensors-00002-of-00002.safetensors; do
test -s "${staging_dir}/${required}" || { echo "Missing Qwen file: ${required}" >&2; exit 1; }
done
mv -- "${staging_dir}" "${MODEL_DIR}"
trap - EXIT
fi
for required in config.json model.safetensors.index.json \
model.safetensors-00001-of-00002.safetensors \
model.safetensors-00002-of-00002.safetensors; do
test -s "${MODEL_DIR}/${required}" || { echo "Missing Qwen file: ${MODEL_DIR}/${required}" >&2; exit 1; }
done
(cd export && sha256sum -c idp-parsing-service-0.2.0.tar.gz.sha256)
docker load -i export/idp-parsing-service-0.2.0.tar.gz
docker compose config --quiet
docker compose config --images | sort -u | while IFS= read -r image; do
docker image inspect "${image}" >/dev/null || { echo "Missing Docker image: ${image}" >&2; exit 1; }
done
if ! docker compose up -d --no-build --pull never --wait \
--wait-timeout "${DEPLOY_WAIT_SECONDS:-1800}"; then
docker compose ps
echo "Deployment did not reach healthy state; inspect docker compose logs" >&2
exit 1
fi
docker compose ps

View File

@@ -11,6 +11,8 @@
# namenode/KDC phân giải theo /etc/hosts của host.
# kie chỉ khởi động sau khi chandra healthy để hai vLLM không đo bộ nhớ GPU cùng lúc;
# worker đợi cả hai model healthy mới nhận trang.
# Chandra đọc weight nhúng sẵn trong image tại /model. Qwen đọc weight đã giải nén
# từ qwen35-4b-weights.tar tại KIE_MODEL_DIR, dùng cùng image làm runtime vLLM.
x-gpu: &gpu
resources:
@@ -20,6 +22,8 @@ x-gpu: &gpu
device_ids: ["${GPU_DEVICE:-0}"] # như `docker run --gpus device=0`
capabilities: [gpu]
x-vllm-image: &vllm-image ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
x-vllm-env: &vllm-env
HF_HUB_OFFLINE: "1"
TRANSFORMERS_OFFLINE: "1"
@@ -41,7 +45,8 @@ x-app: &app
services:
chandra:
image: ${IMAGE_TAG:-chandra-dla-api:v2-20260906-024126}
image: *vllm-image
pull_policy: never
container_name: chandra-ocr
restart: unless-stopped
deploy: *gpu
@@ -50,8 +55,6 @@ services:
ports:
- "${PORT:-9222}:8000"
environment: *vllm-env
volumes:
- ${CHANDRA_MODEL_DIR:?dat CHANDRA_MODEL_DIR trong .env}:/model:ro
command:
- --model=/model
- --served-model-name=chandra
@@ -69,7 +72,9 @@ services:
healthcheck: *health
kie:
image: ${KIE_IMAGE:-vllm/vllm-openai:v0.23.0}
# Dùng runtime vLLM đã có trong image Chandra; mount Qwen đè lên /model.
image: *vllm-image
pull_policy: never
container_name: qwen-kie
restart: unless-stopped
depends_on:
@@ -82,7 +87,12 @@ services:
- "${KIE_PORT:-9224}:8000"
environment: *vllm-env
volumes:
- ${KIE_MODEL_DIR:?dat KIE_MODEL_DIR trong .env}:/model:ro
- type: bind
source: ${KIE_MODEL_DIR:?dat KIE_MODEL_DIR trong .env}
target: /model
read_only: true
bind:
create_host_path: false
command:
- --model=/model
- --served-model-name=qwen3.5-4b
@@ -91,6 +101,7 @@ services:
- --dtype=bfloat16
- --max-model-len=32768
- --max-num-seqs=16
- --max-num-batched-tokens=8192
- --gpu-memory-utilization=${KIE_GPU_UTIL:-0.3}
- --enable-prefix-caching
- --seed=42
@@ -109,6 +120,12 @@ services:
# Cùng đường dẫn trong và ngoài container; SQLite phải nằm trên đĩa local, không NFS.
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
command: ["uvicorn", "idp_service.api:app", "--host=${IDP_HOST:-0.0.0.0}", "--port=${IDP_PORT:-8001}"]
healthcheck:
test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:${IDP_PORT:-8001}/readyz', timeout=3)\""]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
worker:
<<: *app
@@ -126,5 +143,16 @@ services:
HDFS_KEYTAB: /opt/native-hdfs/conf/searchengine.headless.keytab
volumes:
- ${IDP_DATA_DIR:-/data/idp-runtime}:${IDP_DATA_DIR:-/data/idp-runtime}
- ${HDFS_NATIVE_DIR:-./native-hdfs}:/opt/native-hdfs:ro
- type: bind
source: ${HDFS_NATIVE_DIR:?dat HDFS_NATIVE_DIR trong .env}
target: /opt/native-hdfs
read_only: true
bind:
create_host_path: false
command: ["python", "-m", "idp_service.worker"]
healthcheck:
test: ["CMD-SHELL", "python -c \"import os, shutil, sqlite3; from idp_service.config import Settings; s=Settings(); db=sqlite3.connect(str(s.db_path), timeout=3); db.execute('SELECT 1'); db.close(); assert s.storage != 'hdfs_cli' or (shutil.which('hdfs') and os.access(os.environ.get('HDFS_KEYTAB', ''), os.R_OK))\""]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s

View File

@@ -4,6 +4,7 @@ import sqlite3
import time
from contextlib import contextmanager
from pathlib import Path
from threading import Lock
from uuid import uuid4
@@ -14,6 +15,9 @@ def retry_delay(attempt: int) -> int:
class Store:
def __init__(self, path: Path):
self.path = path
# Worker threads share this Store. Serialize their write transactions so
# idle queue polling does not make dozens of SQLite writers contend.
self._tx_lock = Lock()
path.parent.mkdir(parents=True, exist_ok=True)
self.init()
@@ -81,19 +85,20 @@ class Store:
@contextmanager
def tx(self):
db = self.connect()
try:
db.execute("BEGIN IMMEDIATE")
yield db
db.execute("COMMIT")
except BaseException:
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
if db.in_transaction:
db.execute("ROLLBACK")
raise
finally:
db.close()
with self._tx_lock:
db = self.connect()
try:
db.execute("BEGIN IMMEDIATE")
yield db
db.execute("COMMIT")
except BaseException:
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
if db.in_transaction:
db.execute("ROLLBACK")
raise
finally:
db.close()
@staticmethod
def as_dict(row):

View File

@@ -249,9 +249,12 @@ class Worker:
self.callback(job)
return True
def loop(self, step):
def loop(self, step, monitor_threads=()):
"""Lỗi tạm thời (SQLite locked, HDFS chập chờn) chỉ log rồi thử lại, không được giết luồng."""
while not self.stop.is_set():
dead = [thread.name for thread in monitor_threads if not thread.is_alive()]
if dead:
raise RuntimeError(f"Worker threads stopped unexpectedly: {', '.join(dead)}")
try:
if step():
continue
@@ -281,7 +284,7 @@ class Worker:
log.info("Worker started with %s OCR threads and %s callback threads",
self.settings.ocr_workers, self.settings.callback_workers)
try:
self.loop(self.coordinator_once)
self.loop(self.coordinator_once, threads)
finally:
self.stop.set()
for thread in threads:

View File

@@ -406,6 +406,63 @@ def test_locked_database_surfaces_and_does_not_kill_worker_thread(tmp_path, monk
blocker.execute("ROLLBACK")
def test_worker_store_serializes_write_transactions(tmp_path, monkeypatch):
import sqlite3
store = Store(settings_for(tmp_path).db_path)
monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(store.path, timeout=0.05,
isolation_level=None))
first_entered = Event()
release_first = Event()
second_started = Event()
second_done = Event()
errors = []
def first_writer():
try:
with store.tx():
first_entered.set()
release_first.wait(2)
except Exception as exc:
errors.append(exc)
def second_writer():
second_started.set()
try:
store.claim_page(1800, 2)
except Exception as exc:
errors.append(exc)
finally:
second_done.set()
first = Thread(target=first_writer)
second = Thread(target=second_writer)
first.start()
try:
assert first_entered.wait(2)
second.start()
assert second_started.wait(2)
assert not second_done.wait(0.1)
finally:
release_first.set()
first.join(2)
if second.ident is not None:
second.join(2)
assert second_done.is_set()
assert not errors
def test_worker_main_loop_exits_when_processing_thread_stops(tmp_path):
worker = Worker(settings_for(tmp_path))
dead_thread = Thread(name="dead-ocr")
try:
worker.loop(lambda: False, [dead_thread])
except RuntimeError as exc:
assert "dead-ocr" in str(exc)
else:
raise AssertionError("Worker must exit so Docker can restart it")
def test_real_http_ocr_and_callback(tmp_path):
callbacks = []
auth_headers = []
@@ -593,4 +650,3 @@ def test_voffice_decryption_rejects_wrong_key(tmp_path):
pass
else:
raise AssertionError("Invalid encrypted document was accepted")