Files
syops/docs/superpowers/plans/2026-09-18-receipt-worker-parity-hardening.md
T

35 KiB
Raw Blame History

收料 Worker 能力对齐库存 Worker(日志/心跳/清理)实施计划

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: 收料 Worker 具备库存 Worker 的全部运行能力——文件日志(tee+时间戳+轮转)、完整启动 banner、成功/失败全路径留痕、心跳上报(独立 Worker 身份)、磁盘保留清理(含 receipt_* 孤儿 Profile);日志机制提取为 common/worker_logging.py,库存 Worker 同步切换,杜绝第二份复制。

Architecture: 把库存 Worker 内置的日志实现(_TeeStream/_configure_file_logging/_maybe_rotate_open_log/轮转辅助,约 200 行)原样提取到 scripts/rpa/common/worker_logging.py,库存 Worker 切换为委托(行为等价,既有测试必须全绿);收料 Worker 接入同一模块并在主循环补齐 banner、心跳(rpa_heartbeat,独立 SHIPPING_NOTICE_RPA_WORKER_ID)、周期磁盘清理(run_worker_disk_cleanup 直接复用)。库存与收料是两个独立进程:日志文件必须各自独立,禁止共写;心跳身份必须不同,否则监控端同一 Worker 卡片会在两种上下文间抖动。

Tech Stack: 纯标准库(Worker 脚本)、pytest(后端测试)。

Spec: 用户 2026-09-18 口径——「上面库存 worker 有的,收料都需要有」。本计划推翻 2026-08-19 收料交付时的冻结决策「收料 Worker 无心跳/哨兵」;rpa_heartbeat/worker_disk_cleanup/trigger_consumer 均为既有共享模块,直接复用。

Global Constraints

  • 库存 Worker 本轮只做日志委托切换(纯等价重构),其余行为零改动;心跳/清理/触发逻辑不碰。
  • 收料 Worker 的功能增补不改变四态 trigger 目录契约与回调契约(shipping_receipt_rpa.v1、/api/shipping-notice/rpa/receipt-batch-ready 不动)。
  • 心跳必须使用独立 Worker 身份:SHIPPING_NOTICE_RPA_WORKER_ID=<hostname>-receipt(ps1 设置),禁止与库存 Worker 同身份上报。
  • 不新增第三方依赖;不改后端 API;无数据库/迁移改动;前端零改动。
  • Conventional Commits:<type>(<scope>): <中文祈使句>,scope ∈ rpa / shipping-notice。
  • .env.* 文件零改动:Worker 全部新变量由 start_receipt_worker.ps1 以 Process 级注入(Worker 不读 .env 文件)。
  • 测试从 backend/ 运行:python -m pytest -q <路径>;已知既有失败(reuse_session 两个用例等)不属本计划,不修不扩。
  • 工作树可能含用户 in-flight 改动:提交只 git add 各任务明确列出的文件。

Task 1: 提取 common/worker_logging.py(自库存 Worker,行为等价)+ 单测

Files:

  • Create: scripts/rpa/common/worker_logging.py
  • Test: backend/tests/test_rpa_worker_logging.py

Interfaces:

  • Produces(Task 2/3 消费):

    • configure_file_logging() -> Path | None:读 env SHIPPING_NOTICE_RPA_WORKER_LOG_FILE(相对路径基于仓库 backend/),启用后 stdout/stderr 全部 tee 落盘并加 YYYY-MM-DD HH:MM:SS 本地时间戳;重复调用幂等(已启用时直接返回现有路径)。
    • maybe_rotate_open_log() -> None:按 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES(默认 10MB,<=0 禁用)运行中轮转。
    • active_log_path() -> Path | None。
    • shutdown_logging() -> None:恢复 stdout/stderr 并关闭句柄(原 atexit 逻辑公开化,仍保留 atexit 注册)。
    • WorkerLogTee(含 replace_log_file)、log_line_timestamp() -> str、rotate_log_file_if_needed(path) -> None 供测试与后续复用。
  • 源码提取自 scripts/rpa/inventory/inventory_rpa_worker.py:139-152(_log_line_timestamp)、159-248(_TeeStream + 活跃状态)、250-297(_configure_file_logging)、299-323(_maybe_rotate_open_log)、325-345(_log_int_env/_rotate_log_file_if_needed)。逐行为等价迁移:只改模块内引用(_env 从 rpa_common 导入、_backend_dir 改为 Path(__file__).resolve().parents[3] / "backend"),docstring 保留原文。

  • Step 1: 写失败测试

