Files
syops/backend/tests/test_shipping_process_gate_service.py
T
hugo fbca0b485c feat(shipping-notice): 完善处理投影与待办轮询
- 统一处理阶段、Gate 状态及跨页面投影
- 优化订单提取自动推进与待办分类查询
- 完善任务中心待办与批次轮询逻辑
- 补充后端投影、Gate、查询及 Worker 测试
- 新增待办轮询设计文档并更新技术文档
2026-09-14 17:06:11 +08:00

1192 lines
35 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
tests/test_shipping_process_gate_service.py
用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与全量 Gate 接线矩阵。
依赖:Flask testing app、process_gate_service、process_gate_bridge、process_gate_contract。
逻辑:最小 User/Task 夹具上创建 Execution;对每个 Gate 覆盖
passed / blocked_manual / failed_terminal;断言指纹未变不重跑;Gate 数量由契约驱动。
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
import pytest
from app import db
from app.models import (
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES, PROCESS_GATE_DEFINITIONS
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
ensure_process_gates_for_execution,
invalidate_downstream_gates,
queue_gate_attempt,
sync_gate_from_business_result,
)
def _seed_workflow_version(
suffix: str = '001',
*,
owner: User | None = None,
) -> tuple[User, int | None, int | None]:
"""
创建最小 User + ShippingOrderTask,供 Execution 绑定 review_case_id / task_id。
co8 后不再创建 Workflow 台账;保留函数名以兼容其它门禁测试模块 import。
Args:
suffix: 用于编号去重的后缀。
owner: 非空时 Task 归属该用户;否则新建 gate 测试用户。
Returns:
(user, review_case_id, task_id)
"""
tag = str(suffix or '001')[:40]
user = owner
if user is None:
user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(
task_no=f'OT-SN-GATE-{tag}',
user_id=int(user.id),
source_type='direct_pdf',
)
db.session.add(task)
db.session.flush()
return user, None, int(task.id)
@pytest.fixture
def gate_execution(app):
"""提供已初始化全量 Gate 的 Execution(数量由 PROCESS_GATE_DEFINITIONS 驱动)。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version()
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='test',
)
db.session.commit()
yield execution
def test_ensure_execution_creates_all_contract_gates(gate_execution):
"""创建 Execution 时必须初始化契约定义的全部 Gate 行(禁止硬编码 19/20)。"""
gates = ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
assert len(gates) == len(PROCESS_GATE_CODES)
def test_existing_execution_gate_sequence_is_reconciled_to_current_contract(gate_execution):
"""既有 Execution 的 Gate 顺序必须跟随当前契约修正,不能继续沿用旧 sequence_no。"""
gates = {
gate.gate_code: gate
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
}
# 先移到不冲突的临时区间,再模拟旧版顺序。
for index, gate in enumerate(gates.values(), start=1):
gate.sequence_no = 100 + index
db.session.flush()
gates['task_creation'].sequence_no = 12
gates['order_freeze_readiness'].sequence_no = 10
gates['inventory_source_routing'].sequence_no = 11
gates['inventory_preparation'].sequence_no = 13
db.session.flush()
ensure_process_gates_for_execution(gate_execution)
db.session.commit()
assert gates['task_creation'].sequence_no == 10
assert gates['order_freeze_readiness'].sequence_no == 11
assert gates['inventory_source_routing'].sequence_no == 12
assert gates['inventory_preparation'].sequence_no == 13
assert set(gates) == set(PROCESS_GATE_CODES)
assert gate_execution.current_gate_code == 'document_materialization'
def test_ensure_execution_for_task_ignores_superseded_execution(app):
"""Task 指针指向已替代 Execution 时必须创建新正式链,不能复用历史 Gate。"""
with app.app_context():
_user, _review_case_id, task_id = _seed_workflow_version(suffix='superseded-task')
old = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
old.status = 'superseded'
db.session.flush()
current = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
assert current.id != old.id
assert current.status == 'active'
def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeypatch):
"""首次进入库存准备没有任何 RPA Attempt 时,自动推进必须投递一次 trigger。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=1))[1],
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **_kwargs: None,
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert len(queued) == 1
assert queued[0]['gate_code'] == 'inventory_preparation'
def test_auto_progress_seeds_pending_inventory_preparation_after_routing_pass(
gate_execution, monkeypatch,
):
"""人工指定源使 routing passed 后,必须补种并入队 pending 的库存准备。
[回归] pending 门禁 next_action_code 为空时旧逻辑静默 return,工作台永久显示
「库存文件未准备」;手动选源即定论,应按冻结源执行准备,不得再停在路由。
"""
from app.services.shipping_notice import process_gate_service
for prior_gate in ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
).all():
prior_gate.status = 'passed'
prior_gate.next_action_code = None
prep = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
prep.status = 'pending'
prep.next_action_code = None
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'inventory_preparation'
assert prep.next_action_code is None
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=91))[1],
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **_kwargs: None,
)
routing = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_source_routing',
).one()
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=routing,
)
assert prep.next_action_code == 'retry_inventory_preparation'
assert gate_execution.primary_next_action_code == 'retry_inventory_preparation'
assert len(queued) == 1
assert queued[0]['gate_code'] == 'inventory_preparation'
assert queued[0]['input_snapshot']['action_code'] == 'retry_inventory_preparation'
assert queued[0]['input_snapshot']['payload']['trigger'] == 'gate_attempt_passed'
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
from app.services.shipping_notice import process_gate_service
from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt
for prior_gate in ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
).all():
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
))
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(process_gate_service, 'queue_gate_attempt', lambda **kwargs: queued.append(kwargs))
process_gate_service._enqueue_auto_progress_after_gate_pass(execution=gate_execution, gate=gate)
assert queued == []
def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution, monkeypatch):
"""库存已入库后的 upload_inventory_file 是导航动作,不能被自动续跑执行。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_rpa_timeout'
gate.next_action_code = 'upload_inventory_file'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: queued.append(kwargs),
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert queued == []
def test_refresh_pointers_skips_stale_invalidated_when_downstream_blocked(gate_execution):
"""已建单成功后又被标 invalidated 的上游,不得盖住下游真实 blocked_manual。
复现:task_creation 已 passed_at + invalidated,inventory_sufficiency=blocked_manual;
刷新指针必须停在库存充足性,而不是「生成订单草稿」。
"""
from datetime import datetime, timezone
from app.services.shipping_notice import process_gate_service
now = datetime.now(timezone.utc).replace(tzinfo=None)
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
if gate.gate_code == 'task_creation':
gate.status = 'invalidated'
gate.passed_at = now
gate.invalidated_at = now
gate.blocking_reason_code = 'gate_invalidated'
gate.next_action_code = 'retry_task_creation'
elif gate.gate_code in {
'document_materialization', 'layout_parsing', 'document_profile_routing',
'order_field_extraction', 'field_completeness', 'reservation_validation',
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
'order_freeze_readiness', 'inventory_source_routing', 'inventory_preparation',
'inventory_field_mapping', 'inventory_matching',
}:
gate.status = 'passed'
gate.passed_at = now
elif gate.gate_code == 'inventory_sufficiency':
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_shortage_review_required'
gate.next_action_code = 'open_shortage_review'
elif gate.gate_code == 'excel_readiness':
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'excel_not_ready'
# 其余保持 pending
db.session.flush()
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'inventory_sufficiency'
assert gate_execution.primary_next_action_code == 'open_shortage_review'
assert gate_execution.status == 'blocked'
def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_execution):
"""故意失效且下游仍为 passed 时,current 必须停在 invalidated,等待重评。"""
from datetime import datetime, timezone
from app.services.shipping_notice import process_gate_service
now = datetime.now(timezone.utc).replace(tzinfo=None)
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
if gate.gate_code == 'task_creation':
gate.status = 'invalidated'
gate.passed_at = now
gate.invalidated_at = now
gate.blocking_reason_code = 'gate_invalidated'
gate.next_action_code = 'retry_task_creation'
else:
gate.status = 'passed'
gate.passed_at = now
db.session.flush()
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'task_creation'
assert gate_execution.status == 'blocked'
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
"""已通过且输入指纹未变的 Gate 不重跑。"""
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
first = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-1',
)
attempts_before = ShippingProcessGateAttempt.query.filter_by(gate_id=int(first.id)).count()
second = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-2',
)
attempts_after = ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count()
assert second.status == 'passed'
assert attempts_after == attempts_before
def test_upstream_invalidation_only_targets_dependents(gate_execution):
"""库存源变化只失效依赖下游,不碰无关前置门禁。"""
apply_gate_outcome(
execution=gate_execution,
gate_code='inventory_matching',
passed=True,
effective_result={'matched': True},
force=True,
idempotency_key='inv-match-pass',
)
apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'ok': True},
force=True,
idempotency_key='doc-pass',
)
invalidated = invalidate_downstream_gates(
execution=gate_execution,
change_type='inventory_source_changed',
)
assert 'inventory_matching' in invalidated
assert 'document_materialization' not in invalidated
doc = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id),
gate_code='document_materialization',
).first()
assert doc.status == 'passed'
def test_invalidation_uses_target_gate_retry_action_not_inventory_reroute_fallback(gate_execution):
"""下游 Excel Gate 失效后只能保留自身的重检动作,不能落入库存源重路由兜底。"""
excel = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='excel_readiness',
).one()
excel.status = 'passed'
db.session.flush()
invalidate_downstream_gates(
execution=gate_execution,
change_type='inventory_file_changed',
)
assert excel.status == 'invalidated'
assert excel.next_action_code == 'recheck_excel_readiness'
def test_queue_gate_attempt_rejects_action_owned_by_another_gate(gate_execution):
"""任何调用方都不能把库存源路由动作创建到 Excel Gate Attempt。"""
from app.core.errors import ValidationError
with pytest.raises(ValidationError) as exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='excel_readiness',
trigger_type='auto',
actor_type='system',
actor_id='test',
idempotency_key='wrong-action-excel-gate',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert getattr(exc.value, 'code', None) == 'SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED'
@pytest.mark.parametrize('gate_code', [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS])
def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate_code):
"""
契约定义的每个 Gate 至少覆盖 passed、blocked_manual、failed_terminal 三类结果。
核心逻辑:同一 Execution 上对目标 Gate 依次同步三类 outcome。
"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32])
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
# [STEP 1] passed
passed = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=True,
effective_result_json={'findings': [], 'case': 'passed'},
idempotency_key=f'{gate_code}:passed',
invalidate_change_type=None,
)
assert passed.status == 'passed'
# [STEP 2] blocked_manual(允许 repass)
blocked = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=False,
blocking_reason_code='gate_invalidated',
effective_result_json={'findings': [], 'case': 'blocked_manual'},
idempotency_key=f'{gate_code}:blocked',
invalidate_change_type=None,
)
assert blocked.status == 'blocked_manual'
# [STEP 3] failed_terminal via complete path after queue
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate_code,
trigger_type='system_requeue',
actor_type='system',
actor_id='test',
idempotency_key=f'{gate_code}:terminal',
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='test')
terminal = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='failed_terminal',
error_code='TECH',
error_summary='technical failed',
effective_result_json={'case': 'failed_terminal'},
)
assert terminal.status == 'failed_terminal'
def test_business_sync_reuses_same_gate_active_attempt(app):
"""Gate 执行器同步同门业务事实时不得递归创建第二个 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='activefactsync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='active-fact-sync',
input_snapshot={
'action_code': 'retry_inventory_preparation',
'payload': {'actor_user_id': 1},
},
)
from app.services.shipping_notice.process_gate_service import mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='active-fact-sync')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_file_missing',
effective_result_json={'findings': [], 'has_inventory_lines': False},
idempotency_key='nested-fact-sync-must-not-queue',
)
assert gate.status == 'running'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_inventory_ready_sync_leaves_retry_preparation_attempt_for_outer_complete(app):
"""库存已就绪时,sync 不得提前收口 retry_inventory_preparation Attempt。
回归:OT 自动推进复用 ready 快照后,handler 内 sync 见 has_inventory_lines=True
若提前 complete,外层 execute_queued_attempt 再 complete 会抛
Attempt already finished,Job rollback 后收成 technical_failure_present,
界面卡在获取库存(真实单 OT-20260908-95514841)。
契约:非 poll 的活动准备 Attempt 由外层统一 complete;sync 只返回、不收口。
"""
from app.services.shipping_notice.process_gate_service import (
complete_gate_attempt,
mark_attempt_running,
)
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='invreadyouter')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id=None,
idempotency_key='inv-ready-outer-complete',
input_snapshot={
'action_code': 'retry_inventory_preparation',
'payload': {'trigger': 'gate_attempt_passed'},
},
)
mark_attempt_running(attempt_id=int(attempt.id), worker_id='inv-ready-outer')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
'derived_fulfillment_status': 'inventory_ready',
},
idempotency_key='inv-ready-must-not-early-complete',
)
db.session.refresh(attempt)
assert gate.status == 'running'
assert attempt.status == 'running'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
# [断言] 外层唯一收口可成功;不得再抛 Attempt already finished。
completed = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='passed',
effective_result_json={'findings': [], 'tool_status': 'ok'},
output_snapshot={'action_code': 'retry_inventory_preparation'},
)
assert completed.status == 'passed'
db.session.refresh(attempt)
assert attempt.status == 'succeeded'
def test_inventory_ready_sync_still_completes_auto_poll_attempt(app):
"""poll_inventory_preparation 无外层 complete,sync 在库存就绪时仍须收口。"""
from app.services.shipping_notice.process_gate_service import mark_attempt_running
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='invreadypoll')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id='external-wait-poll',
idempotency_key='inv-ready-poll-complete',
input_snapshot={
'action_code': 'poll_inventory_preparation',
'payload': {'poll': True},
},
)
mark_attempt_running(attempt_id=int(attempt.id), worker_id='inv-ready-poll')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
},
idempotency_key='inv-ready-poll-must-complete',
)
db.session.refresh(attempt)
assert gate.status == 'passed'
assert attempt.status == 'succeeded'
def test_business_sync_does_not_swallow_passed_when_gate_has_active_user_attempt(app):
"""活动 Attempt 不得吞掉 sync 的 passed 结论。
核心回归:真实任务 SN-20260831-9F25A698 / gate inventory_matching 曾因
同一秒存在管理员手动 override_line_inventory_source(running)而让
sync_fulfillment_gates_from_task 的 match_passed=True 被 active_attempt
短路 `return gate` 丢弃;随后手动动作失败把 gate 覆盖成 blocked_retryable,
右侧前端误显示「自动处理失败」。
契约:当业务事实判定为 passed 时,即使该 gate 上存在一个并发的、非本轮
inventory_preparation 自动轮询的 Attempt,sync 也必须把 passed 写入 gate
(完成该活动 Attempt 收口),而不是静默返回导致真相被覆盖。
"""
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='passnotswallowed')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
# 模拟并发占用的用户手动 Attempt(非 inventory_preparation 自动轮询)。
user_attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_matching',
trigger_type='user_manual',
actor_type='user',
actor_id=1,
idempotency_key='concurrent-user-override',
input_snapshot={'action_code': 'override_line_inventory_source'},
)
mark_attempt_running(attempt_id=int(user_attempt.id), worker_id='concurrent-user')
# 此时业务事实判定 passed(例如 match_status='fulfillable')。
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_matching',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
'match_status': 'fulfillable',
},
idempotency_key='match-passed-not-swallowed',
)
assert gate is not None
assert gate.status == 'passed', (
'gate 上存在并发的非自动轮询 Attempt 时,sync 的 passed 结论被 active_attempt '
'短路丢弃,导致真实成功事实被覆盖为 blocked_retryable'
)
def test_force_business_sync_uses_current_gate_version(app):
"""强制重评不得回放失效前的固定幂等 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='forceversion')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
first = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert first is not None and first.status == 'passed'
first.status = 'invalidated'
first.blocking_reason_code = 'gate_invalidated'
first.evaluation_version = int(first.evaluation_version) + 1
db.session.flush()
second = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert second is not None and second.status == 'passed'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count() == 2
def test_idempotent_queue_replays_same_attempt(gate_execution):
"""相同幂等键只产生一个 Attempt。"""
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
for _ in range(9):
again = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert int(again.id) == int(first.id)
count = ShippingProcessGateAttempt.query.filter_by(idempotency_key='same-key-ten-times').count()
assert count == 1
def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
"""同幂等键跨 Gate / 跨 action 必须 409,禁止复用其他上下文 Attempt。"""
from app.core.errors import ConflictError
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
with pytest.raises(ConflictError) as gate_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='order_extraction',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert gate_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
with pytest.raises(ConflictError) as action_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'open_order_review'},
)
assert action_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').count() == 1
assert int(first.id) == int(
ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').first().id
)
def test_idempotent_key_conflicts_across_execution(app):
"""同幂等键跨 Execution 必须冲突。"""
from app.core.errors import ConflictError
with app.app_context():
_u1, rc1, task1 = _seed_workflow_version(suffix='idem-a')
_u2, rc2, task2 = _seed_workflow_version(suffix='idem-b')
exe1 = ensure_execution_for_workflow_version(
review_case_id=rc1,
task_id=task1,
actor_type='system',
actor_id='test',
)
exe2 = ensure_execution_for_workflow_version(
review_case_id=rc2,
task_id=task2,
actor_type='system',
actor_id='test',
)
db.session.commit()
queue_gate_attempt(
execution_no=exe1.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
with pytest.raises(ConflictError) as exc:
queue_gate_attempt(
execution_no=exe2.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
def test_superseded_execution_rejects_late_business_gate_result(app):
"""候选版本已替换后,迟到结果不得重新写回旧 Gate。"""
from app.core.errors import ConflictError
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='superseded-sync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
execution.status = 'superseded'
db.session.flush()
with pytest.raises(ConflictError) as exc:
sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_preparation_failed',
effective_result_json={'findings': []},
idempotency_key='late-result-must-not-write-superseded-execution',
)
assert exc.value.code == 'SHIPPING.PROCESS_EXECUTION_SUPERSEDED'