468 lines
14 KiB
Python
468 lines
14 KiB
Python
"""持久批次执行任务租约、取消和事件测试。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
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_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,
|
|
)
|
|
|
|
|
|
def _user(db, name: str = "execution-user") -> User:
|
|
user = User(
|
|
username=name,
|
|
password_hash="h",
|
|
role="super_admin",
|
|
is_active=True,
|
|
)
|
|
db.add(user)
|
|
db.commit()
|
|
return user
|
|
|
|
|
|
def test_job_claim_heartbeat_cancel_and_finish(db):
|
|
user = _user(db)
|
|
job = enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_LOGIN_BATCH,
|
|
lane_scope=LANE_AUTH,
|
|
batch_id="exec-claim",
|
|
payload={"account_ids": [1]},
|
|
created_by=int(user.id),
|
|
)
|
|
db.commit()
|
|
|
|
claimed = claim_execution_jobs(
|
|
lane_scopes=(LANE_AUTH,),
|
|
owner="worker-a",
|
|
limit=1,
|
|
)
|
|
assert [row.id for row in claimed] == [job.id]
|
|
assert claimed[0].status == STATUS_RUNNING
|
|
assert claimed[0].attempt_count == 1
|
|
|
|
held, cancel_requested = heartbeat_execution_job(
|
|
job_id=int(job.id),
|
|
owner="worker-a",
|
|
)
|
|
assert held is True
|
|
assert cancel_requested is False
|
|
|
|
request_execution_cancel(db, batch_id="exec-claim")
|
|
db.commit()
|
|
held, cancel_requested = heartbeat_execution_job(
|
|
job_id=int(job.id),
|
|
owner="worker-a",
|
|
)
|
|
assert held is True
|
|
assert cancel_requested is True
|
|
assert finish_execution_job(
|
|
job_id=int(job.id),
|
|
owner="worker-a",
|
|
status=STATUS_CANCELLED,
|
|
)
|
|
|
|
|
|
def test_queued_job_cancel_is_immediate_and_token_scoped(db):
|
|
user = _user(db, "execution-cancel")
|
|
job = enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_LOGIN_BATCH,
|
|
lane_scope=LANE_AUTH,
|
|
batch_id="exec-cancel",
|
|
payload={},
|
|
created_by=int(user.id),
|
|
)
|
|
db.commit()
|
|
|
|
request_execution_cancel(db, batch_id=job.batch_id)
|
|
db.commit()
|
|
db.refresh(job)
|
|
|
|
assert job.status == STATUS_CANCELLED
|
|
assert job.cancel_requested_at is not None
|
|
|
|
|
|
def test_expired_running_job_is_recovered(db):
|
|
user = _user(db, "execution-recover")
|
|
job = enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_LOGIN_BATCH,
|
|
lane_scope=LANE_AUTH,
|
|
batch_id="exec-recover",
|
|
payload={},
|
|
created_by=int(user.id),
|
|
)
|
|
job.status = STATUS_RUNNING
|
|
job.lease_owner = "dead-worker"
|
|
job.lease_expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
|
job.attempt_count = 1
|
|
job.max_attempts = 2
|
|
db.commit()
|
|
|
|
claimed = claim_execution_jobs(
|
|
lane_scopes=(LANE_AUTH,),
|
|
owner="worker-b",
|
|
limit=1,
|
|
)
|
|
|
|
assert len(claimed) == 1
|
|
assert claimed[0].lease_owner == "worker-b"
|
|
assert claimed[0].attempt_count == 2
|
|
|
|
|
|
def test_execution_worker_runs_claimed_login_batch(db, monkeypatch):
|
|
user = _user(db, "execution-run")
|
|
job = enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_LOGIN_BATCH,
|
|
lane_scope=LANE_AUTH,
|
|
batch_id="exec-run",
|
|
payload={
|
|
"account_ids": [1],
|
|
"mode": "login",
|
|
"concurrency": 1,
|
|
},
|
|
created_by=int(user.id),
|
|
)
|
|
db.commit()
|
|
worker = execution_worker.ExecutionJobWorker()
|
|
claimed = claim_execution_jobs(
|
|
lane_scopes=(LANE_AUTH,),
|
|
owner=worker._owner,
|
|
limit=1,
|
|
)
|
|
assert [row.id for row in claimed] == [job.id]
|
|
seen: dict = {}
|
|
|
|
class FakeLoginRunner:
|
|
def __init__(self, **kwargs):
|
|
seen.update(kwargs)
|
|
|
|
def run(self):
|
|
seen["ran"] = True
|
|
|
|
monkeypatch.setattr(execution_worker, "LoginBatchRunner", FakeLoginRunner)
|
|
worker._run_job(int(job.id))
|
|
assert seen.get("ran") is True
|
|
|
|
db.rollback()
|
|
db.expire_all()
|
|
refreshed = db.get(ExecutionJob, job.id)
|
|
assert refreshed is not None
|
|
assert refreshed.status == "succeeded"
|
|
assert seen["ran"] is True
|
|
assert seen["batch_id"] == "exec-run"
|
|
|
|
|
|
def test_lane_slots_reserve_capacity_for_fulfillment(monkeypatch):
|
|
"""登录批次再慢也不能占满整个池子:履约 lane 必须留得住槽。"""
|
|
monkeypatch.setenv("EXECUTION_WORKER_MAX_JOBS", "2")
|
|
monkeypatch.setenv("EXECUTION_WORKER_LANES", "auth,fulfillment")
|
|
monkeypatch.delenv("EXECUTION_WORKER_AUTH_JOBS", raising=False)
|
|
monkeypatch.delenv("EXECUTION_WORKER_FULFILLMENT_JOBS", raising=False)
|
|
|
|
limits = execution_worker._lane_slot_limits()
|
|
assert limits[LANE_AUTH] == 1
|
|
assert limits[LANE_FULFILLMENT] == 2
|
|
# 领取顺序:履约优先,登录只用剩下的槽
|
|
assert execution_worker._lane_claim_order()[0] == LANE_FULFILLMENT
|
|
|
|
|
|
def test_auth_batches_cannot_starve_fulfillment_lane(db, monkeypatch):
|
|
"""两个登录批次在跑时,履约批次仍然能拿到执行槽(总槽位不变)。"""
|
|
user = _user(db, "lane-isolation")
|
|
for index in range(2):
|
|
enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_LOGIN_BATCH,
|
|
lane_scope=LANE_AUTH,
|
|
batch_id=f"lane-auth-{index}",
|
|
payload={"account_ids": [1], "mode": "login", "concurrency": 1},
|
|
created_by=int(user.id),
|
|
)
|
|
enqueue_execution_job(
|
|
db,
|
|
job_type=JOB_DOUYU_BATCH,
|
|
lane_scope=LANE_FULFILLMENT,
|
|
batch_id="lane-fulfillment-1",
|
|
payload={"task_type": "elite_exchange", "payload": {}},
|
|
created_by=int(user.id),
|
|
)
|
|
db.commit()
|
|
|
|
monkeypatch.setenv("EXECUTION_WORKER_MAX_JOBS", "2")
|
|
monkeypatch.setenv("EXECUTION_WORKER_LANES", "auth,fulfillment")
|
|
monkeypatch.delenv("EXECUTION_WORKER_AUTH_JOBS", raising=False)
|
|
monkeypatch.delenv("EXECUTION_WORKER_FULFILLMENT_JOBS", raising=False)
|
|
|
|
release = threading.Event()
|
|
worker = execution_worker.ExecutionJobWorker()
|
|
|
|
def fake_run_job(_job_id: int) -> None:
|
|
release.wait(10)
|
|
|
|
monkeypatch.setattr(worker, "_run_job", fake_run_job)
|
|
worker.start()
|
|
try:
|
|
deadline = time.monotonic() + 10
|
|
lanes: list[str] = []
|
|
while time.monotonic() < deadline:
|
|
# 结束当前事务再查:worker 在**另一个连接**上把任务改成 running,
|
|
# 旧快照看不到(MySQL REPEATABLE READ)。
|
|
db.rollback()
|
|
rows = (
|
|
db.query(ExecutionJob)
|
|
.filter(ExecutionJob.status == STATUS_RUNNING)
|
|
.all()
|
|
)
|
|
lanes = [row.lane_scope for row in rows]
|
|
if LANE_FULFILLMENT in lanes and LANE_AUTH in lanes:
|
|
break
|
|
time.sleep(0.2)
|
|
assert LANE_AUTH in lanes
|
|
assert LANE_FULFILLMENT in lanes, "履约批次被登录批次饿死了"
|
|
# auth lane 最多占 1 个槽,第二个登录批次必须留在队列里
|
|
assert lanes.count(LANE_AUTH) == 1
|
|
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,
|
|
}
|