"""worker_logging 公共文件日志模块测试。

用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
      按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
"""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))

from worker_logging import (  # noqa: E402
    WorkerLogTee,
    configure_file_logging,
    log_line_timestamp,
    rotate_log_file_if_needed,
    shutdown_logging,
)


@pytest.fixture(autouse=True)
def _restore_streams():
    """每用例后强制恢复标准流并关闭日志,避免污染其他测试。"""
    yield
    shutdown_logging()


def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
    """tee 应把带时间戳的行同时写入控制台与日志文件。"""
    log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1)
    tee = WorkerLogTee(sys.stdout, log_file)
    original_stdout = sys.stdout
    sys.stdout = tee
    try:
        print("hello-worker")
    finally:
        sys.stdout = original_stdout
        log_file.close()
    content = (tmp_path / "worker.log").read_text(encoding="utf-8")
    assert "hello-worker" in content
    assert content.startswith(log_line_timestamp()[:10])  # 日期前缀存在
    assert "hello-worker" in capsys.readouterr().out


def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
    """超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
    monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10")
    monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
    path = tmp_path / "worker.log"
    for round_no in range(3):
        path.write_text(f"round-{round_no}-padding", encoding="utf-8")
        rotate_log_file_if_needed(path)
    # [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入
    assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding"
    assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding"
    assert not Path(f"{path}.3").exists()
    assert not path.exists()  # 轮转后主文件位腾空,由调用方以追加模式重建


def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
    """configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
    monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
    enabled = configure_file_logging()
    assert enabled == tmp_path / "logs" / "worker.log"
    assert enabled.parent.is_dir()  # 日志目录自动创建
    print("banner-line")
    shutdown_logging()
    content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8")
    assert "banner-line" in content
    assert "[logging] tee enabled" in content
    out = capsys.readouterr().out
    assert "banner-line" in out


def test_configure_without_env_is_noop(monkeypatch):
    """未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
    monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False)
    assert configure_file_logging() is None
  • Step 2: 运行确认失败

Run: cd backend && python -m pytest -q tests/test_rpa_worker_logging.py Expected: FAIL(ModuleNotFoundError: worker_logging)

  • Step 3: 实现(从 inventory_rpa_worker.py:139-345 等价迁移)

模块骨架(函数体从库存 Worker 原样搬运,仅做下列机械替换,禁止行为改动):

"""scripts/rpa/common/worker_logging.py

用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
      按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
逻辑:configure_file_logging 读 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用;
      maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
