fix(worker): 优化连接池容量拆分、并发入队与事件写入

This commit is contained in:
yml
2026-11-29 11:24:35 +08:00
parent 1d92fa6d53
commit 2ea105a924
18 changed files with 956 additions and 207 deletions
@@ -614,3 +614,60 @@ def test_default_enabled_job_is_created_enabled(db, monkeypatch):
.one()
)
assert row.enabled is True
def test_multi_commodity_refresh_handles_missing_and_due_states(db):
from web.backend.services.platform_fulfillment.account_selector import (
capability_refresh_candidate_accounts,
)
missing_one = _account(db, "cap-multi-missing-one")
fresh_storehome_missing = _account(db, "cap-multi-fresh-sh")
due_one = _account(db, "cap-multi-due-one")
all_fresh = _account(db, "cap-multi-all-fresh")
# missing_one 只有 C1 新鲜,缺少 C2,且 storehome 过期 -> 应被选中
_state(db, missing_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
# fresh_storehome_missing 只有 C1 新鲜,缺少 C2,但 storehome 新鲜 -> 不应重复补扫
_state(
db,
fresh_storehome_missing,
commodity_id="C1",
valid_until=NOW + timedelta(hours=1),
)
db.add(
AccountSyncState(
account_id=fresh_storehome_missing.id,
platform="douyu",
domain="storehome",
status="success",
last_success_at=NOW,
valid_until=NOW + timedelta(hours=1),
)
)
# due_one 两个都有,但 C2 已过期 -> 即使 storehome 新鲜也应被选中
_state(db, due_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
_state(db, due_one, commodity_id="C2", valid_until=NOW - timedelta(minutes=1))
db.add(
AccountSyncState(
account_id=due_one.id,
platform="douyu",
domain="storehome",
status="success",
last_success_at=NOW,
valid_until=NOW + timedelta(hours=1),
)
)
# all_fresh 两个都新鲜 -> 不应被选中
_state(db, all_fresh, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
_state(db, all_fresh, commodity_id="C2", valid_until=NOW + timedelta(hours=1))
db.commit()
selected = capability_refresh_candidate_accounts(
db,
commodity_ids=["C1", "C2"],
scope="elite",
limit=10,
now=NOW,
)
assert {row.id for row in selected} == {missing_one.id, due_one.id}
+77
View File
@@ -536,3 +536,80 @@ def test_login_quota_configuration_route_updates_all_categories(db):
assert updated["relogin_high_value_daily_limit"] == 240
assert updated["failure_pause_ratio"] == 35
assert loaded["login_concurrency"] == 3
def test_enqueue_account_work_survives_repeatable_read_integrity_race(db):
from tests.support.db import make_test_session
account = _account("queue-race-account")
db.add(account)
db.commit()
# 先开启 db 的 REPEATABLE READ 快照,再由另一会话提交同一工作项
assert db.query(AccountWorkItem).count() == 0
other = make_test_session()
try:
committed = enqueue_account_work(
other,
account_id=account.id,
work_type="storehome_sync",
priority=20,
)
other.commit()
committed_id = int(committed.id)
finally:
other.close()
# db 的旧快照看不到 committed,INSERT 会撞唯一键,但不能抛 NoResultFound
reused = enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
assert int(reused.id) == committed_id
db.commit()
# 如果并发项在另一会话中刚被完成并清空 active_dedupe_key,再次撞锁时也能重新入队
other = make_test_session()
try:
current = other.get(AccountWorkItem, committed_id)
assert current is not None
complete_account_work(other, current)
other.commit()
finally:
other.close()
# 人工模拟同一快照里先误判存在冲突后被完成:重新入队应得到一条新记录
fresh = enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
db.commit()
assert int(fresh.id) != committed_id
def test_enqueue_account_work_raises_integrity_error_when_retries_exhausted(
db, monkeypatch
):
import pytest
from sqlalchemy.exc import IntegrityError
account = _account("queue-race-exhausted")
db.add(account)
db.commit()
def always_conflict() -> None:
raise IntegrityError("INSERT", {}, Exception("Duplicate entry"))
monkeypatch.setattr(db, "flush", always_conflict)
with pytest.raises(IntegrityError):
enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
+41
View File
@@ -2128,3 +2128,44 @@ def test_poll_bind_role_once_records_mismatched_cjm_and_ignores_bound_action_rol
assert "妎䏓" in task.message
assert task.result["last_mismatched_role"]["role_name"] == "妎朊"
assert [m["role_name"] for m in task.result["mismatched_roles"]] == ["妎朊"]
def test_mark_task_reuses_worker_session_without_nested_checkout(db, monkeypatch):
from web.backend import database as database_module
from web.backend.services.platform_fulfillment import service as pf_service
_, _, task = _fixtures(db, status="running")
task.task_type = "confirm_bind"
task.handbook_scope = "elite"
db.commit()
monkeypatch.setattr(
database_module,
"WorkerSessionLocal",
lambda: (_ for _ in ()).throw(AssertionError("收尾钩子不能再嵌套借用 WorkerSessionLocal")),
)
seen_dbs: list[tuple[str, object]] = []
monkeypatch.setattr(
pf_service,
"sync_task_from_binding_runner",
lambda session, *, douyu_task_id: seen_dbs.append(("sync", session)) or 0,
)
monkeypatch.setattr(
pf_service,
"verify_active_binding_for_douyu_task",
lambda session, *, douyu_task_id, actor_id=None: seen_dbs.append(("verify", session)) or None,
)
monkeypatch.setattr(
pf_service,
"refresh_active_exchange_eligibility_for_account",
lambda session, *, account_id, scope, actor_id=None: seen_dbs.append(("eligibility", session)) or None,
)
runner = DouyuBatchRunner(db, task.batch_id, "confirm_bind", close_db=False)
runner._mark_task(db, task, "success", "确认绑定成功")
assert seen_dbs == [
("sync", db),
("verify", db),
("eligibility", db),
]
+224 -1
View File
@@ -9,14 +9,15 @@ from datetime import UTC, datetime, timedelta
from web.backend.models import ExecutionJob, User
from web.backend.services import execution_worker
from web.backend.services.execution_jobs import (
JOB_LOGIN_BATCH,
JOB_DOUYU_BATCH,
JOB_LOGIN_BATCH,
LANE_AUTH,
LANE_FULFILLMENT,
STATUS_CANCELLED,
STATUS_RUNNING,
claim_execution_jobs,
enqueue_execution_job,
execution_events_after,
finish_execution_job,
heartbeat_execution_job,
request_execution_cancel,
@@ -242,3 +243,225 @@ def test_auth_batches_cannot_starve_fulfillment_lane(db, monkeypatch):
finally:
release.set()
worker.stop()
def test_execution_worker_batches_events_and_closes_douyu_db(db, monkeypatch):
user = _user(db, "execution-batch-events")
job = enqueue_execution_job(
db,
job_type=JOB_DOUYU_BATCH,
lane_scope=LANE_FULFILLMENT,
batch_id="exec-batch-events",
payload={"task_type": "query_points", "payload": {}, "concurrency": 1},
created_by=int(user.id),
)
db.commit()
worker = execution_worker.ExecutionJobWorker()
claimed = claim_execution_jobs(
lane_scopes=(LANE_FULFILLMENT,),
owner=worker._owner,
limit=1,
)
assert [row.id for row in claimed] == [job.id]
seen: dict = {}
class FakeDouyuRunner:
def __init__(self, **kwargs):
seen.update(kwargs)
def run(self):
seen["log_sink"]({"level": "info", "message": "step-1"})
seen["log_sink"]({"level": "info", "message": "step-2"})
seen["ran"] = True
monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FakeDouyuRunner)
worker._event_writer.start()
try:
worker._run_job(int(job.id))
finally:
worker._event_writer.stop()
assert seen.get("ran") is True
assert seen.get("close_db") is True
db.rollback()
events = execution_events_after(db, batch_id="exec-batch-events")
assert [item.message for item in events] == ["step-1", "step-2"]
def test_douyu_batch_runner_closes_coordinator_session_before_task_execution(
db, monkeypatch
):
from tests.support.db import make_test_session
from web.backend.models import Account, DouyuTask
from web.backend.services.douyu_runner import DouyuBatchRunner
user = _user(db, "douyu-close-session")
account = Account(
username="douyu-close-acc",
password="p",
email="douyu-close-acc@example.com",
email_password="ep",
)
db.add(account)
db.flush()
task = DouyuTask(
batch_id="douyu-close-batch",
account_id=account.id,
task_type="query_points",
status="planned",
created_by=user.id,
)
db.add(task)
db.commit()
coord_db = make_test_session()
closed = {"called": False}
orig_close = coord_db.close
def tracked_close() -> None:
closed["called"] = True
orig_close()
monkeypatch.setattr(coord_db, "close", tracked_close)
runner = DouyuBatchRunner(
coord_db,
"douyu-close-batch",
"query_points",
close_db=True,
)
observed_closed_during_exec: list[bool] = []
monkeypatch.setattr(
runner,
"_execute_one",
lambda _task_id, _cfg, _total: observed_closed_during_exec.append(
closed["called"]
),
)
runner.run()
assert observed_closed_during_exec == [True]
assert closed["called"] is True
def test_event_batch_writer_flush_timeout_preserves_fifo_and_bounds_time(monkeypatch):
from web.backend.services import execution_jobs
flushed_messages: list[str] = []
gate = threading.Event()
first_started = threading.Event()
def fake_append(events: list[dict]) -> bool:
messages = [str(item["message"]) for item in events]
if "in-flight" in messages:
first_started.set()
gate.wait(2)
flushed_messages.extend(messages)
return True
monkeypatch.setattr(execution_jobs, "append_execution_events", fake_append)
writer = execution_jobs.ExecutionEventBatchWriter(flush_interval=0.05, batch_size=1)
writer.start()
try:
writer.enqueue(job_id=1, batch_id="b1", level="info", message="in-flight")
assert first_started.wait(1)
writer.enqueue(job_id=1, batch_id="b1", level="info", message="queued-after")
# 后台线程仍在写第一批时,flush 必须在 timeout 附近立即返回 False,且不能插队写 queued-after
started_at = time.monotonic()
assert writer.flush(timeout=0.06) is False
elapsed = time.monotonic() - started_at
assert elapsed < 0.25
assert flushed_messages == []
# stop 超时同样立即返回 False,不丢线程与队列引用
assert writer.stop(timeout=0.05) is False
finally:
gate.set()
assert writer.stop(timeout=2.0) is True
# 严格按 FIFO 顺序先落第一批,再落队列后续批
assert flushed_messages == ["in-flight", "queued-after"]
# 线程未运行时残留事件也按 FIFO 同步排空
writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-1")
writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-2")
assert writer.flush(timeout=0.05) is True
assert flushed_messages == ["in-flight", "queued-after", "tail-1", "tail-2"]
def test_execution_worker_error_event_stays_after_step_logs(db, monkeypatch):
user = _user(db, "execution-error-order")
job = enqueue_execution_job(
db,
job_type=JOB_DOUYU_BATCH,
lane_scope=LANE_FULFILLMENT,
batch_id="exec-error-order",
payload={"task_type": "query_points", "payload": {}, "concurrency": 1},
created_by=int(user.id),
)
db.commit()
worker = execution_worker.ExecutionJobWorker()
claimed = claim_execution_jobs(
lane_scopes=(LANE_FULFILLMENT,),
owner=worker._owner,
limit=1,
)
assert [row.id for row in claimed] == [job.id]
class FailingDouyuRunner:
def __init__(self, **kwargs):
self.log_sink = kwargs["log_sink"]
def run(self):
self.log_sink({"level": "info", "message": "step-1"})
self.log_sink({"level": "info", "message": "step-2"})
raise RuntimeError("boom")
monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FailingDouyuRunner)
worker._event_writer.start()
try:
worker._run_job(int(job.id))
finally:
assert worker._event_writer.stop() is True
db.rollback()
events = execution_events_after(db, batch_id="exec-error-order")
assert [item.message for item in events] == [
"step-1",
"step-2",
"RuntimeError: boom",
]
def test_resolve_pool_limits_by_runtime_role(monkeypatch):
from web.backend.database import resolve_pool_limits
monkeypatch.setenv("DB_POOL_SIZE", "20")
monkeypatch.setenv("DB_MAX_OVERFLOW", "20")
monkeypatch.setenv("WORKER_DB_POOL_SIZE", "24")
monkeypatch.setenv("WORKER_DB_MAX_OVERFLOW", "16")
api_limits = resolve_pool_limits("api")
assert api_limits == {
"api_pool_size": 20,
"api_max_overflow": 20,
"worker_pool_size": 4,
"worker_max_overflow": 4,
}
bg_limits = resolve_pool_limits("background")
assert bg_limits == {
"api_pool_size": 2,
"api_max_overflow": 2,
"worker_pool_size": 24,
"worker_max_overflow": 16,
}
all_limits = resolve_pool_limits("all")
assert all_limits == {
"api_pool_size": 20,
"api_max_overflow": 20,
"worker_pool_size": 24,
"worker_max_overflow": 16,
}