feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

@@ -0,0 +1,143 @@
"""
tests/services/shipping_notice/test_inventory_candidate_projection.py
用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。
依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。
逻辑:覆盖 active pointer 缺失 fail-closed、当前版本 facts 输出,以及 stale 匹配阻断。
"""
from __future__ import annotations
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
)
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_facts,
)
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
def _task(task_no: str) -> ShippingNotice:
task = ShippingNotice(
task_no=task_no,
process_status='created',
source_type='manual',
)
db.session.add(task)
db.session.flush()
return task
def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet:
row = ShippingInventoryCandidateSet(
task_id=int(task.id),
set_version=version,
lifecycle_status='frozen',
input_fingerprint=f'fp-{task.task_no}-{version}',
)
db.session.add(row)
db.session.flush()
task.active_inventory_candidate_set_id = int(row.id)
db.session.flush()
return row
def test_prepare_candidate_inventory_lines_blocks_without_active_set(app):
with app.app_context():
task = _task('SN-CAND-001')
db.session.commit()
result = prepare_candidate_inventory_lines(task)
assert result['status'] == 'blocked'
assert result['error_code'] == 'inventory_candidates_missing'
assert result['candidate_set_id'] is None
def test_project_inventory_candidate_facts_reads_current_structured_set(app):
with app.app_context():
task = _task('SN-CAND-002')
candidate_set = _candidate_set(task, version=2)
source = ShippingInventoryCandidateSource(
candidate_set_id=int(candidate_set.id),
source_code='DBS_DUB',
candidate_order=1,
candidate_origin='rule',
)
line = ShippingInventoryCandidateLine(
candidate_set_id=int(candidate_set.id),
line_no=1,
source_line_no='00010',
part_number='PN-1',
reservation_id='3000092917',
source_codes_json=['DBS_DUB'],
)
db.session.add_all([source, line])
db.session.commit()
facts = project_inventory_candidate_facts(task, include_history=True)
assert facts['candidate_set_id'] == candidate_set.id
assert facts['candidate_set_version'] == 2
assert facts['candidate_set_status'] == 'frozen'
assert facts['candidate_source_codes'] == ['DBS_DUB']
assert facts['lines'][0]['candidate_line_id'] == line.id
assert facts['lines'][0]['line_no'] == 1
assert facts['lines'][0]['source_line_no'] == '00010'
assert facts['history'][0]['version'] == 2
def test_project_inventory_candidate_facts_marks_stale_current_match(app):
with app.app_context():
task = _task('SN-CAND-003')
old_set = _candidate_set(task, version=1)
old_line = ShippingInventoryCandidateLine(
candidate_set_id=int(old_set.id),
line_no=1,
source_codes_json=['DBS_OLD'],
)
db.session.add(old_line)
db.session.flush()
new_set = ShippingInventoryCandidateSet(
task_id=int(task.id),
set_version=2,
lifecycle_status='frozen',
input_fingerprint='fp-new',
)
db.session.add(new_set)
db.session.flush()
task.active_inventory_candidate_set_id = int(new_set.id)
db.session.flush()
new_line = ShippingInventoryCandidateLine(
candidate_set_id=int(new_set.id),
line_no=1,
source_codes_json=['DBS_NEW'],
)
db.session.add(new_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
line_key='line-1',
line_index=0,
candidate_set_id=int(old_set.id),
candidate_set_version=1,
candidate_line_id=int(old_line.id),
match_result='matched',
inventory_status='ready',
inventory_source_code='DBS_OLD',
is_current=True,
allowed_source_codes_snapshot=['DBS_OLD'],
detail_json={'disposition': 'ok'},
))
db.session.commit()
facts = project_inventory_candidate_facts(task)
assert facts['blocking_reason']['code'] == 'inventory_candidate_version_stale'
assert facts['candidate_set_id'] == new_set.id
assert facts['line_resolutions'][0]['candidate_set_id'] == old_set.id
@@ -0,0 +1,381 @@
"""
tests/services/shipping_notice/test_reconciliation_phase34_contract.py
用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 +
BRANCH F ownership_anomaly rollback 的合同测试。
依赖:recovery_contract、reconciliation_projector、
reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。
逻辑:
[P3 T1] project_case_automation_status 与原 order_review_projection._project_case_automation_status
的纯状态映射完全对齐(status 七值归一化、retryable 双写、can_auto_create 同源)。
[P3 T2] project_case_allowed_actions 白名单:业务阻断码 → REMOVE_SET 删除 retry;
reconcile_and_progress 注入;derive_blocking_next_actions 裁决动作。
[P3 T3] project_case_user_status 七值映射矩阵(completed/cancelled/waiting_human/
retryable/failed/running/idle)。
[P3 T4] project_case_primary_action 1a~1i CTA 分派矩阵。
[P3 T5] project_review_case_projection_bundle 六字段非空(Case + automation + actions)。
[P4 T6] reconcile_and_progress PRE-CHECK:
a) replay_mode=True + is_admin=False → SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED 422
b) legacy_job_id=999 + is_admin=False → 422
[P4 T7] ownership_anomaly BRANCH F:
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
(这里只测 ValidationError 降级情形 hasattr(case,process_status)=False)。
全部为 pure_unit 或 DB 无关单测,不启动 Flask/Worker,不写 DB。
"""
from __future__ import annotations
import uuid
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
# ============================================================
# 工具:用 SimpleNamespace 构造伪 Model(避免 DB 依赖)
# ============================================================
def _fake_case(**kwargs):
base = {
'id': 1,
'case_no': 'CASE-2608-0042',
'status': 'draft',
'disposition': None,
'candidate_id': None,
'confirmed_task_id': None,
'document_id': 42,
'owner_user_id': 7,
'current_draft': None,
'run': None,
'updated_at': None,
}
base.update(kwargs)
return SimpleNamespace(**base)
def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='shipping_stp_auto_create',
reference_key='CASE-2608-0042', result_json=None):
return SimpleNamespace(
id=job_id,
status=status,
domain=domain,
job_type=job_type,
reference_key=reference_key,
reference_type='shipping_order_review_case_no',
result_json=result_json if isinstance(result_json, dict) else {},
)
# ============================================================
# [P3 T1~T5] 纯投影器四事实同源矩阵
# ============================================================
@pytest.mark.pure_unit
@pytest.mark.parametrize(
'automation_status,retryable_flag,expected_user_status,label',
[
# 七值映射 T3
('completed', False, 'completed', '已完成 → completed'),
('queued', False, 'running', '入队中 → running'),
('running', False, 'running', '运行中 → running'),
('waiting_to_start', False, 'running', '等待启动 → running(系统已负责)'),
('failed', False, 'failed', '业务阻断失败 → failed'),
('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'),
('failed', True, 'retryable', '技术失败 retryable → retryable'),
('idle', False, 'idle', 'Idle → idle(默认)'),
],
ids=lambda t: t[3] if isinstance(t, tuple) else '',
)
def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label):
"""[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。"""
from app.services.shipping_notice.reconciliation_projector import project_case_user_status
case = _fake_case(status='draft')
automation = {'status': automation_status, 'retryable': bool(retryable_flag)}
got = project_case_user_status(case, automation)
assert got == expected_user_status, label
@pytest.mark.pure_unit
@pytest.mark.parametrize(
'bcode,actions_in,retryable,expected_pa_code,variant,label',
[
# T4.1a ownership_anomaly → contact_admin
('ownership_anomaly_xxx', ['view', 'contact_admin'], False, 'contact_admin', 'danger', '1a anomaly → contact_admin'),
# T4.1b duplicate → reconcile_and_progress
('duplicate_decision_required', ['view', 'reconcile_and_progress', 'adjudicate_duplicate'], False, 'reconcile_and_progress', 'primary', '1b duplicate → reconcile_and_progress'),
('SHIPPING.NOTICE_EXACT_DUPLICATE', ['view', 'reconcile_and_progress'], False, 'reconcile_and_progress', 'primary', '1b exact dup → reconcile_and_progress'),
# T4.1c profile_schema_mismatch → open_profile_review
('profile_schema_mismatch', ['view', 'open_profile_review'], False, 'open_profile_review', 'warning', '1c profile mismatch → open_profile_review'),
# T4.1d retryable → retry_stp_auto_create
('stp_job_failed', ['view', 'retry_stp_auto_create'], True, 'retry_stp_auto_create', 'primary', '1d retryable → retry_stp'),
],
ids=lambda t: t[6] if isinstance(t, tuple) else '',
)
def test_p3_t4_primary_action_matrix(bcode, actions_in, retryable, expected_pa_code, variant, label):
"""[P3 T4] project_case_primary_action 1a~1i 分派正确性。"""
from app.services.shipping_notice.reconciliation_projector import (
BlockingReason,
UserStatus,
project_case_primary_action,
)
user_status: UserStatus = 'failed' if bcode in {'profile_schema_mismatch'} else (
'retryable' if retryable else 'waiting_human'
)
blocking: BlockingReason = BlockingReason(code=bcode, i18n_key=None, details=None)
got = project_case_primary_action(user_status, blocking, list(actions_in))
assert got is not None, label
assert got['code'] == expected_pa_code, label
assert got['variant'] == variant, label
@pytest.mark.pure_unit
def test_p3_t2_allowed_actions_inject_reconcile_and_remove_retry():
"""[P3 T2] 业务阻断 → REMOVE_SET 删除 retry_stp_auto_create 且注入 reconcile_and_progress。"""
from app.services.shipping_notice.reconciliation_projector import project_case_allowed_actions
from app.services.shipping_notice.recovery_contract import REMOVE_ACTIONS_WHEN_BLOCKED
case = _fake_case(status='draft', candidate_id=1)
automation = {
'status': 'failed',
'retryable': False, # 业务阻断
'blocking_reason': 'duplicate_decision_required',
'reason_code': 'duplicate_decision_required',
}
actions = project_case_allowed_actions(case, automation=automation, is_admin=False)
# REMOVE_SET:retry_stp_auto_create / retry / retry_parse 必须剔除
for forbidden in REMOVE_ACTIONS_WHEN_BLOCKED:
assert forbidden not in actions
# 注入 reconcile_and_progress(统一对账入口)
assert 'reconcile_and_progress' in actions
# 派生裁决动作 adjudicate_duplicate 必须注入
assert 'adjudicate_duplicate' in actions
@pytest.mark.pure_unit
def test_p3_t5_bundle_six_fields_shapes():
"""[P3 T5] bundle 必返回六个只读字段,结构符合 TypedDict 契约。"""
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
case = _fake_case(status='draft', candidate_id=None)
bundle = project_review_case_projection_bundle(
case,
validation={'can_build': True, 'can_auto_create': True, 'status': 'needs_review'},
post_confirm=None,
is_admin=False,
)
for field in (
'automation', 'available_actions', 'current_gate',
'blocking_reason', 'primary_action', 'user_status',
):
assert field in bundle, f'bundle missing {field}'
assert isinstance(bundle['automation'], dict)
assert isinstance(bundle['available_actions'], list)
assert isinstance(bundle['current_gate'], dict)
assert isinstance(bundle['blocking_reason'], dict)
assert isinstance(bundle['user_status'], str)
# primary_action 可能是 None(极端兜底),但不能是未预期类型
assert bundle['primary_action'] is None or isinstance(bundle['primary_action'], dict)
# ============================================================
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
# ============================================================
def _mock_case_for_p4(case_no='CASE-2608-0042'):
case = _fake_case(status='draft', case_no=case_no, candidate_id=None, confirmed_task_id=None)
case.current_draft = SimpleNamespace(
draft_version=1,
issue_summary_json=[],
validation_result_json={'can_build': True, 'can_auto_create': True},
)
case.run = SimpleNamespace(
run_no='RUN-2608-0042',
schema_version_id=1,
id=9,
)
return case
def _install_minimal_mocks(monkeypatch, case=None):
if case is None:
case = _mock_case_for_p4()
# 1) _require_current_user 的行为在 service 层不被用(函数直接传 user_id/case_no)
# 2) monkeypatch FOR UPDATE 查询和 get_review_case_visible_to_user
from app.services.shipping_notice import reconciliation_service as mod
from app.models import User
class _CaseQuery:
def filter_by(self, **_kw):
return self
def filter(self, *_a, **_kw):
return self
def order_by(self, *_a, **_kw):
return self
def with_for_update(self):
return self
def first(self):
return case
class _UserQuery:
def filter_by(self, **_kw):
return self
def first(self):
return None
def _fake_get(coll, _id): # noqa: ARG001
if coll is User:
return SimpleNamespace(id=1, role='user', email='u@example.com')
return None
def _fake_visible(case_no, user_id, is_admin): # noqa: ARG001
return case
monkeypatch.setattr(mod.ShippingOrderReviewCase, 'query', _CaseQuery())
monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible)
# 避免 Job.query / db.session.get / CaseEvent 等深层调用触发
monkeypatch.setattr(mod.db.session, 'get', _fake_get)
monkeypatch.setattr(mod.db, 'session', MagicMock(
commit=lambda: None,
rollback=lambda: None,
flush=lambda: None,
add=lambda _x: None,
))
# L1-L3 对账直接返回 NONE(避免 hit 真 DB)
mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign]
'match_level': 'NONE',
'confidence': 'LOW',
'task_no': None,
'candidate_matches': [],
'evidence': {},
'match_level_steps': [],
}
mod._case_version = lambda _c: 1 # type: ignore[attr-defined]
mod._check_idempotency = lambda **kw: (str(uuid.uuid4()), None) # type: ignore[attr-defined]
mod._candidate_refresh_resume_stp_flow = lambda **kw: ({}, None, 'not_eligible') # type: ignore[attr-defined]
mod._write_reconcile_audit_and_event = lambda **kw: None # type: ignore[attr-defined]
return case
@pytest.mark.pure_unit
def test_p4_t6a_replay_mode_without_admin_raises(monkeypatch):
"""[P4 T6a] replay_mode=True + is_admin=False → 422 SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
replay_mode=True,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6b_legacy_job_id_without_admin_raises(monkeypatch):
"""[P4 T6b] legacy_job_id=928 + is_admin=False → 422 权限拒绝。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
legacy_job_id=928,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
"""[P4 T6c] legacy_job 必须是 failed/dead,否则 422。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
bad_job = _fake_job(job_id=991, status='running') # 不是失败态
from app.services.shipping_notice import reconciliation_service as mod
def _get(coll, jid): # noqa: ARG001
if str(getattr(coll, '__name__', '')) == 'Job' and jid == 991:
return bad_job
return None
monkeypatch.setattr(mod.db.session, 'get', _get)
with pytest.raises(ValidationError):
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=True,
legacy_job_id=991,
)
# ============================================================
# [P4 T7] BRANCH F ownership_anomaly 422 降级(process_status 不存在)
# ============================================================
@pytest.mark.pure_unit
def test_p4_t7_branch_f_ownership_anomaly_throws_validation(monkeypatch):
"""[P4 T7] L3 + reuse_existing 命中 BRANCH F → 抛 422 hard_isolation=True。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
case = _mock_case_for_p4()
_install_minimal_mocks(monkeypatch, case=case)
from app.services.shipping_notice import reconciliation_service as mod
# 让 L3 → ownership_anomaly:L3 + user_action=reuse_existing (太模糊)
mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign]
'match_level': 'L3',
'confidence': 'LOW',
'task_no': None,
'candidate_matches': [],
'evidence': {'reason': 'too_ambiguous_for_reuse_existing'},
'match_level_steps': [
{'step': 'L1_EXACT', 'matched': False},
{'step': 'L2_FP', 'matched': False},
{'step': 'L3_AMBIGUOUS', 'matched': True},
],
}
# 关键:模拟 ReviewCase 没有 process_status 列 → BRANCH F 必须抛 422(而非软返回 outcome)
assert not hasattr(case, 'process_status')
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='reuse_existing', # 非 adjudicate → BRANCH F
is_admin=True,
)
assert exc.value.code == 'SHIPPING.RECONCILE_OWNERSHIP_ANOMALY'
details = getattr(exc.value, 'details', None) or {}
assert details.get('hard_isolation') is True
assert details.get('match') is not None
# 回滚已调用:验证 db.session.rollback 至少被触发了 1 次(硬隔离验证)
assert mod.db.session.rollback.call_count >= 1 # type: ignore[union-attr]
@@ -0,0 +1,158 @@
"""
tests/services/shipping_notice/test_recovery_contract_phase1.py
用途:Phase 1 合同测试 — 锁定错误分类白名单与阻断→动作映射的纯函数矩阵。
依赖:recovery_contract(is_tech_retryable_error、build_stp_job_blocked_manual_result、
should_general_retry_be_removed、derive_blocking_next_actions)。
逻辑:纯单元测,不依赖 DB/Worker,确保 T1 错误分类矩阵与 T3 动作注入判定
与 Phase 1 冻结契约一致;一旦白名单/阻断规则被误修改将立即红。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.recovery_contract import (
RECOVERY_CONTRACT_VERSION,
BLOCKING_REASON_TO_ACTION_CODES,
REMOVE_ACTIONS_WHEN_BLOCKED,
build_stp_job_blocked_manual_result,
build_stp_job_failed_transient_result,
derive_blocking_next_actions,
is_tech_retryable_error,
should_general_retry_be_removed,
)
# ============================================================
# T1:is_tech_retryable_error 白名单矩阵(fail-closed)
# ============================================================
T1_MATRIX = [
# (error_code, category_hint, expected_retryable, case_label)
('SHIPPING.TRANSIENT_NETWORK_TIMEOUT', None, True, 'TRANSIENT_ 前缀 → 技术临时网络'),
('SHIPPING.TRANSIENT_STORAGE_CONNECTION', None, True, 'TRANSIENT_ 前缀 → 技术存储'),
('SHIPPING.WORKER_TIMEOUT_LEASE_EXPIRED', None, True, 'WORKER_TIMEOUT_ 前缀'),
('worker_timeout', 'worker_timeout', True, 'category_hint=worker_timeout'),
('queue_unavailable', 'queue_unavailable', True, 'category_hint=queue_unavailable'),
('temporary_network_error', 'temporary_network_error', True, 'category_hint 网络临时'),
('temporary_storage_error', 'temporary_storage_error', True, 'category_hint 存储临时'),
('external_service_5xx', 'external_service_5xx', True, 'category_hint 外部 5xx'),
('lease_expired', 'lease_expired', True, 'category_hint 租约过期'),
# 业务阻断码:默认不可重试(Q5 白名单制,不在即拒绝)
('SHIPPING.NOTICE_EXACT_DUPLICATE', None, False, '精确重复 — 业务阻断,不可重试'),
('SHIPPING.STP_NOT_ELIGIBLE', None, False, 'STP 资格不足 — 业务阻断'),
('SHIPPING.REVIEW_DRAFT_MISSING', None, False, '草稿缺失 — 业务阻断'),
('SHIPPING.REVIEW_RUN_MISSING', None, False, 'Run 缺失 — 业务阻断'),
('SHIPPING.REVIEW_DOCUMENT_INVALID', None, False, '文档无效 — 业务阻断'),
('SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', None, False, '版本冲突 — 业务阻断,应 409 让前端刷新'),
('profile_schema_mismatch', None, False, 'Profile 模板不匹配 — 业务阻断'),
('final_required_field_missing', None, False, '关键字段缺失 — 业务阻断'),
('duplicate_decision_required', None, False, '等待重复裁决 — 业务阻断'),
# 空码/未知码:fail-closed(默认不可重试,不能因空码回退到 retryable=true)
('', None, False, '空码 → fail-closed 不可重试'),
('RANDOM.UNKNOWN_ERROR_XYZ', None, False, '未知码 → fail-closed 不可重试'),
(None, None, False, 'None 码 → fail-closed 不可重试'),
# category_hint 与前缀冲突:前缀优先(空码除外)
('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'),
]
@pytest.mark.parametrize('error_code, category_hint, expected, label', T1_MATRIX, ids=[m[3] for m in T1_MATRIX])
def test_t1_is_tech_retryable_error_matrix(error_code, category_hint, expected, label):
"""T1:错误码 → 是否允许技术自动重试(白名单制,fail-closed)。"""
_ = label
assert is_tech_retryable_error(error_code, category_hint=category_hint) is expected
# ============================================================
# T1-ext:build_stp_job_*_result 的结构契约(Q4 Job.result_json schema)
# ============================================================
def test_t1_blocked_manual_result_shape():
"""阻塞业务错误 → result_json 必含 retryable=false / blocking_reason / next_action。"""
result = build_stp_job_blocked_manual_result(
error_code='SHIPPING.NOTICE_EXACT_DUPLICATE',
message='该文件已存在进行中任务',
next_action='adjudicate_duplicate',
details={'source_content_hash': 'abc123', 'existing_task_no': 'OT-2026-0001'},
)
assert result['status'] == 'failed'
assert result['retryable'] is False
assert result['blocking_reason'] == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
assert result['blocking_reason_details'] == {
'source_content_hash': 'abc123', 'existing_task_no': 'OT-2026-0001',
}
assert result['next_action'] == 'adjudicate_duplicate'
assert result['error_code'] == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
assert result['message'] == '该文件已存在进行中任务'
assert result['contract_version'] == RECOVERY_CONTRACT_VERSION
assert 'decision_trace' in result
def test_t1_transient_result_shape():
"""技术临时错误 → retryable=true,blocking_reason/next_action 置空。"""
result = build_stp_job_failed_transient_result(
error_code='SHIPPING.TRANSIENT_NETWORK_TIMEOUT',
message='Dify API 503',
category_hint='external_service_5xx',
)
assert result['status'] == 'failed'
assert result['retryable'] is True
assert result['blocking_reason'] is None
assert result['next_action'] is None
assert result['contract_version'] == RECOVERY_CONTRACT_VERSION
# ============================================================
# T3:should_general_retry_be_removed + derive 动作矩阵(Q9 后端注入/删除动作)
# ============================================================
T3_MATRIX = [
# (retryable, blocking_code, expected_remove, expected_inject_action, label)
(True, None, False, None, '纯技术失败 → 保留 retry,不注入裁决'),
(False, 'duplicate_decision_required', True, 'adjudicate_duplicate', '重复待决 → 删除 retry + 注入 adjudicate'),
(False, 'SHIPPING.NOTICE_EXACT_DUPLICATE', True, 'adjudicate_duplicate', '精确重复 → 同上'),
(False, 'profile_schema_mismatch', True, 'open_profile_review', 'Profile 不匹配 → 打开模板复核'),
(False, 'SHIPPING.STP_NOT_ELIGIBLE', True, 'open_order_review', 'STP 不满足 → 打开订单复核'),
(False, 'SHIPPING.REVIEW_DRAFT_MISSING', True, 'open_order_review', '草稿缺失 → 打开订单复核'),
(False, 'final_required_field_missing', True, 'open_order_review', '字段缺失 → 打开订单复核'),
]
@pytest.mark.parametrize(
'retryable, bcode, expected_remove, expected_action, label',
T3_MATRIX, ids=[m[4] for m in T3_MATRIX],
)
def test_t3_retry_removed_and_actions_injected(retryable, bcode, expected_remove, expected_action, label):
"""T3:业务阻断时删除通用 retry 动作,并注入对应的裁决/复核动作。"""
_ = label
blocking_reason = {'code': bcode} if bcode else None
assert should_general_retry_be_removed(
retryable_flag=retryable,
blocking_reason=blocking_reason,
) is expected_remove
if bcode:
derived = derive_blocking_next_actions(blocking_reason=blocking_reason)
if expected_action is not None:
assert expected_action in derived
# REMOVE_ACTIONS_WHEN_BLOCKED 必须包含 retry_stp_auto_create(原 Job 928/929 的主重试入口)
assert 'retry_stp_auto_create' in REMOVE_ACTIONS_WHEN_BLOCKED
assert 'retry' in REMOVE_ACTIONS_WHEN_BLOCKED
assert 'retry_parse' in REMOVE_ACTIONS_WHEN_BLOCKED
def test_t3_contract_version_anchor_frozen():
"""契约锚点版本号固定:Phase 1 必须与 shipping-recovery-v1-phase1 对齐,便于审计与迁移。"""
assert RECOVERY_CONTRACT_VERSION == 'shipping-recovery-v1-phase1'
# BLOCKING_REASON_TO_ACTION_CODES 必显式含 6 条核心映射,不能因重构丢失
for key in (
'duplicate_decision_required',
'SHIPPING.NOTICE_EXACT_DUPLICATE',
'profile_schema_mismatch',
'SHIPPING.STP_NOT_ELIGIBLE',
'SHIPPING.REVIEW_DRAFT_MISSING',
'final_required_field_missing',
):
assert key in BLOCKING_REASON_TO_ACTION_CODES