"""

from __future__ import annotations

import atexit
import sys
from pathlib import Path
from typing import TextIO

from rpa_common import _env

def _backend_dir() -> Path:
    """返回仓库内 backend 根目录(本模块位于 <repo>/scripts/rpa/common/)。"""
    return Path(__file__).resolve().parents[3] / "backend"

def log_line_timestamp() -> str:
    # 原样搬运 inventory_rpa_worker.py:139-152(`%Y-%m-%d %H:%M:%S` 本地时区)。

def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
    # 原样搬运 :325-330(_env 已从 rpa_common 导入)。

class WorkerLogTee:
    # 原样搬运 :159-197(__init__/replace_log_file/_emit_line/write/flush/isatty)。

# 活跃状态四元组 + configure_file_logging() + maybe_rotate_open_log() + _rotate_log_file_if_needed(path)
# 原样搬运 :199-345,仅两处机械替换:
#   1) `_env(...)` 已改为模块顶部 `from rpa_common import _env`(原文件内同名函数);
#   2) `_configure_file_logging` 内部闭包 `_close_log` 提升为模块级公开函数 `shutdown_logging()`,
#      atexit.register(shutdown_logging) 保留;`maybe_rotate_open_log`/`shutdown_logging`
#      共享同一组模块级 _ACTIVE_* 状态。
# 额外导出:def active_log_path() -> Path | None: return _ACTIVE_LOG_PATH
# 幂等保护:configure_file_logging 开头 `if _ACTIVE_LOG_PATH is not None: return _ACTIVE_LOG_PATH`。

执行者注意:搬运时保持函数体逐行一致(含注释),上述缩略注释不是让你重写实现。完成后 git diff 自查:除模块头/导入/shutdown_logging 提升外不得有其他差异。

  • Step 4: 运行确认通过

Run: cd backend && python -m pytest -q tests/test_rpa_worker_logging.py Expected: 4 passed

  • Step 5: 提交
git add scripts/rpa/common/worker_logging.py backend/tests/test_rpa_worker_logging.py
git commit -m "feat(rpa): 提取Worker通用文件日志模块worker_logging"

Task 2: 库存 Worker 切换委托 worker_logging(纯等价重构)

Files:

  • Modify: scripts/rpa/inventory/inventory_rpa_worker.py(删除 :139-345 的本地实现,改为导入委托)
  • Test: 既有 backend/tests/test_freight_rpa_worker.py 等(零新增,全量必须绿)

Interfaces:

  • Consumes: Task 1 的 configure_file_logging / maybe_rotate_open_log / active_log_path。

  • Produces: 库存 Worker 行为零变化;_maybe_rotate_open_log() 与 log_file=_ACTIVE_LOG_PATH 调用点改走公共模块。

  • Step 1: 切换

  1. 删除本地 _log_line_timestamp、_log_int_env、_TeeStream、_ACTIVE_* 四个全局、_configure_file_logging、_maybe_rotate_open_log、_rotate_log_file_if_needed(:139-345 区段)。
  2. 导入区加 from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402。
  3. 调用点机械替换:_configure_file_logging() → configure_file_logging();_maybe_rotate_open_log() → maybe_rotate_open_log();log_file=_ACTIVE_LOG_PATH → log_file=active_log_path()。
  4. grep -n "_ACTIVE_\|_TeeStream\|_configure_file_logging\|_maybe_rotate\|_rotate_log_file\|_log_line_timestamp\|_log_int_env" scripts/rpa/inventory/inventory_rpa_worker.py 确认零残留(若 worker_disk_cleanup 或测试引用了这些名字,逐一改为公共模块引用)。
  • Step 2: 回归

Run: cd backend && python -m pytest -q tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_inventory_rpa_download_save_fallback.py tests/test_rpa_worker_heartbeat.py tests/test_rpa_trigger_consumer.py tests/test_rpa_worker_logging.py Expected: 除已知 2 个 reuse_session 既有失败外全绿;日志相关行为断言(若有引用内部名的用例)按公共模块名等价更新并在注释说明。

  • Step 3: 提交
git add scripts/rpa/inventory/inventory_rpa_worker.py
git commit -m "refactor(rpa): 库存Worker日志切换公共worker_logging模块"

Task 3: 收料 Worker 接入文件日志 + 完整 banner + 全路径留痕

Files:

  • Modify: scripts/rpa/receipt/receipt_rpa_worker.py
  • Modify: scripts/rpa/receipt/start_receipt_worker.ps1(补 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE)
  • Test: backend/tests/test_freight_receipt_worker_contract.py(追加静态断言)

Interfaces:

  • Consumes: Task 1 configure_file_logging / maybe_rotate_open_log;Task 2 后 inventory 与 receipt 共用同一模块。

  • Produces: 收料 Worker 启动即落盘 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 指向的文件;每个 trigger 的领取/归档、每个单元的成功/失败、每批次开始均有带时间戳日志。

  • Step 1: 写失败测试(追加静态契约断言)

def test_receipt_worker_logs_full_lifecycle_and_banner():
    """收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
    text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
    assert 'configure_file_logging' in text
    assert 'maybe_rotate_open_log' in text
    assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text  # banner 对齐库存字段
    assert '[receipt-unit] success' in text  # 成功单元留痕(此前成功路径零输出)
    assert '[receipt-unit] failed' in text
    assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
  • Step 2: 运行确认失败

Run: cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py::test_receipt_worker_logs_full_lifecycle_and_banner Expected: FAIL

  • Step 3: 实现收料 Worker 改动
  1. 导入区(from trigger_consumer import ... 旁)加:
import worker_logging  # noqa: E402

后续全部使用 worker_logging. 限定名(configure_file_logging / maybe_rotate_open_log / active_log_path)。

  1. 新增本地掩码辅助(放 _require_dir 前):
def _mask_secret(value: str | None) -> str:
    """掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
    value = str(value or '').strip()
    if len(value) <= 8:
        return '***' if value else 'missing'
    return f'{value[:4]}....{value[-4:]}'
  1. main() 重写为(保持轮询骨架与 trigger_consumer 用法不变):
def main() -> None:
    """轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
    worker_logging.configure_file_logging()  # 未配置 LOG_FILE 时 no-op,仅 stdout
    drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
    trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
    poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
    # [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
    print(
        '[freight_receipt_rpa_worker] started\n'
        f'  mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n'
        f'  api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
        f'  poll_seconds={poll}\n'
        f'  headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} '
        f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
        f'  auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
        f'  credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n'
        f'  trigger_dir={trigger_dir}\n'
        f'  drop_dir={drop_dir}\n'
        f'  browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
        f'  log={worker_logging.active_log_path() or "stdout-only"}'
    )
    while True:
        for path in sorted(trigger_dir.glob('*.json')):
            worker_logging.maybe_rotate_open_log()
            try:
                _claim_and_process(path, drop_dir)
            except Exception as exc:
                print(f'[receipt-trigger] failed {path.name}: {exc}')
        time.sleep(poll)

执行说明:main() 内其他 worker_logging.* 限定名(banner 的 active_log_path()、循环内的 maybe_rotate_open_log())与本步使用同一 import worker_logging 导入,无需再单独 from-import。

  1. _claim_and_process 补领取/归档留痕:
    claimed = claim_trigger(path)
    if claimed is None:
        return
    print(f'[receipt-trigger] claimed {claimed.name}')
    try:
        _process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
        archive_trigger(claimed, 'processed')
        print(f'[receipt-trigger] archived processed {claimed.name}')
    except (Exception, SystemExit):
        # SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
        # 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
        archive_trigger(claimed, 'failed')
        print(f'[receipt-trigger] archived failed {claimed.name}')
        raise
  1. _process_units 分组循环开头与单元回调处补留痕:
    for (connector, _profile, login_url), group in grouped.items():
        print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
        # …… 原逻辑不变,成功回调前补:
                        print(
                            f'[receipt-unit] success source={unit["source_code"]} '
                            f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
                        )
                        _post_callback({...})  # 原样
  1. _report_failure 补一行(回调前):
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
    """失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
    print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
    _post_callback({...})  # 原样
  1. start_receipt_worker.ps1 的 $processVars 有序表追加(SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS 行之后):
    SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log'
  • Step 4: 运行确认通过

Run: cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_rpa_worker_logging.py Expected: 全部 passed(既有「只消费 receipt 目录/无 freight_rpa_worker 字样」等断言不受影响——banner 前缀仍是 [freight_receipt_rpa_worker])

  • Step 5: 提交
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/receipt/start_receipt_worker.ps1 backend/tests/test_freight_receipt_worker_contract.py
git commit -m "feat(rpa): 收料Worker补文件日志完整banner与全路径留痕"

Task 4: 收料 Worker 心跳对齐(独立 Worker 身份)

Files:

  • Modify: scripts/rpa/receipt/receipt_rpa_worker.py
  • Modify: scripts/rpa/receipt/start_receipt_worker.ps1(补 SHIPPING_NOTICE_RPA_WORKER_ID)
  • Test: backend/tests/test_rpa_worker_heartbeat.py(追加收料侧静态断言)+ test_freight_receipt_worker_contract.py

Interfaces:

  • Consumes: 既有 rpa_heartbeat.maybe_send_heartbeat(trigger_dir=, drop_dir=, last_sent_mono=, force=) 与 start_heartbeat_loop(trigger_dir=, drop_dir=, interval_seconds=)(与库存 Worker main 中的调用形态一致,镜像即可);后端端点 POST /api/shipping-notice/rpa/heartbeat(已存在,不改)。

  • Produces: 监控端出现独立收料 Worker 卡片(<hostname>-receipt),上报运行态 idle/busy 与收料 trigger/drop 积压。

  • Step 1: 写失败测试(追加到 test_freight_receipt_worker_contract.py)

def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
    """收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
    text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
    assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
    ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
    assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
  • Step 2: 运行确认失败

