fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性
This commit is contained in:
@@ -0,0 +1,391 @@
|
||||
"""斗鱼相关 P0 + P1 修复回归测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import Future
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import inspect
|
||||
|
||||
from core.douyu import DouyuActivityClient, FishFinRechargeClient, FishFinRechargeConfig
|
||||
from core.douyu.email_verifier import EmailVerifier
|
||||
from core.douyu.login import DouyuLogin
|
||||
from core.douyu.proxy_verifier import verify_proxies_concurrent
|
||||
from tests.support.db import get_test_engine, init_test_schema, make_test_session
|
||||
from web.backend.database import release_idle_session
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountSyncRun,
|
||||
AccountSyncState,
|
||||
DouyuTask,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.services import account_sync_service
|
||||
from web.backend.services.douyu_runner import DouyuBatchRunner
|
||||
from web.backend.services.task_runtime import TaskLane
|
||||
|
||||
|
||||
class _TestBase:
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
init_test_schema(self.engine)
|
||||
self.session = make_test_session(self.engine)
|
||||
self.user = User(username="p0p1-admin", password_hash="h", role="super_admin")
|
||||
self.session.add(self.user)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="p0p1-acc",
|
||||
password="p",
|
||||
email="p0p1@example.com",
|
||||
email_password="ep",
|
||||
uid="10086",
|
||||
cookie="acf_uid=10086; acf_ltkid=1; acf_username=u",
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.commit()
|
||||
self.account_id = int(self.account.id)
|
||||
self.user_id = int(self.user.id)
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
|
||||
class TestLockOrderAndSingleWriteSync(_TestBase):
|
||||
def test_record_sync_success_locks_account_and_inserts_single_finished_run(self):
|
||||
events: list[str] = []
|
||||
original_lock = account_sync_service.lock_account_row
|
||||
|
||||
def spy_lock(db, account_id):
|
||||
events.append(f"lock:{account_id}")
|
||||
return original_lock(db, account_id)
|
||||
|
||||
observed_at = datetime.now(UTC)
|
||||
with patch.object(account_sync_service, "lock_account_row", side_effect=spy_lock):
|
||||
run = account_sync_service.record_sync_success(
|
||||
self.session,
|
||||
account_id=self.account_id,
|
||||
domain="points",
|
||||
source="test.sync",
|
||||
observed_at=observed_at,
|
||||
raw_payload={"points": 1200},
|
||||
task_id=42,
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
assert events == [f"lock:{self.account_id}"]
|
||||
assert run.observed_at == observed_at
|
||||
runs = (
|
||||
self.session.query(AccountSyncRun)
|
||||
.filter(AccountSyncRun.account_id == self.account_id)
|
||||
.all()
|
||||
)
|
||||
assert len(runs) == 1
|
||||
assert runs[0].status == "success"
|
||||
assert runs[0].finished_at is not None
|
||||
state = (
|
||||
self.session.query(AccountSyncState)
|
||||
.filter(
|
||||
AccountSyncState.account_id == self.account_id,
|
||||
AccountSyncState.domain == "points",
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert state.status == "success"
|
||||
|
||||
|
||||
class TestSessionReleaseAndClientLifecycle(_TestBase):
|
||||
def test_release_idle_session_respects_managed_and_dirty_flags(self):
|
||||
# Unmanaged test session must never be rolled back.
|
||||
assert release_idle_session(self.session) is False
|
||||
|
||||
# Dirty managed session must not drop pending changes.
|
||||
self.session.info["managed_worker_session"] = True
|
||||
self.account.nickname = "dirty-check"
|
||||
assert release_idle_session(self.session) is False
|
||||
self.session.rollback()
|
||||
|
||||
# Clean managed session gets rolled back (connection returned to pool).
|
||||
self.session.info["managed_request_session"] = True
|
||||
assert release_idle_session(self.session) is True
|
||||
|
||||
def test_runner_releases_preflight_db_and_closes_tracked_clients(self):
|
||||
task = DouyuTask(
|
||||
batch_id="b-session-rel",
|
||||
account_id=self.account_id,
|
||||
task_type="query_points",
|
||||
handbook_scope="elite",
|
||||
status="pending",
|
||||
created_by=self.user_id,
|
||||
)
|
||||
self.session.add(task)
|
||||
self.session.commit()
|
||||
task_id = int(task.id)
|
||||
|
||||
closed_clients: list[DouyuActivityClient] = []
|
||||
|
||||
class _SpyClient(DouyuActivityClient):
|
||||
def close(self) -> None:
|
||||
closed_clients.append(self)
|
||||
super().close()
|
||||
|
||||
preflight_db = make_test_session(self.engine)
|
||||
worker_db = make_test_session(self.engine)
|
||||
close_flags: list[bool] = []
|
||||
original_preflight_close = preflight_db.close
|
||||
original_worker_close = worker_db.close
|
||||
|
||||
def track_preflight_close():
|
||||
close_flags.append(True)
|
||||
original_preflight_close()
|
||||
|
||||
def track_worker_close():
|
||||
original_worker_close()
|
||||
|
||||
preflight_db.close = track_preflight_close # type: ignore[method-assign]
|
||||
worker_db.close = track_worker_close # type: ignore[method-assign]
|
||||
session_iter = iter([preflight_db, worker_db])
|
||||
|
||||
def fake_probe_session(cookie: str, *, checker=None):
|
||||
# Preflight DB must already be closed before external HTTP cookie check runs.
|
||||
assert close_flags == [True]
|
||||
return {"status": "valid", "message": "ok", "detail": {"nickname": "n"}}
|
||||
|
||||
runner = DouyuBatchRunner(
|
||||
self.session, "b-session-rel", "query_points", close_db=False
|
||||
)
|
||||
|
||||
def fake_handler(db, t, acc, cookie, cfg):
|
||||
client = runner._client(cookie)
|
||||
assert isinstance(client, _SpyClient)
|
||||
runner._mark_task(db, t, "success", "完成")
|
||||
|
||||
with (
|
||||
patch(
|
||||
"web.backend.services.douyu_runner.SessionLocal",
|
||||
side_effect=lambda: next(session_iter),
|
||||
),
|
||||
patch(
|
||||
"web.backend.services.douyu_runner.probe_session",
|
||||
side_effect=fake_probe_session,
|
||||
),
|
||||
patch(
|
||||
"web.backend.services.douyu_runner_core.activity_client",
|
||||
side_effect=lambda c, **_kw: _SpyClient(c),
|
||||
),
|
||||
patch.object(runner, "_execute_query_points", side_effect=fake_handler),
|
||||
):
|
||||
runner._execute_one_with_slot(task_id, {"manual_id": "1"}, 1)
|
||||
|
||||
assert len(closed_clients) == 1
|
||||
|
||||
|
||||
class TestRunnerQueueWaitAndTaskId(_TestBase):
|
||||
def test_run_logs_true_queue_wait_and_correct_task_id(self):
|
||||
t1 = DouyuTask(
|
||||
batch_id="b-queue-wait",
|
||||
account_id=self.account_id,
|
||||
task_type="query_points",
|
||||
handbook_scope="elite",
|
||||
status="planned",
|
||||
created_by=self.user_id,
|
||||
)
|
||||
t2 = DouyuTask(
|
||||
batch_id="b-queue-wait",
|
||||
account_id=self.account_id,
|
||||
task_type="query_points",
|
||||
handbook_scope="elite",
|
||||
status="planned",
|
||||
created_by=self.user_id,
|
||||
)
|
||||
self.session.add_all([t1, t2])
|
||||
self.session.commit()
|
||||
id1, id2 = int(t1.id), int(t2.id)
|
||||
|
||||
runner = DouyuBatchRunner(
|
||||
self.session,
|
||||
"b-queue-wait",
|
||||
"query_points",
|
||||
concurrency=2,
|
||||
close_db=False,
|
||||
)
|
||||
logs: list[tuple[str, str]] = []
|
||||
runner._push_log = lambda level, msg: logs.append((level, msg)) # type: ignore[method-assign]
|
||||
|
||||
def fake_execute(task_id: int, config: dict, total: int) -> None:
|
||||
now = time.monotonic()
|
||||
if int(task_id) == id1:
|
||||
runner._task_started_at[int(task_id)] = now
|
||||
raise RuntimeError("boom-first")
|
||||
# Simulate task 2 having waited 6.5s in the lane queue before starting.
|
||||
runner._task_started_at[int(task_id)] = now + 6.5
|
||||
|
||||
def fake_submit(lane: TaskLane, fn, *args, **_kwargs):
|
||||
fut: Future[None] = Future()
|
||||
|
||||
def _run():
|
||||
try:
|
||||
fn(args[0], args[1], args[2])
|
||||
fut.set_result(None)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fut.set_exception(exc)
|
||||
|
||||
threading.Thread(target=_run, daemon=True).start()
|
||||
return fut
|
||||
|
||||
with (
|
||||
patch.object(runner, "_execute_one", side_effect=fake_execute),
|
||||
patch("web.backend.services.douyu_runner.submit", side_effect=fake_submit),
|
||||
):
|
||||
runner.run()
|
||||
|
||||
error_logs = [msg for lvl, msg in logs if lvl == "error"]
|
||||
assert any(f"task_id={id1}" in msg for msg in error_logs), error_logs
|
||||
assert all(f"task_id={id2}" not in msg for msg in error_logs)
|
||||
info_logs = [msg for lvl, msg in logs if lvl == "info"]
|
||||
assert any(f"task_id={id2}" in msg and "排队" in msg for msg in info_logs), info_logs
|
||||
assert all(f"task_id={id1}" not in msg or "排队" not in msg for msg in info_logs)
|
||||
|
||||
|
||||
class TestSlowQueryIndexesAndRoleNorm(_TestBase):
|
||||
def test_role_norm_virtual_column_and_new_indexes_exist(self):
|
||||
row = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="p0p1-ord",
|
||||
source_order_item_id="p0p1-item",
|
||||
source_fulfillment_id="p0p1-ff",
|
||||
platform_order_id="ORD-P0P1",
|
||||
provider="91kaquan",
|
||||
shop_id="s1",
|
||||
shop_name="shop",
|
||||
sku_code="sku",
|
||||
sku_name="sku",
|
||||
internal_sku_key="sku",
|
||||
quantity=1,
|
||||
order_amount_fen=100,
|
||||
target_platform="douyu",
|
||||
scope="elite",
|
||||
customer_role_name=" MiXeD_Role_名称 ",
|
||||
flow_version=2,
|
||||
)
|
||||
self.session.add(row)
|
||||
self.session.commit()
|
||||
|
||||
found = (
|
||||
self.session.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.customer_role_norm == "mixed_role_名称")
|
||||
.one()
|
||||
)
|
||||
assert found.id == row.id
|
||||
|
||||
inspector = inspect(self.engine)
|
||||
event_indexes = {idx["name"] for idx in inspector.get_indexes("account_events")}
|
||||
assert "ix_account_events_event_subject_occurred" in event_indexes
|
||||
assert "ix_account_events_type_occurred" in event_indexes
|
||||
|
||||
sync_indexes = {idx["name"] for idx in inspector.get_indexes("account_sync_runs")}
|
||||
assert "ix_account_sync_runs_trend_cover" in sync_indexes
|
||||
|
||||
commodity_indexes = {
|
||||
idx["name"] for idx in inspector.get_indexes("account_commodity_states")
|
||||
}
|
||||
assert "ix_account_commodity_skin_options" in commodity_indexes
|
||||
|
||||
pf_indexes = {
|
||||
idx["name"] for idx in inspector.get_indexes("platform_fulfillment_tasks")
|
||||
}
|
||||
assert "ix_platform_fulfillment_role_norm" in pf_indexes
|
||||
|
||||
|
||||
class TestProxyNonBlockingAndHttpSessionClosing:
|
||||
def test_verify_proxies_concurrent_returns_fast_without_waiting_slow_probe(self):
|
||||
def fake_verify(proxy_url: str, timeout=(3, 5)):
|
||||
if "slow" in proxy_url:
|
||||
time.sleep(2.0)
|
||||
return False, "timeout"
|
||||
return True, "ok"
|
||||
|
||||
started = time.monotonic()
|
||||
with patch(
|
||||
"core.douyu.proxy_verifier.verify_proxy_url", side_effect=fake_verify
|
||||
):
|
||||
proxy, msg = verify_proxies_concurrent(
|
||||
["http://slow:1", "http://fast:2"],
|
||||
return_all=False,
|
||||
)
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
assert proxy == "http://fast:2"
|
||||
assert msg == "ok"
|
||||
assert elapsed < 0.8
|
||||
|
||||
def test_clients_close_owned_http_sessions(self):
|
||||
activity = DouyuActivityClient("acf_uid=1")
|
||||
activity.session.close = MagicMock() # type: ignore[method-assign]
|
||||
with activity:
|
||||
pass
|
||||
activity.session.close.assert_called_once()
|
||||
|
||||
owned_recharge = FishFinRechargeClient(
|
||||
FishFinRechargeConfig(
|
||||
base_url="https://supplier.example",
|
||||
app_id="app",
|
||||
app_secret="sec",
|
||||
)
|
||||
)
|
||||
owned_recharge.session.close = MagicMock() # type: ignore[method-assign]
|
||||
with owned_recharge:
|
||||
pass
|
||||
owned_recharge.session.close.assert_called_once()
|
||||
|
||||
external_sess = MagicMock()
|
||||
borrowed_recharge = FishFinRechargeClient(
|
||||
FishFinRechargeConfig(
|
||||
base_url="https://supplier.example",
|
||||
app_id="app",
|
||||
app_secret="sec",
|
||||
),
|
||||
session=external_sess,
|
||||
)
|
||||
borrowed_recharge.close()
|
||||
external_sess.close.assert_not_called()
|
||||
|
||||
verifier = EmailVerifier(username="u@e.com", password="p")
|
||||
mock_rc_sess = MagicMock()
|
||||
verifier._rc_session = mock_rc_sess
|
||||
verifier._rc_logged_in = True
|
||||
verifier.disconnect()
|
||||
mock_rc_sess.close.assert_called_once()
|
||||
|
||||
# Failed login attempt must still close its temporary requests.Session.
|
||||
temp_sess = MagicMock()
|
||||
temp_sess.get.return_value = SimpleNamespace(text="no-token-here")
|
||||
with (
|
||||
patch("core.douyu.email_verifier.requests.Session", return_value=temp_sess),
|
||||
):
|
||||
ok, pwd_err = verifier._try_roundcube_login("wrong")
|
||||
assert (ok, pwd_err) == (False, False)
|
||||
temp_sess.close.assert_called_once()
|
||||
|
||||
loginer = DouyuLogin(
|
||||
SimpleNamespace(
|
||||
username="u",
|
||||
password="p",
|
||||
email="e@example.com",
|
||||
email_password="ep",
|
||||
email_imap_server="",
|
||||
email_imap_port=993,
|
||||
email_imap_ssl=True,
|
||||
)
|
||||
)
|
||||
loginer.session.close = MagicMock() # type: ignore[method-assign]
|
||||
with loginer:
|
||||
pass
|
||||
loginer.session.close.assert_called_once()
|
||||
|
||||
assert pytest is not None
|
||||
@@ -0,0 +1,303 @@
|
||||
"""P2 运维与队列可观测性优化回归测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from web.backend import background_runtime
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AutomationJob,
|
||||
DouyuTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.routers import automation as automation_router
|
||||
from web.backend.routers import douyu as douyu_router
|
||||
from web.backend.services import (
|
||||
binding_poll_scheduler,
|
||||
execution_worker,
|
||||
payment_poll_scheduler,
|
||||
task_runtime,
|
||||
)
|
||||
from web.backend.services.account_observability import account_platform_status
|
||||
from web.backend.services.account_work_queue import (
|
||||
STALE_RUNNING_SECONDS,
|
||||
enqueue_account_work,
|
||||
recover_stale_running_account_work,
|
||||
)
|
||||
from web.backend.services.automation.jobs import account_sync_queue
|
||||
from web.backend.services.douyu_runner_core import DouyuBatchRegistry
|
||||
from web.backend.services.execution_jobs import (
|
||||
JOB_DOUYU_BATCH,
|
||||
LANE_FULFILLMENT,
|
||||
ExecutionEventBatchWriter,
|
||||
enqueue_execution_job,
|
||||
)
|
||||
|
||||
|
||||
def _seed_user_and_account(db, suffix: str) -> tuple[User, Account]:
|
||||
user = User(username=f"p2-user-{suffix}", password_hash="h", role="super_admin")
|
||||
account = Account(
|
||||
username=f"p2-acc-{suffix}",
|
||||
password="p",
|
||||
email=f"p2-{suffix}@example.com",
|
||||
email_password="ep",
|
||||
uid=f"99{suffix}"[:32],
|
||||
cookie="acf_uid=99; acf_ltkid=1; acf_username=p2",
|
||||
)
|
||||
db.add_all([user, account])
|
||||
db.commit()
|
||||
return user, account
|
||||
|
||||
|
||||
def test_cleanup_orphan_tasks_preserves_durable_execution_job_batches(db):
|
||||
user, account = _seed_user_and_account(db, "orphan")
|
||||
enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_DOUYU_BATCH,
|
||||
lane_scope=LANE_FULFILLMENT,
|
||||
batch_id="durable-active-batch",
|
||||
payload={"task_type": "query_points", "payload": {}},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
durable_task = DouyuTask(
|
||||
batch_id="durable-active-batch",
|
||||
account_id=int(account.id),
|
||||
task_type="query_points",
|
||||
status="running",
|
||||
message="执行中",
|
||||
created_by=int(user.id),
|
||||
)
|
||||
orphan_task = DouyuTask(
|
||||
batch_id="lost-orphan-batch",
|
||||
account_id=int(account.id),
|
||||
task_type="query_points",
|
||||
status="running",
|
||||
message="执行中",
|
||||
created_by=int(user.id),
|
||||
)
|
||||
db.add_all([durable_task, orphan_task])
|
||||
db.commit()
|
||||
|
||||
result = douyu_router.cleanup_orphan_tasks(db=db, current=user)
|
||||
|
||||
db.refresh(durable_task)
|
||||
db.refresh(orphan_task)
|
||||
assert result["cleaned"] == 1
|
||||
assert durable_task.status == "running"
|
||||
assert orphan_task.status == "stopped"
|
||||
|
||||
|
||||
def test_douyu_batch_registry_evicts_expired_finished_batches(monkeypatch):
|
||||
monkeypatch.setenv("DOUYU_BATCH_REGISTRY_FINISHED_TTL_SECONDS", "10")
|
||||
registry = DouyuBatchRegistry()
|
||||
dummy_runner = SimpleNamespace(stop=lambda: None)
|
||||
|
||||
registry.register("active-batch", None, None, dummy_runner)
|
||||
registry.register("expired-batch", None, None, dummy_runner)
|
||||
registry.register("recent-finished-batch", None, None, dummy_runner)
|
||||
|
||||
registry.mark_finished("expired-batch")
|
||||
registry.mark_finished("recent-finished-batch")
|
||||
registry.get("expired-batch")["updated_at"] = time.time() - 30
|
||||
|
||||
stats = registry.stats()
|
||||
|
||||
assert registry.get("expired-batch") is None
|
||||
assert registry.get("recent-finished-batch") is not None
|
||||
assert registry.active_ids() == {"active-batch"}
|
||||
assert stats == {"active": 1, "finished": 1, "total": 2}
|
||||
|
||||
|
||||
def test_task_runtime_lane_stats_tracks_active_queued_and_rejected(monkeypatch):
|
||||
monkeypatch.setenv("TASK_LANE_COLLAB_RECOMMEND_WORKERS", "1")
|
||||
monkeypatch.setenv("TASK_LANE_COLLAB_RECOMMEND_MAX_IN_FLIGHT", "2")
|
||||
with task_runtime._LOCK:
|
||||
old_runtime = task_runtime._RUNTIMES.pop(task_runtime.TaskLane.COLLAB_RECOMMEND, None)
|
||||
if old_runtime is not None:
|
||||
old_runtime.executor.shutdown(wait=False)
|
||||
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
try:
|
||||
def block():
|
||||
entered.set()
|
||||
release.wait(timeout=5)
|
||||
return "ok"
|
||||
|
||||
f1 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, block)
|
||||
assert f1 is not None
|
||||
assert entered.wait(timeout=2)
|
||||
|
||||
f2 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, lambda: "second")
|
||||
assert f2 is not None
|
||||
f3 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, lambda: "rejected")
|
||||
assert f3 is None
|
||||
|
||||
stats = task_runtime.lane_stats()[task_runtime.TaskLane.COLLAB_RECOMMEND.value]
|
||||
assert stats["workers"] == 1
|
||||
assert stats["max_in_flight"] == 2
|
||||
assert stats["admission_value"] == 0
|
||||
assert stats["in_flight"] == 2
|
||||
assert stats["active"] == 1
|
||||
assert stats["queued"] == 1
|
||||
assert stats["rejected"] >= 1
|
||||
assert stats["submitted"] >= 2
|
||||
|
||||
release.set()
|
||||
assert f1.result(timeout=5) == "ok"
|
||||
assert f2.result(timeout=5) == "second"
|
||||
|
||||
after = task_runtime.lane_stats()[task_runtime.TaskLane.COLLAB_RECOMMEND.value]
|
||||
assert after["in_flight"] == 0
|
||||
assert after["active"] == 0
|
||||
assert after["admission_value"] == 2
|
||||
finally:
|
||||
release.set()
|
||||
with task_runtime._LOCK:
|
||||
rt = task_runtime._RUNTIMES.pop(task_runtime.TaskLane.COLLAB_RECOMMEND, None)
|
||||
if rt is not None:
|
||||
rt.executor.shutdown(wait=True)
|
||||
|
||||
|
||||
def test_poll_scheduler_and_execution_worker_status_expose_health(monkeypatch):
|
||||
monkeypatch.setattr(binding_poll_scheduler, "available_slots", lambda _lane: 4)
|
||||
monkeypatch.setattr(binding_poll_scheduler, "_claim_due_binding_tasks", lambda _limit: [])
|
||||
assert binding_poll_scheduler.run_binding_poll_dispatch_once(10) == 0
|
||||
b_status = binding_poll_scheduler.scheduler_status()
|
||||
assert "last_claimed" in b_status
|
||||
assert "consecutive_errors" in b_status
|
||||
|
||||
monkeypatch.setattr(payment_poll_scheduler, "available_slots", lambda _lane: 4)
|
||||
monkeypatch.setattr(payment_poll_scheduler, "_claim_due_payment_tasks", lambda _limit: [])
|
||||
assert payment_poll_scheduler.run_payment_poll_dispatch_once(10) == 0
|
||||
p_status = payment_poll_scheduler.scheduler_status()
|
||||
assert "last_claimed" in p_status
|
||||
assert "consecutive_errors" in p_status
|
||||
|
||||
writer = ExecutionEventBatchWriter()
|
||||
assert writer.status() == {
|
||||
"running": False,
|
||||
"pending": 0,
|
||||
"flushing": False,
|
||||
"failed_batches": 0,
|
||||
}
|
||||
w_status = execution_worker.execution_job_worker_status()
|
||||
assert "inflight" in w_status
|
||||
assert "inflight_total" in w_status
|
||||
assert "event_writer" in w_status
|
||||
|
||||
|
||||
def test_automation_list_jobs_prefers_background_heartbeat_runtime_and_queues(
|
||||
db,
|
||||
monkeypatch,
|
||||
tmp_path,
|
||||
):
|
||||
user, account = _seed_user_and_account(db, "auto")
|
||||
enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_DOUYU_BATCH,
|
||||
lane_scope=LANE_FULFILLMENT,
|
||||
batch_id="bg-queued-batch",
|
||||
payload={},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
db.add(
|
||||
DouyuTask(
|
||||
batch_id="bg-queued-batch",
|
||||
account_id=int(account.id),
|
||||
task_type="get_bind_qr",
|
||||
queue_lane="binding_poll",
|
||||
status="running",
|
||||
next_run_at=datetime.now(UTC) - timedelta(seconds=5),
|
||||
created_by=int(user.id),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
heartbeat_path = tmp_path / "background_runtime.json"
|
||||
monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path))
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.automation.scheduler.scheduler_status",
|
||||
lambda: {
|
||||
"enabled": True,
|
||||
"running": True,
|
||||
"tick_seconds": 30,
|
||||
"job_interval_seconds": 300,
|
||||
"registered": ["account_sync_queue"],
|
||||
"in_flight": ["account_sync_queue"],
|
||||
},
|
||||
)
|
||||
background_runtime._write_runtime_heartbeat()
|
||||
|
||||
monkeypatch.setattr(
|
||||
automation_router,
|
||||
"scheduler_status",
|
||||
lambda: {
|
||||
"enabled": True,
|
||||
"running": False,
|
||||
"tick_seconds": 30,
|
||||
"job_interval_seconds": 300,
|
||||
"registered": [],
|
||||
"in_flight": [],
|
||||
},
|
||||
)
|
||||
|
||||
payload = automation_router.list_jobs(db=db, current=user)
|
||||
|
||||
assert payload["scheduler"]["process"] == "background"
|
||||
assert payload["scheduler"]["in_flight"] == ["account_sync_queue"]
|
||||
assert "douyu_batches" in payload["runtime"]
|
||||
assert payload["runtime"]["queues"]["execution_jobs"]["fulfillment"]["queued"] == 1
|
||||
assert payload["runtime"]["queues"]["binding_poll"] == {"running": 1, "due": 1}
|
||||
assert payload["runtime"]["queues"]["payment_poll"] == {"running": 0, "due": 0}
|
||||
|
||||
|
||||
def test_recover_stale_running_account_work_and_observability_alert(db, monkeypatch):
|
||||
_, account = _seed_user_and_account(db, "stalework")
|
||||
now = datetime.now(UTC).replace(microsecond=0)
|
||||
stale = enqueue_account_work(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
work_type="storehome_sync",
|
||||
due_at=now - timedelta(hours=2),
|
||||
max_attempts=2,
|
||||
)
|
||||
stale.status = "running"
|
||||
stale.started_at = now - timedelta(seconds=STALE_RUNNING_SECONDS + 120)
|
||||
stale.attempt_count = 1
|
||||
db.commit()
|
||||
|
||||
status = account_platform_status(
|
||||
db,
|
||||
now=now,
|
||||
include_trends=False,
|
||||
include_supply=False,
|
||||
include_diagnostics=False,
|
||||
)
|
||||
assert any(a["code"] == "account_work_stale_running" for a in status["alerts"])
|
||||
|
||||
monkeypatch.setattr(
|
||||
account_sync_queue,
|
||||
"run_account_sync_queue",
|
||||
lambda _db, batch_size=20: {"scanned": 0, "success": 0, "failed": 0, "message": "ok"},
|
||||
)
|
||||
job = AutomationJob(key="account_sync_queue", title="sync", batch_size=20)
|
||||
outcome = account_sync_queue.run_account_sync_queue_job(db, job)
|
||||
|
||||
db.refresh(stale)
|
||||
assert outcome["recovered_stale"] == 1
|
||||
assert stale.status == "pending"
|
||||
assert "疑似卡死" in stale.last_error
|
||||
|
||||
# Verify exhausted attempts transition cleanly to failed when recovered again.
|
||||
stale.status = "running"
|
||||
stale.started_at = now - timedelta(seconds=STALE_RUNNING_SECONDS + 60)
|
||||
stale.attempt_count = 2
|
||||
db.commit()
|
||||
assert recover_stale_running_account_work(db, now=now) == 1
|
||||
db.refresh(stale)
|
||||
assert stale.status == "failed"
|
||||
@@ -15,6 +15,7 @@ from sqlalchemy import func
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountSyncRun,
|
||||
AutomationJob,
|
||||
DouyuTask,
|
||||
ExecutionJob,
|
||||
@@ -30,6 +31,7 @@ class _Base:
|
||||
def setup_method(self):
|
||||
self.engine = get_test_engine()
|
||||
self.session = make_test_session(self.engine)
|
||||
self.session.query(AccountSyncRun).delete()
|
||||
self.session.query(DouyuTask).delete()
|
||||
self.session.query(AutomationJob).filter(
|
||||
AutomationJob.key == retention.JOB_KEY
|
||||
@@ -258,6 +260,37 @@ class TestRetention(_Base):
|
||||
assert out["deleted_execution_jobs"] == 1
|
||||
assert self.session.query(ExecutionJob).count() == 0
|
||||
|
||||
def test_old_account_sync_runs_cleaned_by_retention(self):
|
||||
self.session.add_all(
|
||||
[
|
||||
AccountSyncRun(
|
||||
account_id=self.account_id,
|
||||
domain="points",
|
||||
started_at=NOW - timedelta(days=20),
|
||||
finished_at=NOW - timedelta(days=20),
|
||||
status="success",
|
||||
duration_ms=120,
|
||||
),
|
||||
AccountSyncRun(
|
||||
account_id=self.account_id,
|
||||
domain="points",
|
||||
started_at=NOW - timedelta(days=3),
|
||||
finished_at=NOW - timedelta(days=3),
|
||||
status="success",
|
||||
duration_ms=80,
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
out = self.run(noise_days=7, business_days=90, sync_run_days=14)
|
||||
|
||||
assert out["deleted_sync_runs"] == 1
|
||||
assert out["sync_run_days"] == 14
|
||||
remaining_runs = self.session.query(AccountSyncRun).all()
|
||||
assert len(remaining_runs) == 1
|
||||
assert remaining_runs[0].duration_ms == 80
|
||||
|
||||
|
||||
class TestClassification(_Base):
|
||||
def test_noise_list_has_no_duplicates(self):
|
||||
|
||||
@@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261129_0140"
|
||||
HEAD_REVISION = "20261129_0141"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -91,6 +91,7 @@ _LATER_ORM_COLUMNS = {
|
||||
"exchange_result_image_key": "VARCHAR(512) NOT NULL DEFAULT ''",
|
||||
"exchange_result_image_saved_at": "DATETIME NULL",
|
||||
"customer_role_name": "VARCHAR(128) NOT NULL DEFAULT ''",
|
||||
"customer_role_norm": "VARCHAR(128) GENERATED ALWAYS AS (lower(trim(customer_role_name))) VIRTUAL NULL",
|
||||
"customer_platform": "VARCHAR(16) NOT NULL DEFAULT ''",
|
||||
"customer_system": "VARCHAR(16) NOT NULL DEFAULT ''",
|
||||
"customer_home_images": "JSON NULL",
|
||||
@@ -248,6 +249,7 @@ class TestMigrationSmoke:
|
||||
# 迁移新增的复合查询索引(不入模型,但应存在)。
|
||||
for index_name in EXTRA_INDEXES:
|
||||
assert index_name in all_db_indexes, f"迁移链未创建索引 {index_name}"
|
||||
assert "ix_account_sync_runs_started_domain_status" not in all_db_indexes
|
||||
finally:
|
||||
database_module.DATABASE_URL = original_url
|
||||
with admin_engine.begin() as conn:
|
||||
|
||||
Reference in New Issue
Block a user