"""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"