Run: cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py::test_receipt_worker_reports_heartbeat_with_dedicated_identity Expected: FAIL

  • Step 3: 实现
  1. receipt_rpa_worker.py 导入区加 import rpa_heartbeat # noqa: E402(common 已在 sys.path)。
  2. main() 中 STEP 1 banner 之后、while True 之前补(镜像库存 Worker main 的接线):
    heartbeat_seconds = max(
        15,
        int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
    )
    rpa_heartbeat.maybe_send_heartbeat(
        trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
    )
    rpa_heartbeat.start_heartbeat_loop(
        trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
    )
    print(f'  heartbeat_seconds={heartbeat_seconds}')

(banner 文本补一行 heartbeat_seconds=;set_worker_runtime_status 不需要——收料单线程串行,processing 期间保持 idle 口径与 _scan_triggers 语义差异可接受;若要完全对齐库存,可在 _claim_and_process 领取成功后 rpa_heartbeat.set_worker_runtime_status("busy")、finally 里 set_worker_runtime_status("idle")——要求做上,与库存监控语义一致。)

  1. start_receipt_worker.ps1 $processVars 追加:
    SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
    SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20'
  • Step 4: 运行确认通过

Run: cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_rpa_worker_heartbeat.py Expected: 全部 passed(若 test_rpa_worker_heartbeat.py 有按 worker id 断言的用例,确认不受新 id 影响)

  • Step 5: 提交
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/receipt/start_receipt_worker.ps1 backend/tests/test_freight_receipt_worker_contract.py
git commit -m "feat(rpa): 收料Worker接入心跳上报并使用独立Worker身份"

Task 5: 收料 Worker 磁盘保留清理 + 孤儿 receipt_* Profile 清理

Files:

  • Modify: scripts/rpa/receipt/receipt_rpa_worker.py(主循环周期清理)
  • Modify: scripts/rpa/common/worker_disk_cleanup.py(孤儿 Profile 匹配前缀扩展 receipt_*)
  • Test: backend/tests/test_rpa_trigger_consumer.py 追加静态断言;worker_disk_cleanup 行为测试追加 receipt_* 用例(找到该模块既有测试文件并跟随其模式)

Interfaces:

  • Consumes: run_worker_disk_cleanup(*, inventory_trigger_dir, upload_trigger_dir, drop_dir, upload_queue_dir, browser_profile_dir, log_file, now_unix) 全参数默认 None;cleanup_interval_seconds()、format_cleanup_summary(stats)。收料映射:inventory_trigger_dir=<收料 trigger 根>(该函数只清 processed/failed 归档 JSON,绝不碰根目录待领取 *.json)、drop_dir=<收料 drop>、browser_profile_dir=<共享 profile 根>、log_file=<收料日志路径>、upload_trigger_dir/upload_queue_dir=None。

  • Produces: 收料 Worker 每 SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS(默认同库存)执行一轮保留清理,并打印与库存同格式的 summary;崩溃残留的 receipt_* 临时 Profile 超期后被清理。

  • Step 1: 写失败测试

静态断言(追加到 test_rpa_trigger_consumer.py):

