Fix worker db

This commit is contained in:
2026-09-29 05:39:45 +00:00
parent 73c51ed1cd
commit 498a22ab61
8 changed files with 241 additions and 43 deletions

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: