""" tests/test_shipping_process_gate_lease.py 用途:验证门禁 Attempt 租约竞争、心跳续租与超时接管。 依赖:process_gate_job_service、process_gate_service、Flask testing app。 逻辑:创建 queued Attempt 后双 Worker claim,仅一方持有租约;心跳超时后 recover 接管。 """ from __future__ import annotations from datetime import datetime, timedelta from app import db from app.models import ShippingProcessGateAttempt from app.services.shipping_notice.process_gate_job_service import ( claim_and_run_gate_attempt, heartbeat_gate_attempt, recover_stale_gate_attempts, ) from app.services.shipping_notice.process_gate_service import ( ensure_execution_for_workflow_version, mark_attempt_running, queue_gate_attempt, ) from tests.test_shipping_process_gate_service import _seed_workflow_version def test_lease_takeover_after_stale_heartbeat(app, monkeypatch): """心跳超过接管阈值后,recover_stale_gate_attempts 必须接管。""" with app.app_context(): monkeypatch.setattr( 'app.services.shipping_notice.process_gate_job_service._takeover_seconds', lambda: 30, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', lambda **kwargs: 0, ) _user, review_case_id, task_id = _seed_workflow_version(suffix='lease1') execution = ensure_execution_for_workflow_version( review_case_id=review_case_id, task_id=task_id, actor_type='system', actor_id='lease-test', ) attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='layout_parsing', trigger_type='user_retry', actor_type='system', actor_id='w1', idempotency_key='lease-takeover-1', ) mark_attempt_running( attempt_id=int(attempt.id), worker_id='worker-a', lease_token='token-a', lease_expires_at=datetime.utcnow() - timedelta(seconds=120), ) # 心跳早于接管阈值(默认/补丁 30s)即可被 recover 选中。 attempt.heartbeat_at = datetime.utcnow() - timedelta(seconds=120) db.session.flush() taken = recover_stale_gate_attempts(worker_id='worker-b') assert int(attempt.id) in taken db.session.refresh(attempt) assert attempt.status == 'queued' assert attempt.worker_id is None assert attempt.lease_token is None def test_heartbeat_rejects_foreign_lease(app): """租约 Token 不匹配时心跳必须 Conflict。""" from app.core.errors import ConflictError with app.app_context(): _user, review_case_id, task_id = _seed_workflow_version(suffix='lease2') execution = ensure_execution_for_workflow_version( review_case_id=review_case_id, task_id=task_id, actor_type='system', actor_id='lease-test', ) attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='layout_parsing', trigger_type='auto', actor_type='system', actor_id='w1', idempotency_key='lease-hb-1', ) mark_attempt_running( attempt_id=int(attempt.id), worker_id='worker-a', lease_token='token-a', lease_expires_at=datetime.utcnow() + timedelta(seconds=60), ) try: heartbeat_gate_attempt( attempt_id=int(attempt.id), worker_id='worker-b', lease_token='wrong', ) assert False, 'expected ConflictError' except ConflictError as err: assert err.code == 'SHIPPING.PROCESS_GATE_LEASE_CONFLICT' def test_sync_manual_open_via_claim_and_run(app, monkeypatch): """claim_and_run 对同步人工入口动作可完成 Attempt。""" with app.app_context(): # enqueue 在 recover 空跑时无副作用;claim 路径执行 open_order_review。 monkeypatch.setattr( 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', lambda **kwargs: 0, ) _user, review_case_id, task_id = _seed_workflow_version(suffix='lease3') execution = ensure_execution_for_workflow_version( review_case_id=review_case_id, task_id=task_id, actor_type='system', actor_id='lease-test', ) # 先阻断冻结门禁,再排队人工打开动作。 from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome apply_gate_outcome( execution=execution, gate_code='order_freeze_readiness', passed=False, blocking_reason_code='auto_freeze_not_enabled', effective_result={'findings': []}, force=True, idempotency_key='freeze-block-1', ) gate = db.session.query(__import__('app.models', fromlist=['ShippingProcessGate']).ShippingProcessGate).filter_by( execution_id=int(execution.id), gate_code='order_freeze_readiness', ).first() attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='order_freeze_readiness', trigger_type='user_manual', actor_type='user', actor_id=1, idempotency_key='open-review-1', expected_gate_version=int(gate.evaluation_version), input_snapshot={'action_code': 'open_order_review', 'payload': {'actor_user_id': 1}}, ) result = claim_and_run_gate_attempt(attempt_id=int(attempt.id), worker_id='worker-sync') assert result.get('skipped') is False db.session.refresh(attempt) assert attempt.status in {'succeeded', 'failed'} def test_lock_execution_gate_attempt_parent_before_child(app): """[断言] 助手按 Execution→Gate→Attempt 返回隶属一致的三元组;mark/complete 同步改 Gate。""" from app.models import ShippingProcessGate from app.services.shipping_notice.process_gate_service import ( _lock_execution_gate_attempt, complete_gate_attempt, ) with app.app_context(): _user, review_case_id, task_id = _seed_workflow_version(suffix='lockord1') execution = ensure_execution_for_workflow_version( review_case_id=review_case_id, task_id=task_id, actor_type='system', actor_id='lock-order-test', ) attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='layout_parsing', trigger_type='auto', actor_type='system', actor_id='w1', idempotency_key='lock-order-1', ) locked = _lock_execution_gate_attempt(int(attempt.id)) assert locked is not None locked_execution, locked_gate, locked_attempt = locked assert int(locked_execution.id) == int(execution.id) assert int(locked_gate.execution_id) == int(locked_execution.id) assert int(locked_attempt.gate_id) == int(locked_gate.id) mark_attempt_running( attempt_id=int(attempt.id), worker_id='worker-lock', lease_token='token-lock', lease_expires_at=datetime.utcnow() + timedelta(seconds=60), ) gate = ShippingProcessGate.query.filter_by(id=int(attempt.gate_id)).one() assert gate.status == 'running' complete_gate_attempt( attempt_id=int(attempt.id), outcome='passed', output_snapshot={'ok': True}, ) db.session.refresh(gate) db.session.refresh(attempt) assert gate.status == 'passed' assert attempt.status == 'succeeded'