def test_receipt_worker_runs_periodic_disk_cleanup():
    """收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
    receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
    assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
    cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
    assert '"receipt_"' in cleanup or "'receipt_'" in cleanup

行为测试(在 worker_disk_cleanup 既有测试文件追加,跟随其 fixture 模式):

def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
    """崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。"""
    root = tmp_path / "browser_profile"
    stale_receipt = root / "receipt_abcd1234"; stale_receipt.mkdir()
    session_dir = root / "dsv_session"; session_dir.mkdir()
    old = time.time() - 10 * 24 * 3600
    os.utime(stale_receipt, (old, old))
    stats = DiskCleanupStats()
    cleanup_orphan_runtime_profiles(root, cutoff_unix=time.time(), stats=stats)
    assert not stale_receipt.exists() and session_dir.exists()

(导入路径/Stats 构造以该测试文件既有写法为准。)

  • Step 2: 运行确认失败

Run: cd backend && python -m pytest -q tests/test_rpa_trigger_consumer.py::test_receipt_worker_runs_periodic_disk_cleanup Expected: FAIL

  • Step 3: 实现
  1. worker_disk_cleanup.py:孤儿 Profile 前缀元组化——
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
# cleanup_orphan_runtime_profiles 中 `if not name.startswith("run_"):` 改为
#     `if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):`
# docstring 补一句:收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。

(str.startswith 接受元组,无需循环。)

  1. receipt_rpa_worker.py 导入区加:
import worker_disk_cleanup  # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup  # noqa: E402
  1. main():banner 后补启动即清一轮 + 主循环按间隔清理(对齐库存节奏;收料无 upload/queue 目录,对应参数传 None):
    last_cleanup_mono = 0.0
    cleanup_interval = cleanup_interval_seconds()

    def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
        """按间隔执行保留清理;启动时强制一轮。返回更新后的上次清理时间。"""
        nonlocal last_cleanup_mono
        if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
            return last_cleanup_mono
        profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
        stats = run_worker_disk_cleanup(
            inventory_trigger_dir=trigger_dir,  # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
            drop_dir=drop_dir,
            browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
            log_file=worker_logging.active_log_path(),
        )
        print(format_cleanup_summary(stats))
        return now_mono

    last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)

主循环 while True: 内 time.sleep(poll) 前补 last_cleanup_mono = _run_cleanup_if_due(time.monotonic())。 banner 补一行 disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}。

  • Step 4: 运行确认通过

Run: cd backend && python -m pytest -q tests/test_rpa_trigger_consumer.py tests/test_rpa_worker_logging.py(以及 worker_disk_cleanup 既有测试文件——用 grep -rln "worker_disk_cleanup" backend/tests 找到后一并跑) Expected: 全部 passed

  • Step 5: 提交
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/common/worker_disk_cleanup.py backend/tests/test_rpa_trigger_consumer.py <disk_cleanup 测试文件>
git commit -m "feat(rpa): 收料Worker周期磁盘保留清理并覆盖receipt孤儿Profile"

Task 6: 文档契约同步

Files:

  • Modify: scripts/rpa/README.md

  • Modify: docs/features/shipping-notice/technical.md(§1.9 收料 Worker 部署增量;该文件可能有用户 in-flight 改动——只编辑,提交与否以当时工作树状态由执行者按控制器指令处理;默认不提交,与此前裁定一致)

  • Step 1: README 增「Worker 运行能力对齐表 + 日志」小节(四态契约小节之后)

## Worker 运行能力(库存 / 收料对齐)

| 能力 | 库存 Worker | 收料 Worker |
| --- | --- | --- |
| 文件日志(tee+时间戳+轮转) | `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_receipt_rpa\logs\worker.log`) |
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
| 心跳上报 | `<hostname>` | `<hostname>-receipt`(独立身份,ps1 注入) |
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`) |

规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
  • Step 2: technical.md §1.9 收料 Worker 部署增量处补两行

在收料 Worker 部署变量说明处补:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE(ps1 自动设为 logs\worker.log)与 SHIPPING_NOTICE_RPA_WORKER_ID=<主机名>-receipt(独立心跳身份);并注明日志/心跳/清理能力已与库存 Worker 对齐。

  • Step 3: 提交
git add scripts/rpa/README.md
git commit -m "docs(rpa): 补收料Worker运行能力对齐说明与日志独立规则"

Task 7: 回归 + 本机验收

Files: 无新改动(发现问题回对应任务修复后重跑)

  • Step 1: 全量相关回归

Run: cd backend && python -m pytest -q tests/test_rpa_worker_logging.py tests/test_freight_receipt_worker_contract.py tests/test_rpa_trigger_consumer.py tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_rpa_worker_heartbeat.py tests/test_inventory_rpa_download_save_fallback.py tests/test_freight_receipt_rpa_callback.py tests/test_freight_receipt_rpa_schedule.py Expected: 除已知 2 个 reuse_session 既有失败外全绿。

  • Step 2: 语法编译

Run: cd backend && python -m py_compile ../scripts/rpa/common/worker_logging.py ../scripts/rpa/common/worker_disk_cleanup.py ../scripts/rpa/inventory/inventory_rpa_worker.py ../scripts/rpa/receipt/receipt_rpa_worker.py Expected: 无输出

  • Step 3: 本机人工验收(含上次遗留的 env 修正)
  1. 先修本机环境:当前 shell/系统里旧的 SHIPPING_NOTICE_RPA_SHARED_RECEIPT_{TRIGGER,DROP}_DIR(指向 receipts_triggers 复数旧目录)必须删除或改为 backend\data\shipping_notice\freight_receipt_rpa\receipt_triggers/receipt_drop(rpa_common._env 只读进程环境变量、不读 .env 文件)。
  2. 设 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后裸跑收料 Worker:确认 banner 全字段落盘到 freight_receipt_rpa/logs/worker.log 且行首有时间戳。
  3. SHIPPING_NOTICE_RPA_WORKER_MOCK=true 跑一次 mock trigger:确认 [receipt-trigger] claimed → [receipt-unit] success → archived processed 全链路留痕。
  4. 管理端 Worker 监控确认出现 <主机名>-receipt 独立在线卡片(心跳 20s)。
  5. 库存 Worker 照常启动一次,确认日志行为与改前一致(tee 启动行、轮转配置打印)。
  • Step 4: 执行记录

结果写入本文件末尾「执行记录」小节。

明确不做

  • 库存 Worker 除日志委托切换外的任何行为改动(心跳/清理/触发保持原样)。
  • 后端 API/监控端改动(心跳端点已存在,新 Worker 身份自动出现卡片)。
  • 收料 Worker 的失败自动重试(冻结决策:只标失败人工重试)。
  • 把两个 Worker 的日志合并到一个文件(多进程共写是反模式)。

执行记录(2026-09-18,Subagent-Driven Development)

结果:7 个任务全部完成 + 最终全分支审查「With fixes」→ 文档修复波收口 → 复审 all findings addressed。

提交清单(base 051f80e1e,7 个提交): 9eabcc2b9 提取 worker_logging → 2a1fcfd91 库存 Worker 委托切换 → f3655a4c5 收料文件日志+banner+留痕 → 5b5ab263b 心跳独立身份 → 54cf2a4f4 磁盘清理+receipt_* 孤儿(含 try/except 修复轮)→ b00194dcd 文档契约(含 5 处矛盾句修复轮)→ 20d41fa41 终审文档偏差修正(technical.md §1.9 入库 + 库存身份口径 + 幽灵文件名 + banner 描述)。

回归:Task 7 全量 sweep 147 passed / 4 failed(全部为计划前既有基线:reuse_session×2 + heartbeat Flask fail-fast×2)/ 1 skipped;py_compile 通过。

执行中的两次裁定修正:

  1. T5 清理闭包缺 try/except(库存参照版有)——SMB 抖动可杀主循环,补包裹 + 失败推进时钟 + 年轻 receipt_* 存活断言(54cf2a4f4)。
  2. T6 文档 5 处旧句与新增能力矛盾——全部修订并修正 §1.9.3 幽灵文件名(b00194dcd)。

待人工完成(Task 7 Step 3 本机验收):

  1. 清除 shell/系统环境变量中旧的 SHIPPING_NOTICE_RPA_SHARED_RECEIPT_{TRIGGER,DROP}_DIR(指向 receipts_triggers 复数旧目录)或改为规范路径——rpa_common._env 只读进程环境变量、不读 .env 文件。
  2. 设 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 裸跑收料 Worker:banner 全字段落盘 freight_receipt_rpa/logs/worker.log 且行首带时间戳。
  3. SHIPPING_NOTICE_RPA_WORKER_MOCK=true 跑一次 mock trigger:[receipt-trigger] claimed → [receipt-unit] success → archived processed 全链路留痕。
  4. 管理端 Worker 监控确认 <主机名>-receipt 独立在线卡片。
  5. 库存 Worker 照常启动一次,确认日志行为与改前一致。

后续跟进建议(终审提出,均 SHIP 不阻塞):WorkerLogTee 加线程锁、收料 rotate 调用移到清理节奏、build_heartbeat_payload capabilities 按 Worker 参数化、关闭 4 个既有测试基线失败。