Merge branch 'hugo-auto-transfer' into test

This commit is contained in:
hugo committed 2026-10-07 10:00:14 +08:00
commit 20122ce6d3
11 files changed
+225 -26

No files matched your search

@@ -176,6 +176,9 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
@@ -267,19 +270,40 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
)
def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
stamps = [run.started_at] if run.started_at else []
for unit in units:
if unit.started_at:
stamps.append(unit.started_at)
if unit.finished_at:
stamps.append(unit.finished_at)
return max(stamps)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
return False
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = ShippingReceiptRpaUnitRun.query.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
).all()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
@@ -357,9 +357,6 @@ def prepare_schedule_queue() -> int:
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_recovered:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
@@ -379,6 +376,13 @@ def prepare_schedule_queue() -> int:
if transfer_stale:
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -513,7 +513,7 @@ def _check_rpa_worker_ready_for_capability(
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(收料为 False)。
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
Returns:
RpaWorkerReadiness。
@@ -205,3 +205,66 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
assert path
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists()
assert not list(tmp_path.glob('.*.tmp'))
def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
db.session.add(run); db.session.flush()
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
db.session.commit()
# [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径);
# 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。
assert recover_all_stale_receipt_rpa_schedule_runs() == 1
db.session.refresh(run)
assert run.status == 'failed'
assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout'
def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
db.session.add(run); db.session.flush()
# 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚)
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45)))
db.session.commit()
# [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s——
# 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。
assert recover_all_stale_receipt_rpa_schedule_runs() == 0
db.session.refresh(run)
assert run.status == 'running'
def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
"""哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。"""
import inspect
from app.services.schedule import queue_service
source = inspect.getsource(queue_service)
marker_init = source.index("_worker_initialized = True")
# [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区);
# 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init
assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source
+4 -3
View File
@@ -203,7 +203,7 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""收料 fail-fast 应附带 reasons,且不要求共享哨兵。"""
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
@@ -225,11 +225,12 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_receipt_rpa_worker_ready()
# [断言意图] 与库存同构的用户可见文案与 reasons;收料不因缺哨兵失败。
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
reasons = (exc_info.value.details or {}).get('reasons', [])
assert 'no_worker_heartbeat' in reasons
assert 'shared_sentinel_missing' not in reasons
assert 'shared_sentinel_missing' in reasons
def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):