# Schedule Worker 手动入队唤醒 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** 手动触发排程(及同属 schedule worker 消费的 Job)入队成功后立刻唤醒 `hxops-schedule-worker`,把「点一次执行 → 写出 RPA trigger」的队列空等从最多约 30s 降到通常 <1s,同时保持空闲维护节奏仍为 `SCHEDULE_WORKER_POLL_SECONDS=30`。 **Architecture:** 继续异步:Web API 只入队;独立 schedule worker 执行。新增 Redis List 唤醒通道(`LPUSH` / `BLPOP`):入队事务提交后 best-effort 发 wake;worker 空闲时用 `BLPOP(timeout=poll)` 替代 `time.sleep(poll)`。Redis 不可用时 fail-open,退回原 sleep/poll 行为。不把写 trigger 或整段 RPA 搬回 HTTP 线程。 **Tech Stack:** Flask (Python 3.12) + 现有 `redis` 客户端(`app.services.redis_client.get_redis_client`)+ pytest;Docker Compose `hxops-schedule-worker`。 **Spec:** 本计划实现 2026-09-29 会话批准的「方案 B:继续异步 + 手动入队唤醒」(无独立 spec 文件)。冻结决策: - D1:空闲 `SCHEDULE_WORKER_POLL_SECONDS` 默认仍为 **30**(控制 `prepare_schedule_queue` 维护频率);唤醒只打断 sleep,不把维护打到 2s。 - D2:唤醒通道用 Redis List + `BLPOP`(比 pub/sub 更适合「睡醒领任务」;迟到信号用 `LTRIM` 压成有界)。 - D3:fail-open:无 `REDIS_URL` / ping 失败 / wake 关闭时行为与改前一致。 - D4:HTTP API 契约不变(`POST /api/admin/schedules//run` 仍立即返回 `queued`);不改前端。 - D5:YAGNI——本计划不做「同步写 trigger」、不做前端 5s 轮询提速;cron 扫描仍靠既有 poll/prepare。 ## Global Constraints - 🔒 不提交密钥/密码;新增环境变量只写开关与 key 名默认值,不写真实 Redis 密码。 - 📝 新建/调整代码必须满足 AGENTS.md §5:文件头三要素(用途/依赖/逻辑)+ 每个函数 docstring(用途、核心逻辑、Args/Returns)。 - 🚫 禁止自动 commit:每个任务止步于 `git add <具体文件>`;提交须用户明确批准。 - ➕ 不新增第三方依赖(复用已有 `redis`)。 - 🧪 后端测试:`cd backend && python -m pytest -v`。 - 🌐 环境变量:跨环境一致项进 `.env.shared`;`docker-compose.yml` 给 schedule-worker 透传;`settings.py` 提供默认值。 - ⚠️ `enqueue(..., commit=False)` 路径禁止在 flush 后立刻 wake(worker 可能抢在 commit 前 claim);wake 必须在事务提交之后。 --- ## File Map | 文件 | 职责 | | --- | --- | | `backend/app/jobs/schedule_wake.py` | **新建**:唤醒契约(是否目标队列、notify、wait);唯一 Redis key/协议实现点 | | `backend/app/jobs/runner.py` | schedule 单队列空闲等待改为 `wait_for_schedule_wake`;其它队列仍 `time.sleep` | | `backend/app/services/schedule/queue_service.py` | `enqueue_manual_schedule_run` 在 **commit 成功且 created=True** 后调用 `notify_schedule_worker` | | `backend/app/jobs/queue.py` | `enqueue(..., commit=True)` 且 Job 由 schedule worker 消费时,commit 后 `notify_schedule_worker`(覆盖文件检核等) | | `backend/app/core/config/settings.py` | 新增 `SCHEDULE_WORKER_WAKE_ENABLED` / `SCHEDULE_WORKER_WAKE_REDIS_KEY` | | `.env.shared` | 文档化默认开关与 key(与 settings 默认一致) | | `docker-compose.yml` | `hxops-schedule-worker` 透传上述环境变量 | | `docs/project_context.md` | 一行说明:手动入队可 Redis 唤醒 schedule-worker | | `backend/tests/jobs/test_schedule_wake.py` | **新建**:wake 模块单测(假 Redis / 降级) | | `backend/tests/jobs/test_runner.py` | 增补:schedule 队列空闲走 wait 而非裸 sleep | | `backend/tests/jobs/test_schedule_queue.py` | 增补:手动入队成功后调用 notify | ## Interface Contract(全任务共用) ### Redis 协议 - Key:`SCHEDULE_WORKER_WAKE_REDIS_KEY`,默认 `hxops:jobs:wake:schedule` - Notify:`LPUSH key "wake"`,然后 `LTRIM key 0 7`(最多保留 8 个信号,防堆积) - Wait:`BLPOP key timeout_seconds`;超时返回「未唤醒」,有元素返回「已唤醒」 - 不使用 Redis Stream / pubsub(本计划范围外) ### Python API(`app.jobs.schedule_wake`) ```python def targets_schedule_worker(*, domain: str | None, job_type: str | None) -> bool: """判断该 Job 是否由 hxops-schedule-worker 消费。""" def notify_schedule_worker(*, reason: str = "enqueue") -> bool: """ Best-effort 唤醒 schedule worker。 Returns: True=已写入 Redis;False=跳过/失败(永不抛到业务主路径)。 """ def wait_for_schedule_wake(timeout_seconds: float) -> bool: """ 阻塞至多 timeout_seconds 等待唤醒;Redis 不可用时等价 time.sleep(timeout)。 Returns: True=被信号唤醒;False=超时或降级 sleep 结束。 """ ``` ### `targets_schedule_worker` 判定(锁死) 返回 True 当且仅当: 1. `domain == "schedule"`,或 2. `job_type` ∈ `{ "schedule_run", "file_check_run", "wecom_directory_sync" }` (与 `app/jobs/store.py` schedule 分支领取集合对齐;新增 schedule worker 消费类型时必须同步改此集合。) ### HTTP / 前端契约(不变) | 接口 | 行为 | | --- | --- | | `POST /api/admin/schedules//run` | 仍立即 `200` + `serialize_run`(`status=queued`);不新增字段 | | 排程运行列表 / Worker 心跳 API | 无变更 | | 前端火箭按钮 | 无变更(仍调同一 run API) | ### 环境变量契约 | 变量 | 默认 | 含义 | | --- | --- | --- | | `SCHEDULE_WORKER_POLL_SECONDS` | `30` | 空闲等待上限 / BLPOP timeout;**不改默认** | | `SCHEDULE_WORKER_WAKE_ENABLED` | `true` | `false` 时 notify/wait 均降级为 no-op / sleep | | `SCHEDULE_WORKER_WAKE_REDIS_KEY` | `hxops:jobs:wake:schedule` | Redis List key | 依赖既有 `REDIS_URL`(compose 已给 schedule-worker 注入)。 --- ### Task 1: `schedule_wake` 模块 + 单测 **Files:** - Create: `backend/app/jobs/schedule_wake.py` - Create: `backend/tests/jobs/test_schedule_wake.py` **Interfaces:** - Consumes: `get_redis_client()`、`current_app.config` - Produces: `targets_schedule_worker` / `notify_schedule_worker` / `wait_for_schedule_wake`(签名见上) - [ ] **Step 1: Write the failing tests** 创建 `backend/tests/jobs/test_schedule_wake.py`: ```python """ tests/jobs/test_schedule_wake.py 用途:锁定 schedule worker Redis 唤醒契约(判定、notify、wait、fail-open)。 依赖:app.jobs.schedule_wake、Flask app fixture。 逻辑:用假 Redis 客户端替换 get_redis_client;不连真实 Redis。 """ from __future__ import annotations from types import SimpleNamespace import pytest class _FakeRedis: def __init__(self): self.lists: dict[str, list[str]] = {} self.ops: list[tuple] = [] def lpush(self, key: str, value: str): self.ops.append(("lpush", key, value)) self.lists.setdefault(key, []).insert(0, value) return len(self.lists[key]) def ltrim(self, key: str, start: int, end: int): self.ops.append(("ltrim", key, start, end)) items = self.lists.get(key, []) # redis LTRIM inclusive end self.lists[key] = items[start : end + 1] return True def blpop(self, keys, timeout: int = 0): self.ops.append(("blpop", tuple(keys), timeout)) key = keys[0] items = self.lists.get(key) or [] if items: value = items.pop() self.lists[key] = items return key, value return None def test_targets_schedule_worker_matrix(): from app.jobs.schedule_wake import targets_schedule_worker assert targets_schedule_worker(domain="schedule", job_type="schedule_run") is True assert targets_schedule_worker(domain="schedule", job_type="anything") is True assert targets_schedule_worker(domain="default", job_type="file_check_run") is True assert targets_schedule_worker(domain="default", job_type="wecom_directory_sync") is True assert targets_schedule_worker(domain="shipping_notice", job_type="shipping_process_gate") is False def test_notify_lpush_and_ltrim(app, monkeypatch): from app.jobs import schedule_wake from app.services import redis_client fake = _FakeRedis() monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) with app.app_context(): app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True app.config["SCHEDULE_WORKER_WAKE_REDIS_KEY"] = "hxops:jobs:wake:schedule" assert schedule_wake.notify_schedule_worker(reason="manual") is True assert ("lpush", "hxops:jobs:wake:schedule", "wake") in fake.ops assert ("ltrim", "hxops:jobs:wake:schedule", 0, 7) in fake.ops def test_notify_disabled_returns_false(app, monkeypatch): from app.jobs import schedule_wake from app.services import redis_client fake = _FakeRedis() monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) with app.app_context(): app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = False assert schedule_wake.notify_schedule_worker() is False assert fake.ops == [] def test_notify_no_redis_returns_false(app, monkeypatch): from app.jobs import schedule_wake from app.services import redis_client monkeypatch.setattr(redis_client, "get_redis_client", lambda: None) with app.app_context(): app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True assert schedule_wake.notify_schedule_worker() is False def test_wait_returns_true_when_signal_present(app, monkeypatch): from app.jobs import schedule_wake from app.services import redis_client fake = _FakeRedis() fake.lpush("hxops:jobs:wake:schedule", "wake") monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) with app.app_context(): app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True app.config["SCHEDULE_WORKER_WAKE_REDIS_KEY"] = "hxops:jobs:wake:schedule" assert schedule_wake.wait_for_schedule_wake(1.0) is True def test_wait_falls_back_to_sleep_without_redis(app, monkeypatch): from app.jobs import schedule_wake from app.services import redis_client slept: list[float] = [] monkeypatch.setattr(redis_client, "get_redis_client", lambda: None) monkeypatch.setattr(schedule_wake.time, "sleep", lambda seconds: slept.append(seconds)) with app.app_context(): app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True assert schedule_wake.wait_for_schedule_wake(2.5) is False assert slept == [2.5] ``` - [ ] **Step 2: Run tests to verify they fail** Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` Expected: FAIL with `ModuleNotFoundError: No module named 'app.jobs.schedule_wake'`(或 import 失败) - [ ] **Step 3: Implement `schedule_wake.py`** 创建 `backend/app/jobs/schedule_wake.py`: ```python """ backend/app/jobs/schedule_wake.py 用途:schedule worker 跨进程唤醒(手动/Web 入队后打断空闲 BLPOP)。 依赖:redis_client.get_redis_client、Flask current_app.config。 逻辑:Web/enqueue 在事务提交后 LPUSH;runner 空闲 BLPOP(timeout=poll); Redis 不可用或开关关闭时 fail-open(notify 返回 False,wait 退回 sleep)。 """ from __future__ import annotations import logging import time from typing import Final from flask import current_app from app.services.redis_client import get_redis_client logger = logging.getLogger(__name__) _DEFAULT_KEY: Final = "hxops:jobs:wake:schedule" _WAKE_PAYLOAD: Final = "wake" _MAX_QUEUED_SIGNALS: Final = 8 # 与 app.jobs.store.claim_next 的 schedule 分支领取集合对齐 _SCHEDULE_WORKER_JOB_TYPES: Final = frozenset( { "schedule_run", "file_check_run", "wecom_directory_sync", } ) def _wake_enabled() -> bool: if not current_app: return False return bool(current_app.config.get("SCHEDULE_WORKER_WAKE_ENABLED", True)) def _wake_key() -> str: raw = "" if current_app: raw = str(current_app.config.get("SCHEDULE_WORKER_WAKE_REDIS_KEY") or "").strip() return raw or _DEFAULT_KEY def targets_schedule_worker(*, domain: str | None, job_type: str | None) -> bool: """ 判断 Job 是否由 hxops-schedule-worker 消费。 核心逻辑:domain=schedule 或 job_type 属于 schedule worker 领取集合。 Args: domain: jobs.domain。 job_type: jobs.job_type 字符串。 Returns: True 表示入队后应尝试唤醒 schedule worker。 """ if str(domain or "").strip() == "schedule": return True return str(job_type or "").strip() in _SCHEDULE_WORKER_JOB_TYPES def notify_schedule_worker(*, reason: str = "enqueue") -> bool: """ Best-effort 向 Redis List 写入唤醒信号。 核心逻辑:开关关闭或无 Redis 时返回 False;LPUSH 后 LTRIM 限长;异常吞掉并打 warning。 Args: reason: 仅用于日志,不写入 Redis(载荷固定为 wake)。 Returns: True=信号已写入;False=跳过或失败。永不向调用方抛异常。 """ try: if not _wake_enabled(): return False client = get_redis_client() if client is None: return False key = _wake_key() client.lpush(key, _WAKE_PAYLOAD) client.ltrim(key, 0, _MAX_QUEUED_SIGNALS - 1) logger.info("[schedule-wake] notified key=%s reason=%s", key, reason) return True except Exception: logger.warning("[schedule-wake] notify failed reason=%s", reason, exc_info=True) return False def wait_for_schedule_wake(timeout_seconds: float) -> bool: """ 等待唤醒信号;用于 schedule worker 空闲循环替代 time.sleep。 核心逻辑:timeout<=0 时立即返回 False;开关关闭或无 Redis 时 sleep(timeout); 否则 BLPOP(key, int(ceil(timeout))),有元素返回 True。 Args: timeout_seconds: 最长等待秒数(来自 SCHEDULE_WORKER_POLL_SECONDS)。 Returns: True=收到信号;False=超时或降级 sleep 结束。 """ timeout = max(0.0, float(timeout_seconds or 0.0)) if timeout <= 0: return False try: if not _wake_enabled(): time.sleep(timeout) return False client = get_redis_client() if client is None: time.sleep(timeout) return False key = _wake_key() # redis-py blpop timeout 为整秒;至少 1,避免 0 变非阻塞空转 blpop_timeout = max(1, int(timeout + 0.999)) item = client.blpop([key], timeout=blpop_timeout) return item is not None except Exception: logger.warning("[schedule-wake] wait failed; falling back to sleep", exc_info=True) time.sleep(timeout) return False ``` - [ ] **Step 4: Run tests to verify they pass** Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` Expected: PASS - [ ] **Step 5: Stage changes** ```bash git add backend/app/jobs/schedule_wake.py backend/tests/jobs/test_schedule_wake.py ``` --- ### Task 2: 配置项(settings / env / compose) **Files:** - Modify: `backend/app/core/config/settings.py`(在 `SCHEDULE_WORKER_POLL_SECONDS` 旁新增两行) - Modify: `.env.shared`(§9 业务模块内、货代/排程相关注释旁新增两行) - Modify: `docker-compose.yml`(`hxops-schedule-worker.environment` 透传) **Interfaces:** - Consumes: 无 - Produces: `app.config["SCHEDULE_WORKER_WAKE_ENABLED"]` / `["SCHEDULE_WORKER_WAKE_REDIS_KEY"]` 可供 Task 1 模块读取 - [ ] **Step 1: Write a failing config smoke test** 在 `backend/tests/jobs/test_schedule_wake.py` 追加: ```python def test_wake_settings_defaults(app): """关键断言:唤醒开关默认开,key 默认固定字符串。""" with app.app_context(): assert app.config.get("SCHEDULE_WORKER_WAKE_ENABLED") is True assert app.config.get("SCHEDULE_WORKER_WAKE_REDIS_KEY") == "hxops:jobs:wake:schedule" assert float(app.config.get("SCHEDULE_WORKER_POLL_SECONDS")) == 30.0 ``` - [ ] **Step 2: Run test to verify it fails** Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py::test_wake_settings_defaults -v` Expected: FAIL(`SCHEDULE_WORKER_WAKE_ENABLED` 为 None / 缺失) - [ ] **Step 3: Patch settings.py** 在 `SCHEDULE_WORKER_POLL_SECONDS` 定义后插入: ```python SCHEDULE_WORKER_WAKE_ENABLED = os.getenv('SCHEDULE_WORKER_WAKE_ENABLED', 'true').lower() == 'true' SCHEDULE_WORKER_WAKE_REDIS_KEY = ( os.getenv('SCHEDULE_WORKER_WAKE_REDIS_KEY') or 'hxops:jobs:wake:schedule' ).strip() or 'hxops:jobs:wake:schedule' ``` 同步更新该文件顶部 docstring 的依赖/逻辑句(若提及 schedule worker 配置)。 - [ ] **Step 4: Patch `.env.shared`** 在 `# --- 9. 业务模块 ---` 下靠近货代 RPA 注释处增加(勿打乱其它域顺序): ```bash # 排程 worker:空闲 poll 默认 30s;手动入队后 Redis List 唤醒(无 Redis 时 fail-open) SCHEDULE_WORKER_WAKE_ENABLED=true SCHEDULE_WORKER_WAKE_REDIS_KEY=hxops:jobs:wake:schedule ``` - [ ] **Step 5: Patch `docker-compose.yml`** 在 `hxops-schedule-worker` 的 `environment:` 中 `SCHEDULE_WORKER_POLL_SECONDS` 旁增加: ```yaml - SCHEDULE_WORKER_WAKE_ENABLED=${SCHEDULE_WORKER_WAKE_ENABLED:-true} - SCHEDULE_WORKER_WAKE_REDIS_KEY=${SCHEDULE_WORKER_WAKE_REDIS_KEY:-hxops:jobs:wake:schedule} ``` (backend 容器若也跑入队,已通过 `env_file` 读 `.env.shared`,无需强制再写一遍;schedule-worker 显式透传避免只挂 compose environment 时漏开关。) - [ ] **Step 6: Run test to verify it passes** Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` Expected: PASS - [ ] **Step 7: Stage changes** ```bash git add backend/app/core/config/settings.py .env.shared docker-compose.yml backend/tests/jobs/test_schedule_wake.py ``` --- ### Task 3: 入队后 notify(commit 之后) **Files:** - Modify: `backend/app/services/schedule/queue_service.py`(`enqueue_manual_schedule_run`) - Modify: `backend/app/jobs/queue.py`(`enqueue` 在 `commit=True` 成功路径末尾) - Modify: `backend/tests/jobs/test_schedule_queue.py` **Interfaces:** - Consumes: `notify_schedule_worker(reason=...)`、`targets_schedule_worker(...)` - Produces: 手动排程与其它 schedule-worker Job 在事务可见后发出 wake - [ ] **Step 1: Write the failing test for manual enqueue notify** 在 `backend/tests/jobs/test_schedule_queue.py` 追加: ```python def test_manual_schedule_run_notifies_wake_after_commit(app, monkeypatch): """关键断言:手动入队 commit 成功后调用 notify;复用活动 run 时不调用。""" from app.services.schedule import queue_service calls: list[str] = [] def _fake_notify(*, reason: str = "enqueue") -> bool: calls.append(reason) return True monkeypatch.setattr(queue_service, "notify_schedule_worker", _fake_notify) with app.app_context(): task = _create_task() run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) assert created is True and job_id > 0 assert calls == ["manual_schedule_run"] calls.clear() run2, _job2, created2 = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) assert created2 is False assert run2.id == run.id assert calls == [] # 未新建 Job,不应唤醒 ``` 注意:测试里通过 `queue_service.notify_schedule_worker` 打桩,因此实现时须在 `queue_service.py` **模块级 import**: `from app.jobs.schedule_wake import notify_schedule_worker` - [ ] **Step 2: Run test to verify it fails** Run: `cd backend && python -m pytest tests/jobs/test_schedule_queue.py::test_manual_schedule_run_notifies_wake_after_commit -v` Expected: FAIL(`notify_schedule_worker` 未定义或 calls 为空) - [ ] **Step 3: Wire `enqueue_manual_schedule_run`** 在 `queue_service.py` 文件头 import 区增加 `notify_schedule_worker`;更新模块 docstring「逻辑」句:手动入队 commit 后 Redis 唤醒 schedule worker。 将 `enqueue_manual_schedule_run` 成功新建分支改为: ```python run, job_id = _create_queued_run( task, trigger_type="manual", triggered_by_user_id=triggered_by_user_id, api_request_json=api_request_json, ) db.session.commit() # [STEP] 事务提交后再唤醒,避免 worker 抢在 commit 前 claim 到不可见行 notify_schedule_worker(reason="manual_schedule_run") return run, job_id, True ``` 同步更新该函数 docstring:说明 commit 后 best-effort wake。 - [ ] **Step 4: Wire generic `enqueue` (commit=True only)** 在 `backend/app/jobs/queue.py` 的 `enqueue` 函数中,找到 `if commit: db.session.commit()`(或等价提交)成功之后、`return job.id` 之前,插入: ```python if commit and targets_schedule_worker(domain=normalized_domain, job_type=normalized_type): from app.jobs.schedule_wake import notify_schedule_worker notify_schedule_worker(reason=f"enqueue:{normalized_type}") ``` 要求: - `commit=False` **绝不** notify(schedule_run 手动路径由 Task 3 Step 3 负责) - dedupe 复用已有 queued/running Job 时:仍可 notify(幂等唤醒无害);若实现里 early-return 已有 job,也在 **该 early-return 之前已 commit/无需 commit** 的路径上对 schedule 目标调用一次 notify——保持简单:仅在「本函数刚执行了 `db.session.commit()`」之后 notify;early-return 未写库则不 notify 在 `queue.py` 顶部或函数内 import `targets_schedule_worker`。更新 `queue.py` 文件头「逻辑」注释。 - [ ] **Step 5: Add enqueue commit=True unit coverage** 在 `backend/tests/jobs/test_schedule_wake.py` 或现有 `tests/jobs/test_types.py` 旁增加轻量测(推荐放 `test_schedule_wake.py`): ```python def test_generic_enqueue_schedule_domain_notifies(app, monkeypatch): """commit=True 且 domain=schedule 时,enqueue 末尾唤醒。""" from app.jobs import queue as job_queue from app.jobs.types import JobType calls: list[str] = [] monkeypatch.setattr( "app.jobs.schedule_wake.notify_schedule_worker", lambda *, reason="enqueue": calls.append(reason) or True, ) with app.app_context(): job_id = job_queue.enqueue( JobType.SCHEDULE_RUN, {"schedule_task_id": 1, "schedule_run_id": 1, "run_no": "RUN-WAKE-TEST"}, domain="schedule", business_ref="schedule_run:wake-test:freight-receipt-rpa", dedupe_active=False, commit=True, ) assert job_id > 0 assert any(c.startswith("enqueue:") for c in calls) ``` 若 `SCHEDULE_RUN` 对 payload 有更严校验,按 `test_schedule_queue` 现有最小 payload 对齐。 - [ ] **Step 6: Run tests** Run: ```bash cd backend && python -m pytest tests/jobs/test_schedule_queue.py::test_manual_schedule_run_notifies_wake_after_commit tests/jobs/test_schedule_wake.py -v ``` Expected: PASS - [ ] **Step 7: Stage changes** ```bash git add backend/app/services/schedule/queue_service.py backend/app/jobs/queue.py backend/tests/jobs/test_schedule_queue.py backend/tests/jobs/test_schedule_wake.py ``` --- ### Task 4: runner 空闲等待改为可唤醒 **Files:** - Modify: `backend/app/jobs/runner.py` - Modify: `backend/tests/jobs/test_runner.py` **Interfaces:** - Consumes: `wait_for_schedule_wake(timeout_seconds: float) -> bool` - Produces: 仅当 `queues == ['schedule']`(单队列)时用 wait;kb/shipping/contract/transfer 行为不变 - [ ] **Step 1: Write the failing runner test** 在 `backend/tests/jobs/test_runner.py` 追加: ```python def test_schedule_queue_idle_uses_wake_wait(monkeypatch): """关键断言:纯 schedule 队列空闲走 wait_for_schedule_wake,不直接 time.sleep。""" from app.jobs import runner events: list[str] = [] class _Logger: def info(self, *_a, **_k): pass def exception(self, *_a, **_k): pass def error(self, *_a, **_k): pass monkeypatch.setattr(runner.store, "claim_next", lambda **_k: None) monkeypatch.setattr(runner.time, "sleep", lambda *_a, **_k: events.append("sleep") or (_ for _ in ()).throw(StopIteration)) monkeypatch.setattr( runner, "wait_for_schedule_wake", lambda timeout: events.append(f"wake:{timeout}") or (_ for _ in ()).throw(StopIteration), ) with pytest.raises(StopIteration): runner.run_forever( SimpleNamespace(extras={"queues": ["schedule"]}, config={"SCHEDULE_WORKER_POLL_SECONDS": 30}, logger=_Logger()), poll_interval_seconds=30, ) assert events == ["wake:30"] def test_shipping_queue_idle_still_sleeps(monkeypatch): """关键断言:非 schedule 单队列仍用 time.sleep,避免误绑 Redis。""" from app.jobs import runner events: list[str] = [] class _Logger: def info(self, *_a, **_k): pass def exception(self, *_a, **_k): pass def error(self, *_a, **_k): pass monkeypatch.setattr(runner.store, "claim_next", lambda **_k: None) monkeypatch.setattr(runner.time, "sleep", lambda seconds: events.append(f"sleep:{seconds}") or (_ for _ in ()).throw(StopIteration)) monkeypatch.setattr( runner, "wait_for_schedule_wake", lambda timeout: events.append(f"wake:{timeout}") or True, ) with pytest.raises(StopIteration): runner.run_forever( SimpleNamespace(extras={"queues": ["shipping"]}, config={}, logger=_Logger()), poll_interval_seconds=2, ) assert events == ["sleep:2"] ``` 实现时在 `runner.py` 增加: `from app.jobs.schedule_wake import wait_for_schedule_wake` 以便测试可 `monkeypatch.setattr(runner, "wait_for_schedule_wake", ...)`。 - [ ] **Step 2: Run tests to verify they fail** Run: `cd backend && python -m pytest tests/jobs/test_runner.py::test_schedule_queue_idle_uses_wake_wait tests/jobs/test_runner.py::test_shipping_queue_idle_still_sleeps -v` Expected: FAIL(`wait_for_schedule_wake` 未绑定到 runner 或仍走 sleep) - [ ] **Step 3: Implement runner idle branch** 更新 `runner.py` 文件头「逻辑」:schedule 单队列空闲 BLPOP 唤醒。 把空闲分支: ```python time.sleep(poll) continue ``` 替换为: ```python # schedule 单队列:用 Redis BLPOP 可打断等待;其它队列保持 sleep if queues == ["schedule"]: wait_for_schedule_wake(poll) else: time.sleep(poll) continue ``` `recovery_callback` 的 tick 逻辑保持在 `claim_next` 返回 None 之后、wait/sleep **之前**(与现文件顺序一致),避免唤醒后跳过超时回收过久。 - [ ] **Step 4: Run runner + wake + schedule_queue tests** Run: ```bash cd backend && python -m pytest tests/jobs/test_runner.py tests/jobs/test_schedule_wake.py tests/jobs/test_schedule_queue.py -v ``` Expected: PASS - [ ] **Step 5: Stage changes** ```bash git add backend/app/jobs/runner.py backend/tests/jobs/test_runner.py ``` --- ### Task 5: 文档 + 手工验收清单 **Files:** - Modify: `docs/project_context.md`(worker 列表附近补一句唤醒说明) - Modify: 本计划文件顶部勾选状态由执行者更新(可选) **Interfaces:** - Produces: 运维可读的行为说明;无新 HTTP 字段 - [ ] **Step 1: Update `docs/project_context.md`** 在提及 `hxops-schedule-worker` /「排程扫描与执行由独立 worker 承担」的段落追加一句(中文): > 手动触发排程(及 file-check / 企微通讯录同步等由该 worker 消费的 Job)在入队事务提交后,通过 Redis List(`SCHEDULE_WORKER_WAKE_REDIS_KEY`,默认 `hxops:jobs:wake:schedule`)唤醒空闲中的 schedule-worker;无 Redis 时仍按 `SCHEDULE_WORKER_POLL_SECONDS`(默认 30s)轮询。 - [ ] **Step 2: Manual verification checklist(执行者在本地/测试环境勾选)** 1. Redis 可用;`hxops-backend` + `hxops-schedule-worker` 已加载新代码。 2. 管理台对「收料 RPA」点一次执行。 3. 查库:`schedule_runs.created_at` 与 `started_at` 差应 **通常 < 2s**(不再稳定出现 15~30s)。 4. 查 trigger:`FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 下出现 `receipt_export_batch_.json` 的时间贴近 `started_at`。 5. 负向:设 `SCHEDULE_WORKER_WAKE_ENABLED=false` 或断开 Redis,行为回退为最多约 30s 空等,且入队 API 不报错。 6. cron 到期任务仍能在一个 poll 周期内入队执行(唤醒非必须)。 - [ ] **Step 3: Stage docs** ```bash git add docs/project_context.md docs/superpowers/plans/2026-09-29-schedule-worker-manual-wake.md ``` --- ## Self-Review 1. **Spec coverage:** D1 空闲 30s → Task 2/4;D2 Redis List → Task 1;D3 fail-open → Task 1 测试;D4 HTTP 不变 → 无 API 任务;D5 不做同步 trigger/前端 → 明确非目标。 2. **Placeholder scan:** 无 TBD/TODO;测试与实现代码已写出。 3. **Type consistency:** `notify_schedule_worker(*, reason: str) -> bool`、`wait_for_schedule_wake(timeout_seconds: float) -> bool`、`targets_schedule_worker(*, domain, job_type) -> bool` 前后一致;wake 仅在 commit 之后。 ## Out of Scope(明确不做) - 同步在 API 线程写 receipt/inventory trigger - 缩短默认 `SCHEDULE_WORKER_POLL_SECONDS` - 前端 `RUN_NOW_POLL_MS` 加速或 SSE - Postgres `LISTEN/NOTIFY` 替代 Redis - 拆分 `prepare_schedule_queue` 与 claim 频率(唤醒已避免为手点而把维护打到 2s)