refactor(agent, shipping): 简化代理模型并完善订单抽取业务
- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
1 parent
1f3ecb87b7
commit
61ac6403c4
159 files changed
+12883
-5099
No files matched your search
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, AgentRuntimeBinding, User
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import agent_service
|
||||
|
||||
|
||||
@@ -85,87 +85,6 @@ def test_update_agent_clears_handler_config_when_explicit_null(app):
|
||||
assert refreshed.handler_config is None
|
||||
|
||||
|
||||
def test_create_agent_and_runtime_binding_are_atomic(app):
|
||||
"""创建货代 Agent 时绑定校验失败必须回滚 Agent,不能留下半配置入口。"""
|
||||
with app.app_context():
|
||||
provider = Agent(
|
||||
name='Invalid Chatflow Provider',
|
||||
agent_code='generic',
|
||||
runtime_provider='dify',
|
||||
dify_app_type='chatflow',
|
||||
exposure_mode='workspace',
|
||||
dify_app_id='invalid-create-provider',
|
||||
dify_api_key='sk-test',
|
||||
api_base_url='http://dify.example/v1',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(provider)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
agent_service.create_agent({
|
||||
'name': 'Atomic Shipping Create',
|
||||
'agent_code': 'shipping_notice',
|
||||
'runtime_provider': 'hybrid',
|
||||
'conversation_mode': 'task_chat',
|
||||
'dify_app_id': 'atomic-shipping-create',
|
||||
'dify_api_key': 'sk-test',
|
||||
'api_base_url': 'http://dify.example/v1',
|
||||
'order_extraction_runtime_binding': {
|
||||
'provider_agent_id': provider.id,
|
||||
'enabled': True,
|
||||
'config': {'timeout_seconds': 900, 'max_attempts': 3},
|
||||
},
|
||||
})
|
||||
db.session.rollback()
|
||||
|
||||
assert Agent.query.filter_by(name='Atomic Shipping Create').count() == 0
|
||||
assert AgentRuntimeBinding.query.count() == 0
|
||||
|
||||
|
||||
def test_update_agent_and_runtime_binding_are_atomic(app):
|
||||
"""更新 Agent 时绑定校验失败必须回滚 Agent 字段,避免配置只保存一半。"""
|
||||
with app.app_context():
|
||||
owner = Agent(
|
||||
name='Atomic Shipping Update',
|
||||
description='before',
|
||||
agent_code='shipping_notice',
|
||||
runtime_provider='hybrid',
|
||||
conversation_mode='task_chat',
|
||||
dify_app_id='atomic-shipping-update',
|
||||
dify_api_key='sk-test',
|
||||
api_base_url='http://dify.example/v1',
|
||||
is_active=True,
|
||||
)
|
||||
provider = Agent(
|
||||
name='Invalid Update Provider',
|
||||
agent_code='generic',
|
||||
runtime_provider='dify',
|
||||
dify_app_type='chatflow',
|
||||
exposure_mode='workspace',
|
||||
dify_app_id='invalid-update-provider',
|
||||
dify_api_key='sk-test',
|
||||
api_base_url='http://dify.example/v1',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
agent_service.update_agent(owner.id, {
|
||||
'description': 'after',
|
||||
'order_extraction_runtime_binding': {
|
||||
'provider_agent_id': provider.id,
|
||||
'enabled': True,
|
||||
'config': {'timeout_seconds': 900, 'max_attempts': 3},
|
||||
},
|
||||
})
|
||||
db.session.rollback()
|
||||
|
||||
assert db.session.get(Agent, owner.id).description == 'before'
|
||||
assert AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).count() == 0
|
||||
|
||||
|
||||
def test_update_agent_permissions(app):
|
||||
with app.app_context():
|
||||
agent = Agent(
|
||||
|
||||
@@ -50,31 +50,6 @@ def test_batch_update_permissions_no_users(app):
|
||||
permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['single', 'batch'])
|
||||
def test_internal_executor_cannot_be_assigned_to_user(app, operation):
|
||||
"""授权服务必须在所有写入口拒绝 internal 执行器。"""
|
||||
with app.app_context():
|
||||
executor = Agent(
|
||||
name='internal-executor', type='api', dify_app_id='wf-internal', dify_api_key='key',
|
||||
dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal',
|
||||
)
|
||||
user = User(username=f'internal-{operation}', email=f'internal-{operation}@example.com', role='user')
|
||||
db.session.add_all([executor, user])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
if operation == 'single':
|
||||
permission_service.update_user_permissions(user.id, {'agent_ids': [executor.id]})
|
||||
else:
|
||||
permission_service.batch_update_permissions({
|
||||
'user_ids': [user.id], 'agent_ids': [executor.id], 'action': 'add',
|
||||
})
|
||||
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
db.session.refresh(user)
|
||||
assert executor not in user.agents
|
||||
|
||||
|
||||
def test_permission_request_approve(app, monkeypatch):
|
||||
with app.app_context():
|
||||
agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r')
|
||||
@@ -100,27 +75,3 @@ def test_permission_request_approve(app, monkeypatch):
|
||||
|
||||
def test_permission_request_not_found(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
permission_service.approve_permission_request(99999)
|
||||
|
||||
|
||||
def test_internal_executor_permission_request_cannot_be_approved(app):
|
||||
"""历史或伪造的内部执行器权限申请不得转化为用户授权。"""
|
||||
with app.app_context():
|
||||
executor = Agent(
|
||||
name='request-executor', type='api', dify_app_id='wf-request', dify_api_key='key',
|
||||
dify_app_type='workflow', runtime_provider='dify', exposure_mode='internal',
|
||||
)
|
||||
user = User(username='request-internal', email='request-internal@example.com', role='user')
|
||||
db.session.add_all([executor, user])
|
||||
db.session.flush()
|
||||
req = PermissionRequest(user_id=user.id, agent_id=executor.id, reason='invalid', status='pending')
|
||||
db.session.add(req)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ForbiddenError) as caught:
|
||||
permission_service.approve_permission_request(req.id)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
db.session.refresh(user)
|
||||
assert executor not in user.agents
|
||||
@@ -54,23 +54,3 @@ def test_list_users_sort_by_username_and_department(app):
|
||||
assert depts == sorted(depts, reverse=True)
|
||||
|
||||
fallback = user_service.resolve_users_order_by({'sort_by': 'role', 'sort_dir': 'asc'})
|
||||
assert len(fallback) == 1
|
||||
|
||||
|
||||
def test_update_user_rejects_internal_executor_permission(app):
|
||||
"""用户 CRUD 的 agent_ids 写入口不得绕过统一授权策略。"""
|
||||
with app.app_context():
|
||||
user = User(username='crud-internal', email='crud-internal@example.com', role='user')
|
||||
executor = Agent(
|
||||
name='CRUD Executor', exposure_mode='internal', runtime_provider='dify',
|
||||
dify_app_type='workflow', dify_app_id='crud-workflow', dify_api_key='key',
|
||||
)
|
||||
db.session.add_all([user, executor])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
user_service.update_user(user.id, {'agent_ids': [executor.id]})
|
||||
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
db.session.refresh(user)
|
||||
assert executor not in user.agents
|
||||
@@ -21,28 +21,3 @@ def test_binding_stats(app):
|
||||
stats = wecom_admin_service.binding_stats()
|
||||
assert stats['total_active'] == 2
|
||||
assert stats['bound'] == 1
|
||||
assert stats['unbound'] == 1
|
||||
|
||||
|
||||
def test_provision_user_rejects_internal_executor_permission(app):
|
||||
"""企微开户/绑定不得把内部执行器写入用户授权关系。"""
|
||||
with app.app_context():
|
||||
user = User(username='wecom-internal', email='wecom-internal@example.com', role='user')
|
||||
executor = Agent(
|
||||
name='WeCom Executor', exposure_mode='internal', runtime_provider='dify',
|
||||
dify_app_type='workflow', dify_app_id='wecom-workflow', dify_api_key='key',
|
||||
)
|
||||
db.session.add_all([user, executor])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
wecom_admin_service.provision_user({
|
||||
'create_user': False,
|
||||
'user_id': user.id,
|
||||
'bind': {'wecom_userid': 'wx-internal'},
|
||||
'agent_ids': [executor.id],
|
||||
})
|
||||
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
db.session.refresh(user)
|
||||
assert executor not in user.agents
|
||||
@@ -31,6 +31,8 @@ from app.models import (
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import published_policy, required_field_configs
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
@@ -280,6 +282,47 @@ def test_freeze_rejects_open_conflict_and_missing_fulfillment_value(app):
|
||||
assert missing_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
|
||||
|
||||
def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app):
|
||||
"""自动冻结模式必须消费 Run 级门禁摘要,并把阻断原因折叠为统一 freeze issues。"""
|
||||
with app.app_context():
|
||||
task, _user = _build_accepted_order(suffix='auto-freeze-readiness')
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
assert extraction is not None
|
||||
policy = published_policy()
|
||||
definition = extraction.schema_version.definition_json or {}
|
||||
configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
}
|
||||
configs.update(required_field_configs(definition, policy))
|
||||
|
||||
with pytest.raises(ValidationError) as blocked_error:
|
||||
assert_freeze_readiness(
|
||||
task=task,
|
||||
extraction=extraction,
|
||||
policy=policy,
|
||||
configs=configs,
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
'mode': 'manual_confirmation',
|
||||
'enabled': False,
|
||||
'qualification_status': 'auto_freeze_approved',
|
||||
'customer_scope_status': 'unconfigured',
|
||||
'blocking_reason_codes': [
|
||||
'customer_scope_not_configured',
|
||||
'customer_confirmation_required',
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
issues = blocked_error.value.details['issues']
|
||||
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues
|
||||
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues
|
||||
assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues)
|
||||
|
||||
|
||||
def test_freeze_is_idempotent_for_repeated_confirmation(app):
|
||||
"""关键断言:用户重复确认冻结只返回同一 Snapshot,不产生第二份履约事实。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -40,74 +40,6 @@ def test_validate_agent_payload_parses_is_active_string_false():
|
||||
assert normalized['is_active'] is False
|
||||
|
||||
|
||||
def test_validate_agent_payload_restricts_new_internal_executor_to_workflow():
|
||||
"""新建 internal Agent 只能登记为 Dify Workflow。"""
|
||||
with pytest.raises(ValidationError, match='内部执行器'):
|
||||
validate_agent_payload({
|
||||
'name': 'Invalid Internal',
|
||||
'agent_code': 'generic',
|
||||
'runtime_provider': 'dify',
|
||||
'dify_app_type': 'chatflow',
|
||||
'exposure_mode': 'internal',
|
||||
'dify_app_id': 'app-1',
|
||||
})
|
||||
|
||||
|
||||
def test_validate_agent_payload_rejects_moving_internal_to_workspace():
|
||||
"""内部执行器的可见性不可改回 workspace。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
agent = SimpleNamespace(
|
||||
agent_code='generic', runtime_provider='dify', conversation_mode='task_chat',
|
||||
dify_app_type='workflow', exposure_mode='internal',
|
||||
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
|
||||
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
|
||||
file_upload_policy=None, is_active=True, is_aggregate=False,
|
||||
)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_agent_payload({
|
||||
'name': 'Provider', 'exposure_mode': 'workspace',
|
||||
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'}))
|
||||
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
|
||||
|
||||
|
||||
def test_validate_agent_payload_rejects_promoting_workspace_to_internal():
|
||||
"""workspace Agent 不能通过编辑请求转换为 internal 执行器。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
agent = SimpleNamespace(
|
||||
agent_code='generic', runtime_provider='dify', conversation_mode='chat',
|
||||
dify_app_type='chatflow', exposure_mode='workspace',
|
||||
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
|
||||
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
|
||||
file_upload_policy=None, is_active=True, is_aggregate=False,
|
||||
)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_agent_payload({
|
||||
'name': 'Promote Provider', 'exposure_mode': 'internal',
|
||||
'runtime_provider': 'dify', 'dify_app_type': 'workflow',
|
||||
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode', 'runtime_provider', 'dify_app_type'}))
|
||||
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
|
||||
|
||||
|
||||
def test_validate_agent_payload_keeps_internal_exposure_immutable():
|
||||
"""已注册内部执行器不得通过编辑请求改成工作台应用。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
agent = SimpleNamespace(
|
||||
agent_code='generic', runtime_provider='dify', conversation_mode='task_chat',
|
||||
dify_app_type='workflow', exposure_mode='internal',
|
||||
dify_app_id='app-1', bound_schedule_task_id=None, capabilities=None, handler_config=None,
|
||||
suggested_questions_style='plain', suggested_questions=[], sort_order=0,
|
||||
file_upload_policy=None, is_active=True, is_aggregate=False,
|
||||
)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_agent_payload({
|
||||
'name': 'Internal Provider', 'exposure_mode': 'workspace',
|
||||
}, agent=agent, provided_fields=frozenset({'name', 'exposure_mode'}))
|
||||
assert caught.value.code == 'AGENT.EXPOSURE_ROLE_IMMUTABLE'
|
||||
|
||||
|
||||
def test_validate_agent_payload_applies_forced_capabilities_from_manifest():
|
||||
"""validate_agent_payload 路径应合并 manifest forced_capabilities。"""
|
||||
normalized = validate_agent_payload({
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.services.agent_registry.resolver import (
|
||||
resolve_agent_code,
|
||||
resolve_capabilities,
|
||||
resolve_conversation_mode,
|
||||
resolve_effective_role,
|
||||
resolve_handler_key,
|
||||
resolve_intent_routes,
|
||||
resolve_progress_contract,
|
||||
@@ -102,13 +101,6 @@ def test_resolve_runtime_provider_reads_column_not_legacy_type():
|
||||
assert resolve_runtime_provider(registered_iframe) == 'iframe'
|
||||
|
||||
|
||||
def test_resolve_effective_role_derives_from_exposure_mode_only():
|
||||
"""internal 仅派生为内部执行器;历史 conversation_mode 不影响角色。"""
|
||||
assert resolve_effective_role(_agent(exposure_mode='internal', conversation_mode='task_chat')) == 'internal_executor'
|
||||
assert resolve_effective_role(_agent(exposure_mode='workspace', conversation_mode='embedded')) == 'user_agent'
|
||||
assert resolve_effective_role(SimpleNamespace()) == 'user_agent'
|
||||
|
||||
|
||||
def test_resolve_capabilities_normalizes_schema():
|
||||
"""capabilities 列 dict 应归一化为固定 schema 布尔键。"""
|
||||
agent = _agent(
|
||||
|
||||
@@ -35,7 +35,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
|
||||
agent_code='generic',
|
||||
runtime_provider='dify',
|
||||
conversation_mode='chat',
|
||||
exposure_mode='internal',
|
||||
dify_app_type='chatflow',
|
||||
iframe_url=None,
|
||||
category=None,
|
||||
@@ -52,7 +51,6 @@ def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
|
||||
payload = serialize_agent_for_admin(agent)
|
||||
assert payload['dify_api_key'] == agent.dify_api_key
|
||||
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
|
||||
assert payload['effective_role'] == 'internal_executor'
|
||||
|
||||
|
||||
def test_serialize_registry_fields_includes_progress_contract():
|
||||
@@ -60,7 +58,6 @@ def test_serialize_registry_fields_includes_progress_contract():
|
||||
agent_code='file_check',
|
||||
runtime_provider='dify',
|
||||
conversation_mode='task_chat',
|
||||
exposure_mode='workspace',
|
||||
capabilities={'task_progress': True},
|
||||
bound_schedule_task_id=42,
|
||||
handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True},
|
||||
@@ -77,7 +74,6 @@ def test_serialize_registry_fields_includes_progress_contract():
|
||||
payload = serialize_registry_fields(file_check)
|
||||
assert payload['progress_contract']['data_source']['type'] == 'schedule_run'
|
||||
assert payload['tool_run_progress']['schedule_task_id'] == 42
|
||||
assert payload['effective_role'] == 'user_agent'
|
||||
|
||||
|
||||
def test_build_tool_run_progress_view_skips_domain_state_contract():
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_agent_runtime_binding_migration.py
|
||||
|
||||
用途:隔离验证阶段 2 Agent 能力绑定迁移可往返执行。
|
||||
依赖:Alembic Operations、SQLAlchemy 内存数据库、c17c8d9e0f1a 增量迁移。
|
||||
逻辑:构造阶段 1 最小表,验证 exposure/binding/Run Provider/Job 唯一索引并完整回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def _pre_schema(engine: sa.Engine) -> None:
|
||||
"""创建阶段 2 迁移依赖的最小表结构。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'jobs', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('domain', sa.String(64)),
|
||||
sa.Column('job_type', sa.String(64)),
|
||||
sa.Column('business_ref', sa.String(128)),
|
||||
sa.Column('status', sa.String(32)),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_agent_runtime_binding_migration_round_trip():
|
||||
"""迁移应创建全部阶段 2 列/表/索引,并可回到阶段 1 结构。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_schema(engine)
|
||||
migration = importlib.import_module('migrations.versions.c17c8d9e0f1a_add_agent_runtime_bindings')
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'exposure_mode' in {item['name'] for item in inspector.get_columns('agents')}
|
||||
assert 'agent_runtime_bindings' in inspector.get_table_names()
|
||||
run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')}
|
||||
assert {
|
||||
'runtime_binding_id', 'provider_agent_id', 'provider_result_json', 'provider_completed_at',
|
||||
} <= run_columns
|
||||
assert 'provider_config_json' not in run_columns
|
||||
assert 'provider_snapshot_json' not in run_columns
|
||||
indexes = {item['name']: item for item in inspector.get_indexes('jobs')}
|
||||
assert indexes['uq_jobs_shipping_order_extraction_active_ref']['unique'] == 1
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'exposure_mode' not in {item['name'] for item in inspector.get_columns('agents')}
|
||||
assert 'agent_runtime_bindings' not in inspector.get_table_names()
|
||||
run_columns = {item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')}
|
||||
assert 'runtime_binding_id' not in run_columns
|
||||
assert 'provider_result_json' not in run_columns
|
||||
finally:
|
||||
migration.op = original_op
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables
|
||||
from app.services.shipping_notice.email_allocation_table_parser import (
|
||||
parse_email_allocation_tables,
|
||||
parse_email_allocation_text,
|
||||
)
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
|
||||
|
||||
@@ -69,3 +72,24 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
]}
|
||||
result = merge_email_supplements(orders=[_order()], supplements_by_intake={1: ambiguous}, schema_definition=SCHEMA)[0]
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
content_hash='b' * 64,
|
||||
body_text='''Hello\nallocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nThank you''',
|
||||
)
|
||||
assert supplement['rows'] == [{
|
||||
'allocation_id': 'A-1', 'reservation_id': '2000484577',
|
||||
'source_from_party': 'Welltrust', 'source_type': 'DSB CMH',
|
||||
'allocated_entity': 'IEC-CJS', 'mpn': 'D4-A08AR12000002',
|
||||
'allocated_qty': '30', 'po_number': '4518838152',
|
||||
'evidence': supplement['rows'][0]['evidence'], 'table_index': None, 'row_index': 1,
|
||||
}]
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_deduplicates_quoted_email_rows():
|
||||
"""转发邮件重复同一正文表时只保留一个事实行,避免制造补充关联冲突。"""
|
||||
body = '''allocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152'''
|
||||
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64)['rows']) == 1
|
||||
@@ -1,65 +0,0 @@
|
||||
"""
|
||||
用途:验证内部执行器不会通过用户列表、详情、授权序列化或统一访问策略暴露。
|
||||
依赖:通用 app/client 测试夹具、JWT、本地 Agent/User 模型。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin.user_service import serialize_admin_user
|
||||
from app.services.agent_user_access import require_user_application_access
|
||||
|
||||
|
||||
def _seed_user_access_rows():
|
||||
"""创建 workspace 应用、内部执行器及带历史脏授权的用户。"""
|
||||
application = Agent(name='Visible Application', exposure_mode='workspace', is_active=True)
|
||||
executor = Agent(
|
||||
name='Hidden Executor', exposure_mode='internal', is_active=True,
|
||||
runtime_provider='dify', dify_app_type='workflow', dify_app_id='hidden-workflow',
|
||||
dify_api_key='key',
|
||||
)
|
||||
user = User(username='isolated-user', email='isolated-user@example.com', role='user')
|
||||
admin = User(username='isolated-admin', email='isolated-admin@example.com', role='admin')
|
||||
user.agents.extend([application, executor])
|
||||
db.session.add_all([application, executor, user, admin])
|
||||
db.session.commit()
|
||||
return application, executor, user, admin
|
||||
|
||||
|
||||
def test_internal_executor_is_hidden_from_public_list_and_admin_user_detail(app, client):
|
||||
"""公开列表和管理员普通用户详情接口都不能暴露内部执行器。"""
|
||||
with app.app_context():
|
||||
application, executor, _user, admin = _seed_user_access_rows()
|
||||
admin_token = issue_local_access_token(admin)
|
||||
executor_id = executor.id
|
||||
application_id = application.id
|
||||
|
||||
public_response = client.get('/api/agents/public')
|
||||
assert public_response.status_code == 200
|
||||
assert {row['id'] for row in public_response.get_json()} == {application_id}
|
||||
|
||||
detail_response = client.get(
|
||||
f'/api/user/agents/{executor_id}',
|
||||
headers={'Authorization': f'Bearer {admin_token}'},
|
||||
)
|
||||
assert detail_response.status_code == 403
|
||||
assert detail_response.get_json()['error']['code'] == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
|
||||
|
||||
def test_internal_executor_is_hidden_from_user_permission_serialization(app):
|
||||
"""历史脏授权关系不能返回权限矩阵或再次通过用户访问校验。"""
|
||||
with app.app_context():
|
||||
application, executor, user, admin = _seed_user_access_rows()
|
||||
|
||||
assert serialize_admin_user(user)['agent_ids'] == [application.id]
|
||||
with pytest.raises(ForbiddenError) as user_error:
|
||||
require_user_application_access(executor, user)
|
||||
with pytest.raises(ForbiddenError) as admin_error:
|
||||
require_user_application_access(executor, admin)
|
||||
|
||||
assert user_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
assert admin_error.value.code == 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN'
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
"""
|
||||
用途:验证内部执行器用户侧历史关系清理迁移的数据边界与幂等性。
|
||||
依赖:Alembic Operations、SQLite 临时数据库。
|
||||
"""
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_internal_executor_user_links_cleanup_is_complete_and_idempotent():
|
||||
"""迁移只清理 internal 用户关系,并保留 workspace 关系与历史权限申请。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
agents = sa.Table(
|
||||
'agents', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('exposure_mode', sa.String(20), nullable=False),
|
||||
)
|
||||
users = sa.Table(
|
||||
'users', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('default_agent_id', sa.Integer, nullable=True),
|
||||
)
|
||||
permissions = sa.Table(
|
||||
'user_agent_permissions', metadata,
|
||||
sa.Column('user_id', sa.Integer, primary_key=True),
|
||||
sa.Column('agent_id', sa.Integer, primary_key=True),
|
||||
)
|
||||
favorites = sa.Table(
|
||||
'user_favorite_agents', metadata,
|
||||
sa.Column('user_id', sa.Integer, primary_key=True),
|
||||
sa.Column('agent_id', sa.Integer, primary_key=True),
|
||||
)
|
||||
defaults = sa.Table(
|
||||
'user_default_agents', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('user_id', sa.Integer, nullable=False),
|
||||
sa.Column('agent_id', sa.Integer, nullable=False),
|
||||
)
|
||||
requests = sa.Table(
|
||||
'permission_requests', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('agent_id', sa.Integer, nullable=False),
|
||||
sa.Column('status', sa.String(20), nullable=False),
|
||||
sa.Column('reviewed_at', sa.DateTime, nullable=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a62b3c4d5e6f_remove_internal_executor_user_links'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(agents.insert(), [
|
||||
{'id': 1, 'exposure_mode': 'workspace'},
|
||||
{'id': 2, 'exposure_mode': 'internal'},
|
||||
])
|
||||
connection.execute(users.insert(), [
|
||||
{'id': 10, 'default_agent_id': 1},
|
||||
{'id': 11, 'default_agent_id': 2},
|
||||
])
|
||||
for table in (permissions, favorites):
|
||||
connection.execute(table.insert(), [
|
||||
{'user_id': 10, 'agent_id': 1},
|
||||
{'user_id': 11, 'agent_id': 2},
|
||||
])
|
||||
connection.execute(defaults.insert(), [
|
||||
{'id': 100, 'user_id': 10, 'agent_id': 1},
|
||||
{'id': 101, 'user_id': 11, 'agent_id': 2},
|
||||
])
|
||||
connection.execute(requests.insert(), [
|
||||
{'id': 200, 'agent_id': 1, 'status': 'pending'},
|
||||
{'id': 201, 'agent_id': 2, 'status': 'pending'},
|
||||
{'id': 202, 'agent_id': 2, 'status': 'approved'},
|
||||
])
|
||||
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
assert connection.execute(sa.select(permissions)).mappings().all() == [
|
||||
{'user_id': 10, 'agent_id': 1}
|
||||
]
|
||||
assert connection.execute(sa.select(favorites)).mappings().all() == [
|
||||
{'user_id': 10, 'agent_id': 1}
|
||||
]
|
||||
assert connection.execute(sa.select(defaults)).mappings().all() == [
|
||||
{'id': 100, 'user_id': 10, 'agent_id': 1}
|
||||
]
|
||||
user_rows = {row['id']: row for row in connection.execute(sa.select(users)).mappings()}
|
||||
assert user_rows[10]['default_agent_id'] == 1
|
||||
assert user_rows[11]['default_agent_id'] is None
|
||||
request_rows = {row['id']: row for row in connection.execute(sa.select(requests)).mappings()}
|
||||
assert request_rows[200]['status'] == 'pending'
|
||||
assert request_rows[201]['status'] == 'rejected'
|
||||
assert request_rows[201]['reviewed_at'] is not None
|
||||
assert request_rows[202]['status'] == 'approved'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""验证已批准 PDF 模板的多 PO 拆分与严格拒识边界。
|
||||
"""验证已批准 PDF 模板的一单一 PO 约束与严格拒识边界。
|
||||
|
||||
依赖:确定性 Profile 订单构建器。
|
||||
逻辑:只有每行携带唯一 PO 证据时拆分;文档级多 PO 绝不猜测行归属。
|
||||
逻辑:一份 PDF 正常只允许一个 PO;检测到多个 PO 时必须整体拒识。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,15 +27,14 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def test_approved_pdf_splits_explicit_line_pos_into_independent_orders():
|
||||
"""同一 PDF 的两条明细各有 PO 时,必须生成两份独立订单。"""
|
||||
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
|
||||
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), _row('PO-2', 'P-2')]},
|
||||
)
|
||||
assert reason is None
|
||||
assert len(orders or []) == 2
|
||||
assert [item['header_fields'][0]['observations'][0]['value'] for item in orders or []] == ['PO-1', 'PO-2']
|
||||
assert orders is None
|
||||
assert reason == 'multiple_po_detected'
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""验证订单解析确定性进度事实迁移可完整 upgrade/downgrade。
|
||||
|
||||
依赖:Alembic Operations、SQLite 内存数据库、0ab45c6d7e8f 迁移。
|
||||
逻辑:创建最小前置 Run/Unit/Job 结构,检查新状态约束与事件表字段,再验证受控回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('agents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(100), nullable=False),
|
||||
sa.Column('status', sa.String(32), nullable=False),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_units',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('plan_id', sa.Integer(), nullable=False),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(32), nullable=False),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_progress_events',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('workflow_run_id', sa.String(128)),
|
||||
sa.Column('node_execution_id', sa.String(128)),
|
||||
sa.Column('event_type', sa.String(64), nullable=False),
|
||||
sa.Column('node_type', sa.String(64)),
|
||||
sa.Column('stage_code', sa.String(64)),
|
||||
sa.Column('event_status', sa.String(32)),
|
||||
sa.Column('provider_occurred_at', sa.DateTime()),
|
||||
sa.Column('received_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('details_json', sa.JSON()),
|
||||
sa.Column('idempotency_key', sa.String(128), nullable=False),
|
||||
sa.Column('mapping_version', sa.String(32)),
|
||||
sa.Column('expires_at', sa.DateTime()),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_progress_facts_migration_round_trip():
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.0ab45c6d7e8f_rebuild_order_extraction_progress_facts'
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
unit_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_units')
|
||||
}
|
||||
assert {'reason_code', 'summary_json', 'last_activity_at'} <= unit_columns
|
||||
|
||||
event_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
assert {
|
||||
'run_id', 'unit_id', 'document_id', 'sequence_no', 'visibility',
|
||||
'event_code', 'status', 'occurred_at', 'reason_code', 'summary_json',
|
||||
} <= event_columns
|
||||
assert {
|
||||
'workflow_run_id', 'node_execution_id', 'event_type', 'node_type',
|
||||
'stage_code', 'event_status', 'provider_occurred_at', 'details_json',
|
||||
}.isdisjoint(event_columns)
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
reverted_event_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
assert {'workflow_run_id', 'node_execution_id', 'event_type', 'stage_code'} <= reverted_event_columns
|
||||
reverted_unit_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_units')
|
||||
}
|
||||
assert {'reason_code', 'summary_json', 'last_activity_at'}.isdisjoint(reverted_unit_columns)
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -0,0 +1,47 @@
|
||||
"""验证订单抽取请求快照迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_extraction_request_snapshot_migration_round_trip():
|
||||
"""发送时审计锚点字段必须独立升级回退,不能与可变执行快照混淆。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.2d3e4f5a6b7c_add_order_extraction_request_snapshot'
|
||||
)
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('input_snapshot_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('input_snapshot_json', sa.JSON(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
columns = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert {'request_snapshot_hash', 'request_snapshot_json'} <= columns
|
||||
|
||||
migration.downgrade()
|
||||
downgraded = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert 'request_snapshot_hash' not in downgraded
|
||||
assert 'request_snapshot_json' not in downgraded
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -0,0 +1,42 @@
|
||||
"""验证自动冻结资格范围迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_profile_auto_freeze_scope_migration_contract():
|
||||
"""资格范围字段必须可升级回退,且不依赖业务表全量存在。"""
|
||||
base = importlib.import_module('migrations.versions.0aa34b5c6d7e_add_profile_auto_freeze_qualifications')
|
||||
migration = importlib.import_module('migrations.versions.0ce67f8a9b01_add_auto_freeze_scope_to_profile_qualification')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('shipping_order_document_profiles', 'shipping_order_schema_versions', 'shipping_document_profile_test_suites', 'users'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
base.op = Operations(MigrationContext.configure(connection))
|
||||
base.upgrade()
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
columns = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications')
|
||||
}
|
||||
assert {
|
||||
'customer_ids_json',
|
||||
'business_scenarios_json',
|
||||
'requires_customer_confirmation',
|
||||
'scope_updated_by_id',
|
||||
'scope_updated_at',
|
||||
} <= columns
|
||||
migration.downgrade()
|
||||
columns_after_downgrade = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications')
|
||||
}
|
||||
assert 'customer_ids_json' not in columns_after_downgrade
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
backend/tests/test_shipping_attachment_selection.py
|
||||
|
||||
用途:验证发送阶段附件选择计划只依赖快览事实,并能把计划摘要投影到 Run 响应。
|
||||
依赖:pytest、纯函数 attachment_selection、订单抽取 Run 序列化服务。
|
||||
逻辑:覆盖评分/排除/去重/首轮预算,以及 Run API 的 selection_plan 摘要输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot
|
||||
from app.services.shipping_notice.order_extraction_plan import (
|
||||
_snapshot_documents,
|
||||
transition_order_extraction_unit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_runtime_snapshot import (
|
||||
resolve_unit_runtime_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_snapshot_selection import (
|
||||
has_attachment_catalog,
|
||||
has_selected_attachments,
|
||||
selected_attachment_keys_by_intake,
|
||||
should_include_snapshot_document,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
serialize_workspace_run_documents,
|
||||
)
|
||||
|
||||
|
||||
def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '', body_text: str = ''):
|
||||
"""构造最小快览 Intake 假对象,避免测试选择计划时依赖数据库。"""
|
||||
return SimpleNamespace(
|
||||
intake_no=intake_no,
|
||||
structured_result_json={
|
||||
'email': {
|
||||
'subject': subject,
|
||||
'body_text': body_text,
|
||||
'body_html_tables': [],
|
||||
},
|
||||
'attachments': attachments,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicates():
|
||||
"""首轮仅选 2 个高相关附件;后续候选进入未来批次,风险附件和重复哈希必须稳定跳过。"""
|
||||
snapshot = build_attachment_selection_snapshot(intakes=[
|
||||
_preview_intake(
|
||||
'SNI-A',
|
||||
[
|
||||
{
|
||||
'attachment_key': 'po-1.pdf',
|
||||
'filename': 'PO_451883815A.pdf',
|
||||
'mime_type': 'application/pdf',
|
||||
'size': 48000,
|
||||
'content_hash': 'a' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'logo.png',
|
||||
'filename': 'customer-logo.png',
|
||||
'mime_type': 'image/png',
|
||||
'size': 4096,
|
||||
'content_hash': 'b' * 64,
|
||||
'ready_for_extraction': False,
|
||||
'is_inline_resource': True,
|
||||
'catalog_reason': 'inline_resource',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'archive.zip',
|
||||
'filename': 'orders.zip',
|
||||
'mime_type': 'application/zip',
|
||||
'size': 120000,
|
||||
'content_hash': 'c' * 64,
|
||||
'ready_for_extraction': False,
|
||||
'catalog_reason': 'archive',
|
||||
},
|
||||
],
|
||||
subject='PO 451883815A and booking details',
|
||||
),
|
||||
_preview_intake(
|
||||
'SNI-B',
|
||||
[
|
||||
{
|
||||
'attachment_key': 'po-1-duplicate.pdf',
|
||||
'filename': 'PO_451883815A_copy.pdf',
|
||||
'mime_type': 'application/pdf',
|
||||
'size': 48000,
|
||||
'content_hash': 'a' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'booking.xlsx',
|
||||
'filename': 'booking_451883816.xlsx',
|
||||
'mime_type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'size': 56000,
|
||||
'content_hash': 'd' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'third.docx',
|
||||
'filename': 'order_notes.docx',
|
||||
'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'size': 42000,
|
||||
'content_hash': 'e' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
],
|
||||
body_text='Please process PO 451883816 first.',
|
||||
),
|
||||
])
|
||||
|
||||
assert snapshot['selection_version'] == 'shipping_notice_attachment_selection.v1'
|
||||
# 内嵌签名资源不属于业务附件,不计入选择计划数量。
|
||||
assert snapshot['total_attachment_count'] == 5
|
||||
assert snapshot['eligible_attachment_count'] == 3
|
||||
assert snapshot['selected_attachment_count'] == 2
|
||||
assert snapshot['planned_attachment_count'] == 3
|
||||
assert snapshot['pending_expansion_attachment_count'] == 1
|
||||
assert snapshot['pending_expansion_batches'] == {'2': 1}
|
||||
selected = [item for item in snapshot['items'] if item['selected']]
|
||||
assert [item['filename'] for item in selected] == ['PO_451883815A.pdf', 'booking_451883816.xlsx']
|
||||
|
||||
by_name = {item['filename']: item for item in snapshot['items']}
|
||||
assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash']
|
||||
assert 'customer-logo.png' not in by_name
|
||||
assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive']
|
||||
assert by_name['order_notes.docx']['skip_reason_codes'] == []
|
||||
assert by_name['order_notes.docx']['planned_selection_batch'] == 2
|
||||
assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A'
|
||||
|
||||
|
||||
def test_attachment_selection_snapshot_stops_at_total_byte_budget():
|
||||
"""累计深度解析字节超预算时,后续附件必须标记为预算停止而非静默扩批。"""
|
||||
snapshot = build_attachment_selection_snapshot(
|
||||
intakes=[_preview_intake('SNI-BYTE', [
|
||||
{
|
||||
'attachment_key': 'first.pdf', 'filename': 'first.pdf', 'mime_type': 'application/pdf',
|
||||
'size': 20, 'content_hash': 'a' * 64, 'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'second.pdf', 'filename': 'second.pdf', 'mime_type': 'application/pdf',
|
||||
'size': 20, 'content_hash': 'b' * 64, 'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
])],
|
||||
max_total_bytes=30,
|
||||
)
|
||||
|
||||
by_name = {item['filename']: item for item in snapshot['items']}
|
||||
assert snapshot['planned_total_bytes'] == 20
|
||||
assert by_name['first.pdf']['selected'] is True
|
||||
assert by_name['second.pdf']['skip_reason_codes'] == ['budget_total_bytes']
|
||||
|
||||
|
||||
def test_attachment_selection_snapshot_excludes_inline_resources_from_counts():
|
||||
"""邮件签名图不属于用户业务附件,不能占用识别计划的附件数量或预算。"""
|
||||
snapshot = build_attachment_selection_snapshot(intakes=[
|
||||
_preview_intake(
|
||||
'SNI-A',
|
||||
[
|
||||
{
|
||||
'attachment_key': 'signature.gif',
|
||||
'filename': 'signature.gif',
|
||||
'mime_type': 'image/gif',
|
||||
'size': 1024,
|
||||
'content_hash': 'a' * 64,
|
||||
'ready_for_extraction': False,
|
||||
'is_inline_resource': True,
|
||||
'catalog_reason': 'inline_resource',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'po-1.pdf',
|
||||
'filename': 'PO_4518838152.pdf',
|
||||
'mime_type': 'application/pdf',
|
||||
'size': 48000,
|
||||
'content_hash': 'b' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
{
|
||||
'attachment_key': 'po-2.pdf',
|
||||
'filename': 'PO_4518838154.pdf',
|
||||
'mime_type': 'application/pdf',
|
||||
'size': 48000,
|
||||
'content_hash': 'c' * 64,
|
||||
'ready_for_extraction': True,
|
||||
'catalog_reason': 'ready_for_extraction',
|
||||
},
|
||||
],
|
||||
),
|
||||
])
|
||||
|
||||
assert snapshot['total_attachment_count'] == 2
|
||||
assert snapshot['eligible_attachment_count'] == 2
|
||||
assert snapshot['selected_attachment_count'] == 2
|
||||
assert [item['filename'] for item in snapshot['items']] == [
|
||||
'PO_4518838152.pdf', 'PO_4518838154.pdf',
|
||||
]
|
||||
|
||||
|
||||
def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypatch):
|
||||
"""Run 用户态响应应暴露计划摘要计数,但不能泄露具体正文或打分细节。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run',
|
||||
lambda _run: {
|
||||
'summary': {
|
||||
'total_documents': 0,
|
||||
'pending_documents': 0,
|
||||
'processing_documents': 0,
|
||||
'completed_documents': 0,
|
||||
'review_required_documents': 0,
|
||||
'failed_documents': 0,
|
||||
'candidate_count': 0,
|
||||
},
|
||||
'current_activity': None,
|
||||
'available_actions': ['view_details'],
|
||||
},
|
||||
)
|
||||
run = SimpleNamespace(
|
||||
run_no='SNER-SELECTION',
|
||||
owner_agent_id=1,
|
||||
conversation_id='conv-selection',
|
||||
status='queued',
|
||||
phase='queued',
|
||||
schema_version_id=1,
|
||||
attempt_count=0,
|
||||
reparse_source=None,
|
||||
superseding_run=None,
|
||||
reparse_reason=None,
|
||||
superseded_at=None,
|
||||
result_json=None,
|
||||
error_code=None,
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
extraction_plan=SimpleNamespace(units=[
|
||||
SimpleNamespace(
|
||||
selection_batch=1,
|
||||
status='candidate_ready',
|
||||
reason_code=None,
|
||||
result_json={
|
||||
'orders': [{
|
||||
'lines': [{'fields': []}],
|
||||
'conflicts': [{'reason': 'supplement_relation_ambiguous'}],
|
||||
}],
|
||||
},
|
||||
retry_status='running',
|
||||
technical_failure_reason_code=None,
|
||||
),
|
||||
SimpleNamespace(
|
||||
selection_batch=1,
|
||||
status='failed',
|
||||
reason_code=None,
|
||||
result_json=None,
|
||||
retry_status='failed',
|
||||
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
),
|
||||
SimpleNamespace(
|
||||
selection_batch=2,
|
||||
status='review_required',
|
||||
reason_code='required_field_missing',
|
||||
result_json={'orders': []},
|
||||
retry_status='review_required',
|
||||
technical_failure_reason_code=None,
|
||||
),
|
||||
]),
|
||||
input_snapshot_json={
|
||||
'schema': {
|
||||
'version': 1,
|
||||
'checksum': 'a' * 64,
|
||||
'definition': {
|
||||
'fields': [{'field_code': 'reservation_id', 'field_id': 'reservation-id'}],
|
||||
},
|
||||
},
|
||||
'intakes': [{'intake_no': 'SNI-1'}],
|
||||
'attachment_selection': {
|
||||
'selection_version': 'shipping_notice_attachment_selection.v1',
|
||||
'max_initial_attachments': 2,
|
||||
'max_initial_concurrency': 2,
|
||||
'expansion_batch_size': 2,
|
||||
'max_total_attachments': 6,
|
||||
'total_attachment_count': 5,
|
||||
'eligible_attachment_count': 3,
|
||||
'selected_attachment_count': 2,
|
||||
'planned_attachment_count': 3,
|
||||
'pending_expansion_attachment_count': 1,
|
||||
'pending_expansion_batches': {'2': 1},
|
||||
'group_count': 2,
|
||||
'items': [
|
||||
{'selected': True, 'selection_batch': 1, 'filename': 'must-not-leak.pdf', 'score': 999},
|
||||
{'selected': True, 'selection_batch': 1},
|
||||
{'selected': False, 'planned_selection_batch': 2, 'skip_reason_codes': []},
|
||||
{'selected': False, 'skip_reason_codes': ['duplicate_content_hash']},
|
||||
{'selected': False, 'skip_reason_codes': ['catalog_reason:inline_resource']},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
payload = serialize_order_extraction_run(run)
|
||||
|
||||
assert payload['selection_plan'] == {
|
||||
'selection_version': 'shipping_notice_attachment_selection.v1',
|
||||
'max_initial_attachments': 2,
|
||||
'max_initial_concurrency': 2,
|
||||
'expansion_batch_size': 2,
|
||||
'max_total_attachments': 6,
|
||||
'max_total_bytes': 0,
|
||||
'max_runtime_seconds': 0,
|
||||
'input_total_bytes': 0,
|
||||
'planned_total_bytes': 0,
|
||||
'total_attachment_count': 5,
|
||||
'eligible_attachment_count': 3,
|
||||
'selected_attachment_count': 2,
|
||||
'planned_attachment_count': 3,
|
||||
'pending_expansion_attachment_count': 1,
|
||||
'pending_expansion_batches': {'2': 1},
|
||||
'skipped_attachment_count': 2,
|
||||
'duplicate_attachment_count': 1,
|
||||
'budget_limited_attachment_count': 0,
|
||||
'group_count': 2,
|
||||
}
|
||||
assert payload['unit_summary'] == {
|
||||
'total_units': 3,
|
||||
'selected_units': 3,
|
||||
'retrying_units': 1,
|
||||
'pending_retry_units': 0,
|
||||
'failed_units': 1,
|
||||
'review_required_units': 1,
|
||||
'succeeded_units': 0,
|
||||
'selection_batches': {'1': 2, '2': 1},
|
||||
'review_required_reason_codes': ['required_field_missing'],
|
||||
'expansion_trigger_reason_codes': [
|
||||
'missing_reservation_id',
|
||||
'required_field_missing',
|
||||
'supplement_relation_ambiguous',
|
||||
],
|
||||
'technical_failure_reason_codes': ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
|
||||
}
|
||||
assert 'must-not-leak' not in str(payload)
|
||||
|
||||
|
||||
def test_snapshot_selection_helpers_keep_only_selected_attachment_documents():
|
||||
"""Run snapshot 应只包含本次计划选中的附件,正文补充事实必须保留。"""
|
||||
selection_snapshot = {
|
||||
'total_attachment_count': 4,
|
||||
'selected_attachment_count': 2,
|
||||
'items': [
|
||||
{'intake_no': 'SNI-A', 'attachment_key': 'po-1.pdf', 'selected': True},
|
||||
{'intake_no': 'SNI-A', 'attachment_key': 'copy.pdf', 'selected': False},
|
||||
{'intake_no': 'SNI-B', 'attachment_key': 'booking.xlsx', 'selected': True},
|
||||
],
|
||||
}
|
||||
|
||||
assert has_attachment_catalog(selection_snapshot) is True
|
||||
assert has_selected_attachments(selection_snapshot) is True
|
||||
assert selected_attachment_keys_by_intake(selection_snapshot) == {
|
||||
'SNI-A': {'po-1.pdf'},
|
||||
'SNI-B': {'booking.xlsx'},
|
||||
}
|
||||
assert should_include_snapshot_document(
|
||||
selection_snapshot=selection_snapshot,
|
||||
intake_no='SNI-A',
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
) is True
|
||||
assert should_include_snapshot_document(
|
||||
selection_snapshot=selection_snapshot,
|
||||
intake_no='SNI-A',
|
||||
document_type='attachment',
|
||||
attachment_key='po-1.pdf',
|
||||
) is True
|
||||
assert should_include_snapshot_document(
|
||||
selection_snapshot=selection_snapshot,
|
||||
intake_no='SNI-A',
|
||||
document_type='attachment',
|
||||
attachment_key='copy.pdf',
|
||||
) is False
|
||||
|
||||
|
||||
def test_snapshot_selection_helpers_fall_back_to_all_documents_for_non_catalog_inputs():
|
||||
"""普通单文件没有附件目录时,不应误把唯一文档过滤掉。"""
|
||||
selection_snapshot = {'total_attachment_count': 0, 'selected_attachment_count': 0, 'items': []}
|
||||
|
||||
assert has_attachment_catalog(selection_snapshot) is False
|
||||
assert has_selected_attachments(selection_snapshot) is False
|
||||
assert should_include_snapshot_document(
|
||||
selection_snapshot=selection_snapshot,
|
||||
intake_no='SNI-FILE',
|
||||
document_type='attachment',
|
||||
attachment_key='file',
|
||||
) is True
|
||||
|
||||
|
||||
def test_snapshot_documents_include_selection_metadata():
|
||||
"""计划编译应把选择批次、原因码、分组键和预算摘要映射到附件单元。"""
|
||||
run = SimpleNamespace(
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'max_initial_attachments': 2,
|
||||
'max_initial_concurrency': 2,
|
||||
'items': [
|
||||
{
|
||||
'intake_no': 'SNI-A',
|
||||
'attachment_key': 'po-1.pdf',
|
||||
'selected': True,
|
||||
'selection_batch': 1,
|
||||
'score_reasons': ['type_pdf', 'po_hint_detected'],
|
||||
'group_key': '451883815A',
|
||||
},
|
||||
{
|
||||
'intake_no': 'SNI-A',
|
||||
'attachment_key': 'copy.pdf',
|
||||
'selected': False,
|
||||
'score_reasons': ['filename_copy_hint'],
|
||||
'group_key': '451883815A',
|
||||
},
|
||||
],
|
||||
},
|
||||
'intakes': [{
|
||||
'intake_id': 11,
|
||||
'intake_no': 'SNI-A',
|
||||
'documents': [
|
||||
{
|
||||
'document_id': 101,
|
||||
'document_type': 'attachment',
|
||||
'attachment_key': 'po-1.pdf',
|
||||
'content_hash': 'a' * 64,
|
||||
},
|
||||
{
|
||||
'document_id': 102,
|
||||
'document_type': 'attachment',
|
||||
'attachment_key': 'copy.pdf',
|
||||
'content_hash': 'b' * 64,
|
||||
},
|
||||
],
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
documents = _snapshot_documents(run)
|
||||
|
||||
assert documents[0]['selection_batch'] == 1
|
||||
assert documents[0]['selection_reason_codes'] == ['type_pdf', 'po_hint_detected']
|
||||
assert documents[0]['group_key'] == '451883815A'
|
||||
assert documents[0]['budget_cost'] == {
|
||||
'initial_attachment_budget': 2,
|
||||
'initial_concurrency_budget': 2,
|
||||
'expansion_batch_size': 0,
|
||||
'max_total_attachments': 0,
|
||||
'selected_in_batch': 1,
|
||||
}
|
||||
assert documents[1]['selection_batch'] is None
|
||||
assert documents[1]['selection_reason_codes'] == ['filename_copy_hint']
|
||||
|
||||
|
||||
def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(monkeypatch):
|
||||
"""附件单元失败与重试时应更新 retry_status 和 technical_failure_reason_code。"""
|
||||
audit_calls: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
lambda **kwargs: audit_calls.append(kwargs),
|
||||
)
|
||||
plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN'))
|
||||
unit = SimpleNamespace(
|
||||
id=1,
|
||||
status='pending',
|
||||
attempt_count=0,
|
||||
reason_code=None,
|
||||
summary_json=None,
|
||||
result_json=None,
|
||||
error_code=None,
|
||||
error_message=None,
|
||||
last_activity_at=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
retry_status='not_started',
|
||||
technical_failure_reason_code=None,
|
||||
plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
assert unit.retry_status == 'running'
|
||||
assert unit.technical_failure_reason_code is None
|
||||
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
error_message='timeout',
|
||||
)
|
||||
assert unit.retry_status == 'failed'
|
||||
assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
|
||||
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
assert unit.retry_status == 'pending_retry'
|
||||
assert unit.technical_failure_reason_code is None
|
||||
assert audit_calls
|
||||
|
||||
|
||||
def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatch):
|
||||
"""冻结快照已有 ready layout 时,Worker 不应回读当前 Document。"""
|
||||
run = SimpleNamespace(
|
||||
input_snapshot_json={
|
||||
'intakes': [{
|
||||
'intake_id': 11,
|
||||
'documents': [{
|
||||
'document_id': 101,
|
||||
'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}},
|
||||
'layout_schema_candidates': [{'mapping_status': 'accepted'}],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
)
|
||||
unit = SimpleNamespace(intake_id=11, document_id=101)
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('should not query db')))
|
||||
|
||||
intake, document = resolve_unit_runtime_snapshot(run, unit)
|
||||
|
||||
assert intake['intake_id'] == 11
|
||||
assert document['layout_snapshot']['status'] == 'ready'
|
||||
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted'}]
|
||||
|
||||
|
||||
def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(monkeypatch):
|
||||
"""Run 先创建后布局就绪时,Worker 应补读当前 ready layout 和 schema candidates。"""
|
||||
run = SimpleNamespace(
|
||||
input_snapshot_json={
|
||||
'schema': {'definition': {'fields': []}},
|
||||
'intakes': [{
|
||||
'intake_id': 11,
|
||||
'documents': [{
|
||||
'document_id': 101,
|
||||
'layout_snapshot': {'status': 'queued'},
|
||||
'layout_schema_candidates': [],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
)
|
||||
unit = SimpleNamespace(intake_id=11, document_id=101)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get',
|
||||
lambda model, document_id: SimpleNamespace(id=document_id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot',
|
||||
lambda document: {'status': 'ready', 'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_runtime_snapshot.map_layout_document_to_schema',
|
||||
lambda layout_candidate, contract: [{'mapping_status': 'accepted', 'issues': []}],
|
||||
)
|
||||
|
||||
_intake, document = resolve_unit_runtime_snapshot(run, unit)
|
||||
|
||||
assert document['layout_snapshot']['status'] == 'ready'
|
||||
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted', 'issues': []}]
|
||||
|
||||
|
||||
def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch):
|
||||
"""工作台文档详情应直接暴露单元选择、预算和失败事实。"""
|
||||
run = SimpleNamespace(
|
||||
id=1,
|
||||
input_snapshot_json={
|
||||
'schema': {'definition': {'fields': []}},
|
||||
'intakes': [{
|
||||
'intake_id': 11,
|
||||
'documents': [{
|
||||
'document_id': 101,
|
||||
'document_type': 'attachment',
|
||||
'filename': 'po-1.pdf',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
extraction_plan=SimpleNamespace(units=[SimpleNamespace(
|
||||
id=7,
|
||||
document_id=101,
|
||||
status='failed',
|
||||
reason_code=None,
|
||||
selection_batch=1,
|
||||
group_key='451883815A',
|
||||
retry_status='failed',
|
||||
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
budget_cost_json={
|
||||
'initial_attachment_budget': 2,
|
||||
'initial_concurrency_budget': 2,
|
||||
'selected_in_batch': 1,
|
||||
},
|
||||
result_json={},
|
||||
)]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_route_decisions',
|
||||
lambda _run: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
|
||||
lambda _run: ({}, None),
|
||||
)
|
||||
|
||||
items = serialize_workspace_run_documents(run)
|
||||
|
||||
assert items == [{
|
||||
'unit_id': 7,
|
||||
'document_id': 101,
|
||||
'file_name': 'po-1.pdf',
|
||||
'status': 'failed',
|
||||
'selection_batch': 1,
|
||||
'group_key': '451883815A',
|
||||
'retry_status': 'failed',
|
||||
'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
'budget_cost': {
|
||||
'initial_attachment_budget': 2,
|
||||
'initial_concurrency_budget': 2,
|
||||
'selected_in_batch': 1,
|
||||
},
|
||||
'po_number': None,
|
||||
'line_count': 0,
|
||||
'profile': None,
|
||||
'email_supplement': {
|
||||
'status': 'none',
|
||||
'relation_codes': [],
|
||||
'conflict_count': 0,
|
||||
'reservation_id_status': 'unavailable',
|
||||
'source_type_status': 'unavailable',
|
||||
},
|
||||
'reason_code': 'technical_failure',
|
||||
'review_details': [],
|
||||
'available_actions': [],
|
||||
}]
|
||||
@@ -17,6 +17,7 @@ from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingCustomer,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
@@ -136,8 +137,8 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
}
|
||||
|
||||
|
||||
def test_profile_blind_test_approval_does_not_enable_auto_freeze(app):
|
||||
"""关键断言:盲测批准与自动冻结资格独立,首版仍只能人工确认。"""
|
||||
def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(app):
|
||||
"""关键断言:盲测批准应升级当前模板版本资格,避免审批结果无法生效。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
@@ -156,7 +157,12 @@ def test_profile_blind_test_approval_does_not_enable_auto_freeze(app):
|
||||
assert executed['latest_run']['status'] == 'passed'
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert approved['status'] == 'approved'
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
qualification = quality.qualification_summary(profile)
|
||||
assert qualification['status'] == 'auto_freeze_approved'
|
||||
assert qualification['quality_suite_id'] == suite['id']
|
||||
# 盲测只批准解析质量,未配置范围时仍要求人工确认。
|
||||
assert qualification['requires_customer_confirmation'] is True
|
||||
with pytest.raises(Exception) as immutable:
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=documents[0].id, table_id='other',
|
||||
@@ -308,6 +314,41 @@ def test_profile_auto_freeze_qualification_can_be_suspended_independently(app):
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
|
||||
|
||||
def test_profile_auto_freeze_scope_can_be_configured_independently(app):
|
||||
"""关键断言:客户/业务场景授权范围可独立配置,并写入模板审计摘要。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
_publishable_v2_draft(profile)
|
||||
db.session.commit()
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
customer = ShippingCustomer(standard_name='Scope Customer', short_code='SCOP')
|
||||
db.session.add(customer)
|
||||
db.session.commit()
|
||||
|
||||
qualification = quality.configure_auto_freeze_qualification_scope(
|
||||
profile_id=profile.id,
|
||||
actor_id=user.id,
|
||||
customer_ids=[customer.id],
|
||||
business_scenarios=['shipping_notice_order'],
|
||||
requires_customer_confirmation=False,
|
||||
)
|
||||
|
||||
assert qualification.customer_ids_json == [customer.id]
|
||||
assert qualification.business_scenarios_json == ['shipping_notice_order']
|
||||
assert qualification.requires_customer_confirmation is False
|
||||
refreshed = profiles.payload(db.session.get(ShippingOrderDocumentProfile, profile.id))
|
||||
assert refreshed['auto_freeze_qualification']['customer_scope_configured'] is True
|
||||
assert refreshed['auto_freeze_qualification']['business_scenario_scope_configured'] is True
|
||||
assert refreshed['auto_freeze_qualification']['requires_customer_confirmation'] is False
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileAudit.id.desc(),
|
||||
).first()
|
||||
assert audit.event_type == 'auto_freeze_scope_configured'
|
||||
|
||||
|
||||
def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app):
|
||||
"""保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -93,6 +94,44 @@ def _minimal_pdf_bytes(marker: str) -> bytes:
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def test_extract_notice_text_preview_only_skips_pdf_loader_and_ocr(tmp_path):
|
||||
"""上传快览只返回普通文件元信息,绝不能同步调用 PDF Loader 或 OCR。"""
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
|
||||
path = tmp_path / "order.pdf"
|
||||
path.write_bytes(_minimal_pdf_bytes("PREVIEW-ONLY"))
|
||||
with patch('app.services.shipping_notice.notice_upload.loader_pdf.run') as pdf_loader, patch(
|
||||
'app.services.shipping_notice.notice_upload.ocr.run',
|
||||
) as ocr_loader:
|
||||
text, meta = extract_notice_text(path, preview_only=True)
|
||||
|
||||
assert text == ""
|
||||
assert meta == {
|
||||
'warnings': [],
|
||||
'file_type': 'pdf',
|
||||
'content_mode': 'preview',
|
||||
}
|
||||
pdf_loader.assert_not_called()
|
||||
ocr_loader.assert_not_called()
|
||||
|
||||
|
||||
def test_extract_notice_text_preview_only_skips_plain_text_read(tmp_path):
|
||||
"""快览对文本文件也只返回目录元信息,不能读取或持久化正文。"""
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
|
||||
path = tmp_path / "order.txt"
|
||||
path.write_text("PO Number: 4510039227", encoding="utf-8")
|
||||
with patch.object(Path, "read_bytes", side_effect=AssertionError("preview must not read content")):
|
||||
text, meta = extract_notice_text(path, preview_only=True)
|
||||
|
||||
assert text == ""
|
||||
assert meta == {
|
||||
'warnings': [],
|
||||
'file_type': 'txt',
|
||||
'content_mode': 'preview',
|
||||
}
|
||||
|
||||
|
||||
_TINY_PNG = (
|
||||
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00"
|
||||
@@ -290,6 +329,33 @@ def test_extract_eml_skips_signature_inline_image(tmp_path):
|
||||
assert "--- attachment: signature.png ---" not in text
|
||||
|
||||
|
||||
def test_preview_eml_skips_signature_inline_image_from_attachment_count(tmp_path):
|
||||
"""签名图不计数,但快览和深度解析必须保留一致的业务附件键。"""
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
|
||||
raw = _build_eml(
|
||||
subject="Two POs",
|
||||
body="Body with two PO attachments.",
|
||||
attachments=[
|
||||
("order-1.pdf", "application/pdf", _minimal_pdf_bytes("PO-ONE")),
|
||||
("order-2.pdf", "application/pdf", _minimal_pdf_bytes("PO-TWO")),
|
||||
],
|
||||
inline_images=[("signature.png", "<sig001@example.com>", _TINY_PNG)],
|
||||
)
|
||||
path = tmp_path / "preview-with-signature.eml"
|
||||
path.write_bytes(raw)
|
||||
|
||||
_, preview_meta = extract_notice_text(path, eml_attachment_mode="preview")
|
||||
_, deep_meta = extract_notice_text(path)
|
||||
|
||||
assert preview_meta["attachment_count"] == 2
|
||||
assert preview_meta["attachment_registered_count"] == 2
|
||||
assert [item["filename"] for item in preview_meta["attachments"]] == ["order-1.pdf", "order-2.pdf"]
|
||||
assert [item["attachment_key"] for item in preview_meta["attachments"]] == ["att-002", "att-003"]
|
||||
assert [item["attachment_key"] for item in deep_meta["attachments"]] == ["att-002", "att-003"]
|
||||
assert any(str(w).startswith("eml_inline_resources_skipped:") for w in preview_meta["warnings"])
|
||||
|
||||
|
||||
def test_extract_eml_duplicate_attachments(tmp_path):
|
||||
"""同信内重复内容哈希的附件标记 duplicate,不重复抽取。"""
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_shipping_notice_intakes.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -932,6 +934,186 @@ def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_
|
||||
return asset, intake
|
||||
|
||||
|
||||
def test_run_intake_parse_for_pdf_uses_preview_and_creates_no_documents(app, shipping_user, monkeypatch):
|
||||
"""普通文件上传只写快览,深度抽取与 Document 物化必须留给发送阶段。"""
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-PREVIEW')
|
||||
asset.original_filename = 'order.pdf'
|
||||
asset.mime_type = 'application/pdf'
|
||||
intake.parse_status = 'parsing'
|
||||
db.session.commit()
|
||||
calls: list[dict] = []
|
||||
|
||||
def _preview_result(_asset, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return NoticeIntakeResult(
|
||||
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
|
||||
text='', warnings=[], meta={'file_type': 'pdf', 'content_mode': 'preview'},
|
||||
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
|
||||
_preview_result,
|
||||
)
|
||||
result = run_intake_parse(intake, asset)
|
||||
|
||||
assert result['status'] == 'parsed'
|
||||
assert calls == [{
|
||||
'eml_attachment_mode': 'preview', 'retain_payloads': False, 'preview_only': True,
|
||||
}]
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() == 0
|
||||
|
||||
|
||||
def test_materialize_single_file_reextracts_deeply_after_send(app, shipping_user, monkeypatch):
|
||||
"""发送阶段物化普通文件时必须重新走深度抽取,而不是复用上传快览空文本。"""
|
||||
from app.services.shipping_notice.order_extraction_materialization import (
|
||||
ensure_order_extraction_input_documents,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-MATERIALIZE')
|
||||
asset.original_filename = 'order.pdf'
|
||||
asset.mime_type = 'application/pdf'
|
||||
db.session.commit()
|
||||
calls: list[dict] = []
|
||||
|
||||
def _deep_result(_asset, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return NoticeIntakeResult(
|
||||
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
|
||||
text='PO Number: 4510039227\\nSKU-A qty 1', warnings=[], meta={'file_type': 'pdf'},
|
||||
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_materialization.extract_notice_from_asset',
|
||||
_deep_result,
|
||||
)
|
||||
persisted: list[NoticeIntakeResult] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_materialization.persist_intake_documents',
|
||||
lambda **kwargs: persisted.append(kwargs['result']) or {'document_count': 1},
|
||||
)
|
||||
|
||||
ensure_order_extraction_input_documents(
|
||||
intakes=[intake], attachment_selection={}, schema_definition={'fields': []},
|
||||
)
|
||||
|
||||
assert calls == [{'eml_attachment_mode': 'deep'}]
|
||||
assert len(persisted) == 1
|
||||
assert persisted[0].text.startswith('PO Number:')
|
||||
|
||||
|
||||
def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, shipping_user, monkeypatch):
|
||||
"""首轮附件深度抽取最多并发 2,ORM 持久化仍留在调用线程处理。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
import app.services.shipping_notice.order_extraction_materialization as materialization
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-MATERIALIZE')
|
||||
asset.original_filename = 'orders.eml'
|
||||
asset.mime_type = 'message/rfc822'
|
||||
db.session.commit()
|
||||
active = 0
|
||||
peak = 0
|
||||
lock = threading.Lock()
|
||||
|
||||
def _preview_result(_asset, **kwargs):
|
||||
assert kwargs == {'eml_attachment_mode': 'preview', 'retain_payloads': True}
|
||||
return NoticeIntakeResult(
|
||||
filename='orders.eml', source_type='email', source_file_type='message/rfc822',
|
||||
text='mail preview', warnings=[],
|
||||
meta={'attachments': [
|
||||
{
|
||||
'attachment_key': f'order-{index}.pdf', 'filename': f'order-{index}.pdf',
|
||||
'mime_type': 'application/pdf', '_payload_bytes': f'pdf-{index}'.encode(),
|
||||
}
|
||||
for index in range(3)
|
||||
]},
|
||||
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
def _deep_extract(*, payload, filename, mime_type, flask_app):
|
||||
nonlocal active, peak
|
||||
assert flask_app is app
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
time.sleep(0.03)
|
||||
with lock:
|
||||
active -= 1
|
||||
return f'text:{filename}', {'warnings': []}
|
||||
|
||||
monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result)
|
||||
monkeypatch.setattr(materialization, '_parse_attachment_payload', _deep_extract)
|
||||
|
||||
result = materialization._build_selected_eml_result(
|
||||
intake=intake,
|
||||
parent_asset=asset,
|
||||
selected_attachment_keys={'order-0.pdf', 'order-1.pdf', 'order-2.pdf'},
|
||||
max_concurrency=2,
|
||||
)
|
||||
|
||||
assert peak == 2
|
||||
assert [item['extracted_text'] for item in result.meta['attachments']] == [
|
||||
'text:order-0.pdf', 'text:order-1.pdf', 'text:order-2.pdf',
|
||||
]
|
||||
|
||||
|
||||
def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch):
|
||||
"""不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
import app.services.shipping_notice.order_extraction_materialization as materialization
|
||||
|
||||
with app.app_context():
|
||||
first_asset, first_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-1')
|
||||
second_asset, second_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-2')
|
||||
first_asset.original_filename = 'first.pdf'
|
||||
second_asset.original_filename = 'second.pdf'
|
||||
first_asset.mime_type = second_asset.mime_type = 'application/pdf'
|
||||
db.session.commit()
|
||||
active = 0
|
||||
peak = 0
|
||||
lock = threading.Lock()
|
||||
persisted: list[str] = []
|
||||
|
||||
def _deep_result(*, parent_asset, flask_app):
|
||||
nonlocal active, peak
|
||||
assert flask_app is app
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
time.sleep(0.03)
|
||||
with lock:
|
||||
active -= 1
|
||||
return NoticeIntakeResult(
|
||||
filename=parent_asset.original_filename, source_type='pdf', source_file_type='application/pdf',
|
||||
text='PO 4510000001', warnings=[], meta={}, content_hash=str(parent_asset.content_hash),
|
||||
file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(materialization, '_build_single_file_result_in_thread', _deep_result)
|
||||
monkeypatch.setattr(
|
||||
materialization,
|
||||
'persist_intake_documents',
|
||||
lambda **kwargs: persisted.append(kwargs['result'].filename) or {'document_count': 1},
|
||||
)
|
||||
|
||||
materialization.ensure_order_extraction_input_documents(
|
||||
intakes=[first_intake, second_intake],
|
||||
attachment_selection={'max_initial_concurrency': 2},
|
||||
schema_definition={'fields': []},
|
||||
)
|
||||
|
||||
assert peak == 2
|
||||
assert persisted == ['first.pdf', 'second.pdf']
|
||||
|
||||
|
||||
def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch):
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id)
|
||||
@@ -2461,6 +2643,51 @@ def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user)
|
||||
assert finished.status == 'success'
|
||||
|
||||
|
||||
def test_recover_stale_order_extraction_job_requeues_run(app, shipping_user):
|
||||
"""订单抽取 Worker 退出后,超时回收须使 Job 和 Run 一起回到可重试状态。"""
|
||||
with app.app_context():
|
||||
from datetime import timedelta
|
||||
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingOrderExtractionRun
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no='SNER-STALE-RECOVERY',
|
||||
user_id=shipping_user.id,
|
||||
owner_agent_id=shipping_user.id,
|
||||
conversation_id='stale-recovery-test',
|
||||
schema_version_id=1,
|
||||
input_snapshot_hash='stale-recovery-hash',
|
||||
input_snapshot_json={'intakes': []},
|
||||
idempotency_key='stale-recovery-idempotency-key',
|
||||
status='processing',
|
||||
phase='deterministic_parsing',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
|
||||
status='running',
|
||||
business_ref=run.run_no,
|
||||
payload_json={'run_no': run.run_no},
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
started_at=datetime.utcnow() - timedelta(hours=1),
|
||||
locked_at=datetime.utcnow() - timedelta(hours=1),
|
||||
locked_by='dead-worker',
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
count, _ = recover_stale_shipping_notice_jobs()
|
||||
assert count >= 1
|
||||
db.session.expire_all()
|
||||
assert db.session.get(Job, job.id).status == 'queued'
|
||||
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'queued'
|
||||
|
||||
|
||||
def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2(
|
||||
app, shipping_user,
|
||||
):
|
||||
@@ -2775,7 +3002,7 @@ def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, m
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
|
||||
lambda _asset: NoticeIntakeResult(
|
||||
lambda _asset, **_kwargs: NoticeIntakeResult(
|
||||
filename='notice.txt',
|
||||
source_type='manual',
|
||||
source_file_type='text/plain',
|
||||
@@ -2952,7 +3179,7 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
|
||||
lambda _asset: NoticeIntakeResult(
|
||||
lambda _asset, **_kwargs: NoticeIntakeResult(
|
||||
filename='notice.txt',
|
||||
source_type='manual',
|
||||
source_file_type='text/plain',
|
||||
@@ -2976,9 +3203,10 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
|
||||
|
||||
def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch):
|
||||
"""
|
||||
FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。
|
||||
FileAsset → run_intake_parse → DB:shipping_notice 用途的 EML 上传仅持久化附件目录。
|
||||
|
||||
核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。
|
||||
核心逻辑:阶段 1 上传快览只保留邮件头/正文/附件目录,不得把附件全文、派生资产或 Document
|
||||
混入 Intake 摘要;详情接口也只能回放目录事实。
|
||||
"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
@@ -3049,14 +3277,18 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
|
||||
assert structured.get('email', {}).get('subject') == 'Intake EML Persist'
|
||||
attachments = structured.get('attachments') or []
|
||||
assert len(attachments) == 2
|
||||
texts = {row['filename']: row.get('extracted_text') for row in attachments}
|
||||
assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '')
|
||||
assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '')
|
||||
assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '')
|
||||
by_name = {str(row.get('filename') or ''): row for row in attachments}
|
||||
assert by_name['order-a.txt'].get('parse_status') == 'ready_for_extraction'
|
||||
assert by_name['order-b.txt'].get('parse_status') == 'ready_for_extraction'
|
||||
assert by_name['order-a.txt'].get('ready_for_extraction') is True
|
||||
assert by_name['order-b.txt'].get('ready_for_extraction') is True
|
||||
assert all('extracted_text' not in row for row in attachments)
|
||||
assert 'PO-PERSIST-LINE-001' not in str(refreshed.extracted_text or '')
|
||||
expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6')
|
||||
assert refreshed.parser_version == expected_parser
|
||||
assert all('_payload_bytes' not in row for row in attachments)
|
||||
assert all(row.get('asset_no') for row in attachments)
|
||||
assert all(row.get('asset_no') is None for row in attachments)
|
||||
assert all(row.get('document_id') is None for row in attachments)
|
||||
|
||||
from app.services.shipping_notice.intake_service import serialize_intake
|
||||
|
||||
@@ -3067,17 +3299,17 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
|
||||
|
||||
full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
|
||||
full_atts = (full.get('parse_summary') or {}).get('attachments') or []
|
||||
assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '')
|
||||
assert full_atts and 'extracted_text' not in full_atts[0]
|
||||
|
||||
|
||||
def test_run_intake_parse_persists_attached_multipart_and_detail_api(
|
||||
app, client, shipping_user, monkeypatch,
|
||||
):
|
||||
"""
|
||||
FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。
|
||||
FileAsset → run_intake_parse → DB → 详情接口:上传快览只保留附件目录,不递归落 multipart 子内容。
|
||||
|
||||
核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning;
|
||||
status 瘦身、详情含全文。
|
||||
核心逻辑:附件型 multipart 只作为单个目录项展示;嵌套内容和深度警告不应以附件全文形式写入
|
||||
shipping_notice Intake 的摘要或详情接口。
|
||||
"""
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
@@ -3151,18 +3383,12 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
|
||||
for row in (structured.get('attachments') or [])
|
||||
}
|
||||
assert 'bundle-persist.mime' in by_name
|
||||
assert 'inner-depth.mime' in by_name
|
||||
bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '')
|
||||
assert 'PLAIN-PO-101' in bundle_text
|
||||
assert 'HTML-PO-202' in bundle_text
|
||||
assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed'
|
||||
assert by_name['inner-depth.mime'].get('parse_status') == 'skipped'
|
||||
warnings = list(structured.get('warnings') or []) + list(
|
||||
by_name['inner-depth.mime'].get('warnings') or []
|
||||
)
|
||||
assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings)
|
||||
assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '')
|
||||
assert 'HTML-PO-202' in str(refreshed.extracted_text or '')
|
||||
assert 'inner-depth.mime' not in by_name
|
||||
assert by_name['bundle-persist.mime'].get('parse_status') == 'directory_only'
|
||||
assert by_name['bundle-persist.mime'].get('ready_for_extraction') is False
|
||||
assert by_name['bundle-persist.mime'].get('catalog_reason') == 'unknown_binary'
|
||||
assert 'PLAIN-PO-101' not in str(refreshed.extracted_text or '')
|
||||
assert 'HTML-PO-202' not in str(refreshed.extracted_text or '')
|
||||
|
||||
lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
|
||||
lean_bundle = next(
|
||||
@@ -3178,8 +3404,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
|
||||
for row in ((full.get('parse_summary') or {}).get('attachments') or [])
|
||||
if row.get('filename') == 'bundle-persist.mime'
|
||||
)
|
||||
assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '')
|
||||
assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '')
|
||||
assert 'extracted_text' not in full_bundle
|
||||
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'}
|
||||
|
||||
@@ -3193,8 +3418,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
|
||||
status_atts = (status_item.get('parse_summary') or {}).get('attachments') or []
|
||||
status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime')
|
||||
assert 'extracted_text' not in status_bundle
|
||||
status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime')
|
||||
assert status_inner.get('parse_status') == 'skipped'
|
||||
assert all(row.get('filename') != 'inner-depth.mime' for row in status_atts)
|
||||
|
||||
detail_res = client.get(
|
||||
'/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001',
|
||||
@@ -3203,10 +3427,8 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
|
||||
assert detail_res.status_code == 200
|
||||
detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or []
|
||||
detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime')
|
||||
assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '')
|
||||
assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '')
|
||||
detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime')
|
||||
assert detail_inner.get('parse_status') == 'skipped'
|
||||
assert 'extracted_text' not in detail_bundle
|
||||
assert all(row.get('filename') != 'inner-depth.mime' for row in detail_atts)
|
||||
|
||||
|
||||
def test_intake_status_api_strips_texts_detail_returns_full(app, client):
|
||||
@@ -3413,8 +3635,10 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""
|
||||
上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document;
|
||||
点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。
|
||||
上传预处理验收:EML 快览阶段不创建附件 Document、派生资产或布局任务。
|
||||
|
||||
核心逻辑:即使附件是可解析 PDF,shipping_notice 上传阶段也只登记目录与可解析标记;
|
||||
真正的 Document/资产/布局物化必须等到点击发送后的计划链路。
|
||||
"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
@@ -3489,7 +3713,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
if str(w).startswith('document_candidate_persist_failed')
|
||||
]
|
||||
assert not persist_warns, persist_warns
|
||||
assert first.get('document_count') == 4, first
|
||||
assert first.get('document_count') == 0, first
|
||||
docs = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter_by(intake_id=refreshed_intake.id)
|
||||
@@ -3511,26 +3735,24 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json)
|
||||
body_docs = [d for d in docs if d.document_type == 'email_body']
|
||||
assert len(body_docs) == 1
|
||||
assert body_docs[0].classification == 'email_context'
|
||||
pdf_docs = [d for d in docs if d.document_type == 'attachment']
|
||||
assert len(pdf_docs) == 3
|
||||
assert all(d.classification == 'order_notice' for d in pdf_docs)
|
||||
assert all(d.asset_id for d in pdf_docs)
|
||||
assert len(docs) == 0, (first, refreshed_intake.parse_warnings_json)
|
||||
assert len(cands) == 0
|
||||
assert len(children) == 3
|
||||
assert len({c.content_hash for c in children}) == 3
|
||||
assert len(children) == 0
|
||||
from app.models import Job, ShippingDocumentLayoutVersion
|
||||
|
||||
assert ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]),
|
||||
).count() == 3
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 0
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
|
||||
|
||||
structured = refreshed_intake.structured_result_json or {}
|
||||
assert structured.get('attachment_count') == 3
|
||||
assert structured.get('ready_attachment_count') == 3
|
||||
rows = structured.get('attachments') or []
|
||||
assert {row.get('filename') for row in rows} == {f'{po}.pdf' for po in markers}
|
||||
assert all(row.get('parse_status') == 'ready_for_extraction' for row in rows)
|
||||
assert all('extracted_text' not in row for row in rows)
|
||||
|
||||
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
|
||||
assert detail['document_count'] == 4
|
||||
assert detail['document_count'] == 0
|
||||
assert detail['candidate_count'] == 0
|
||||
|
||||
intake2 = (
|
||||
@@ -3549,22 +3771,22 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
.one()
|
||||
.id
|
||||
)
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 0
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 3
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 0
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
|
||||
assert (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
|
||||
.count()
|
||||
== 3
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。"""
|
||||
"""HTML 正文表格快览只保留脱敏摘要,不在上传阶段生成 Document 或布局版本。"""
|
||||
from email.message import EmailMessage
|
||||
from io import BytesIO
|
||||
|
||||
@@ -3607,18 +3829,19 @@ def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak
|
||||
|
||||
result = run_intake_parse(intake, parent)
|
||||
db.session.expire_all()
|
||||
body = ShippingNoticeDocument.query.filter_by(
|
||||
intake_id=intake.id, document_type='email_body',
|
||||
).one()
|
||||
version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one()
|
||||
structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json
|
||||
|
||||
assert result['status'] == 'parsed'
|
||||
assert version.status == 'needs_review'
|
||||
assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom'
|
||||
assert 'SECRET' not in repr(version.payload_json)
|
||||
assert 'body_html_tables' not in repr(structured)
|
||||
assert '<table' not in repr(structured)
|
||||
assert ShippingNoticeDocument.query.filter_by(intake_id=intake.id).count() == 0
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 0
|
||||
email_summary = (structured.get('email') or {})
|
||||
html_tables = email_summary.get('body_html_tables') or []
|
||||
assert len(html_tables) == 1
|
||||
assert '<table' in str(html_tables[0] or '')
|
||||
assert 'script' not in str(html_tables[0] or '').lower()
|
||||
assert 'SECRET' not in repr(structured)
|
||||
assert structured.get('document_count') == 0
|
||||
assert structured.get('candidate_count') == 0
|
||||
|
||||
|
||||
def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
|
||||
@@ -4325,7 +4548,7 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
|
||||
lambda _a: NoticeIntakeResult(
|
||||
lambda _a, **_kwargs: NoticeIntakeResult(
|
||||
filename='clear.eml',
|
||||
source_type='email',
|
||||
source_file_type='message/rfc822',
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""验证发货通知上传批次迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_shipping_notice_upload_batch_migration_round_trip():
|
||||
"""上传批次字段和查询索引必须可升级回退,避免部署后历史附件无法查询。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.0cf78a9b0c12_add_shipping_notice_upload_batch'
|
||||
)
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_notice_intakes',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('user_id', sa.Integer, nullable=False),
|
||||
sa.Column('created_at', sa.DateTime, nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'upload_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns('shipping_notice_intakes')
|
||||
}
|
||||
assert 'ix_shipping_notice_intakes_user_upload_batch_created' in {
|
||||
item['name'] for item in inspector.get_indexes('shipping_notice_intakes')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
assert 'upload_batch_id' not in {
|
||||
item['name'] for item in sa.inspect(connection).get_columns('shipping_notice_intakes')
|
||||
}
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -0,0 +1,381 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_auto_freeze_policy.py
|
||||
|
||||
用途:验证订单抽取 Run 的自动冻结门禁摘要按模板资格、技术失败和预算事实 fail-closed。
|
||||
依赖:Run 创建夹具、Profile 资格模型与自动冻结策略服务。
|
||||
逻辑:结果后评估只汇总已知事实,不在客户/场景资格未建模前提前放行自动冻结。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
# 本组用例只验证 Run 级门禁摘要,不执行 OpenCV 版面识别;本地缺少 cv2 时用空模块兜底导入链。
|
||||
if 'cv2' not in sys.modules:
|
||||
sys.modules['cv2'] = types.SimpleNamespace()
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingDocumentProfileAutoFreezeQualification,
|
||||
ShippingCustomer,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
)
|
||||
from app.services.shipping_notice.order_auto_freeze_policy import evaluate_run_auto_freeze_policy
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrderDocumentProfile:
|
||||
"""构造最小 published Profile,供资格与 Run 门禁测试复用。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code=f'AF-{checksum[:6]}',
|
||||
display_name='Auto freeze profile',
|
||||
version=1,
|
||||
status='published',
|
||||
schema_version_id=schema_version_id,
|
||||
structure_fingerprint='fp-' + checksum[:16],
|
||||
checksum=checksum,
|
||||
definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': []},
|
||||
published_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
return profile
|
||||
|
||||
|
||||
def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None:
|
||||
"""为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。"""
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=run_id,
|
||||
intake_id=intake_id,
|
||||
schema_version_id=schema_version_id,
|
||||
input_snapshot_hash=f'run-{run_id}-customer-{customer.id}',
|
||||
input_snapshot_json={},
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id,
|
||||
role='bill_to',
|
||||
identity_components_json={},
|
||||
status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint=f'customer-{customer.id}',
|
||||
identity_rule_version='customer-match.v1',
|
||||
resolution_method='manual',
|
||||
confirmed_at=datetime.utcnow(),
|
||||
))
|
||||
|
||||
|
||||
def _materialize_run_plan(run) -> None:
|
||||
"""模拟 Worker 物化边界,为 Run 级门禁测试创建延迟生成的执行计划。"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
|
||||
materialize_order_extraction_run_inputs(run)
|
||||
|
||||
|
||||
def test_evaluate_run_auto_freeze_policy_keeps_fail_closed_with_run_blockers(app):
|
||||
"""即使命中已批准模板,技术失败、预算停止与待处理订单仍必须阻断自动冻结。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-POLICY')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
_materialize_run_plan(run)
|
||||
plan = run.extraction_plan
|
||||
unit = plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='a' * 64)
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification(
|
||||
profile_id=profile.id,
|
||||
profile_version=profile.version,
|
||||
profile_checksum=profile.checksum,
|
||||
schema_version_id=run.schema_version_id,
|
||||
parser_version='deterministic-order-parser.v1',
|
||||
status='auto_freeze_approved',
|
||||
)
|
||||
next_sequence_no = (
|
||||
db.session.query(ShippingOrderExtractionProgressEvent.sequence_no)
|
||||
.filter_by(run_id=run.id)
|
||||
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
|
||||
.limit(1)
|
||||
.scalar()
|
||||
or 0
|
||||
) + 1
|
||||
unit.technical_failure_reason_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
|
||||
run.status = 'review_required'
|
||||
db.session.add_all([
|
||||
qualification,
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
job_id=job.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=True,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=1,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id,
|
||||
sequence_no=next_sequence_no,
|
||||
visibility='workspace',
|
||||
event_code='budget_stopped',
|
||||
status='completed',
|
||||
occurred_at=datetime.utcnow(),
|
||||
reason_code='budget_initial_limit',
|
||||
idempotency_key=f'budget-stop-{run.id}',
|
||||
summary_json={'reason_codes': ['budget_initial_limit']},
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 1})
|
||||
|
||||
assert policy['enabled'] is False
|
||||
assert policy['selected_profile_id'] == profile.id
|
||||
assert policy['qualification_id'] == qualification.id
|
||||
assert policy['qualification_status'] == 'auto_freeze_approved'
|
||||
assert set(policy['blocking_reason_codes']) >= {
|
||||
'technical_failure_present',
|
||||
'budget_stopped',
|
||||
'review_required',
|
||||
'pending_orders_present',
|
||||
'customer_scope_not_configured',
|
||||
'business_scenario_not_configured',
|
||||
'customer_confirmation_required',
|
||||
}
|
||||
|
||||
|
||||
def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app):
|
||||
"""模板资格被暂停后,新 Run 即使命中该模板也必须继续人工确认。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SUSPENDED')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
_materialize_run_plan(run)
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='b' * 64)
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification(
|
||||
profile_id=profile.id,
|
||||
profile_version=profile.version,
|
||||
profile_checksum=profile.checksum,
|
||||
schema_version_id=run.schema_version_id,
|
||||
parser_version='deterministic-order-parser.v1',
|
||||
status='auto_freeze_suspended',
|
||||
)
|
||||
db.session.add_all([
|
||||
qualification,
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
job_id=job.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=True,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=1,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
|
||||
|
||||
assert policy['enabled'] is False
|
||||
assert policy['qualification_status'] == 'auto_freeze_suspended'
|
||||
assert 'profile_auto_freeze_suspended' in policy['blocking_reason_codes']
|
||||
assert 'customer_scope_not_configured' in policy['blocking_reason_codes']
|
||||
|
||||
|
||||
def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app):
|
||||
"""客户和业务场景配置命中且无真实 pending 时,Run 可以进入自动冻结放行状态。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-SCOPE-MATCH')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
_materialize_run_plan(run)
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='c' * 64)
|
||||
customer = ShippingCustomer(standard_name='Matched Customer', short_code='MATCH')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
_confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer)
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification(
|
||||
profile_id=profile.id,
|
||||
profile_version=profile.version,
|
||||
profile_checksum=profile.checksum,
|
||||
schema_version_id=run.schema_version_id,
|
||||
parser_version='deterministic-order-parser.v1',
|
||||
status='auto_freeze_approved',
|
||||
customer_ids_json=[customer.id],
|
||||
business_scenarios_json=['shipping_notice_order'],
|
||||
requires_customer_confirmation=False,
|
||||
)
|
||||
db.session.add_all([
|
||||
qualification,
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
job_id=job.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=True,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=1,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
|
||||
|
||||
assert policy['enabled'] is True
|
||||
assert policy['customer_scope_status'] == 'matched'
|
||||
assert policy['business_scenario_status'] == 'matched'
|
||||
assert policy['confirmed_customer_ids'] == [customer.id]
|
||||
assert policy['authorized_customer_ids'] == [customer.id]
|
||||
assert policy['customer_confirmation_required'] is False
|
||||
assert 'customer_scope_not_configured' not in policy['blocking_reason_codes']
|
||||
assert 'customer_scope_out_of_scope' not in policy['blocking_reason_codes']
|
||||
assert 'business_scenario_not_configured' not in policy['blocking_reason_codes']
|
||||
assert 'business_scenario_out_of_scope' not in policy['blocking_reason_codes']
|
||||
assert 'customer_confirmation_required' not in policy['blocking_reason_codes']
|
||||
|
||||
# Worker 提交本 Unit 的候选时,Run 可能尚未转为 review_required;Unit 事实必须先阻断副作用。
|
||||
unit.status = 'review_required'
|
||||
run.status = 'processing'
|
||||
db.session.flush()
|
||||
blocked = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
|
||||
|
||||
assert blocked['enabled'] is False
|
||||
assert 'unit_review_required' in blocked['blocking_reason_codes']
|
||||
|
||||
|
||||
def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app):
|
||||
"""仅因自动消费尚未执行而遗留的空原因 pending,不应继续阻断自动冻结。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-PENDING-PLACEHOLDER')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
_materialize_run_plan(run)
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
profile = _published_profile(schema_version_id=run.schema_version_id, checksum='d' * 64)
|
||||
customer = ShippingCustomer(standard_name='Matched Customer 2', short_code='MAT')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
_confirm_run_customer(run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, customer=customer)
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification(
|
||||
profile_id=profile.id,
|
||||
profile_version=profile.version,
|
||||
profile_checksum=profile.checksum,
|
||||
schema_version_id=run.schema_version_id,
|
||||
parser_version='deterministic-order-parser.v1',
|
||||
status='auto_freeze_approved',
|
||||
customer_ids_json=[customer.id],
|
||||
business_scenarios_json=['shipping_notice_order'],
|
||||
requires_customer_confirmation=False,
|
||||
)
|
||||
db.session.add_all([
|
||||
qualification,
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
job_id=job.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=True,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=1,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={
|
||||
'pending_count': 1,
|
||||
'pending_orders': [{
|
||||
'candidate_no': 'SNC-PLACEHOLDER',
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
'duplicate_status': None,
|
||||
}],
|
||||
})
|
||||
|
||||
assert policy['enabled'] is True
|
||||
assert 'pending_orders_present' not in policy['blocking_reason_codes']
|
||||
@@ -14,6 +14,7 @@ from types import SimpleNamespace
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import app.services.shipping_notice.preview_grant_store as preview_grant_store_service
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
@@ -894,7 +895,8 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch):
|
||||
"""预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.redis_client.get_redis_client', lambda: None)
|
||||
app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = False
|
||||
monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None)
|
||||
with pytest.raises(Exception) as unavailable:
|
||||
service._preview_grant_store()
|
||||
assert getattr(unavailable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE'
|
||||
@@ -903,6 +905,17 @@ def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app,
|
||||
assert getattr(unbound.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypatch):
|
||||
"""开发环境允许单进程内存兜底,仍需保持一次性令牌语义。"""
|
||||
with app.app_context():
|
||||
app.config['ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK'] = True
|
||||
monkeypatch.setattr(preview_grant_store_service, 'get_redis_client', lambda: None)
|
||||
store = service._preview_grant_store()
|
||||
store.setex('preview-token', 30, '{"page_no":1}')
|
||||
assert store.getdel('preview-token') == '{"page_no":1}'
|
||||
assert store.getdel('preview-token') is None
|
||||
|
||||
|
||||
def test_profile_region_preview_requires_a_bound_document(app, monkeypatch):
|
||||
"""局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -22,58 +22,57 @@ def _run() -> ShippingOrderExtractionRun:
|
||||
row = ShippingOrderExtractionRun(
|
||||
run_no='SNER-PROGRESS', user_id=1, owner_agent_id=1, conversation_id='progress-conv',
|
||||
schema_version_id=1, input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
|
||||
status='running', phase='calling_provider',
|
||||
status='processing', phase='deterministic_parsing',
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
def test_progress_events_dedupe_parallel_stages_and_protect_hxops_persistence(app):
|
||||
"""重复SSE不重复落库;并行阶段合并,持久化阶段不被迟到Dify节点覆盖。"""
|
||||
def test_progress_events_dedupe_sequence_and_protect_terminal_run(app):
|
||||
"""重复业务事件不重复落库;终态后迟到普通事件不能覆盖当前投影。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-progress'},
|
||||
event={'event_code': 'document_queued', 'document_id': 11},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'},
|
||||
event={'event_code': 'profile_matching', 'unit_id': 7, 'document_id': 11},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
|
||||
event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_started', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
|
||||
event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}},
|
||||
) is False
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.current_stage_code == 'order_recognition'
|
||||
assert set(run.active_stage_codes_json or []) == {'document_processing', 'order_recognition'}
|
||||
assert run.current_stage_code == 'profile_matched'
|
||||
assert list(run.active_stage_codes_json or []) == ['profile_matched']
|
||||
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n2', 'node_type': 'llm'},
|
||||
event={'event_code': 'candidate_ready', 'unit_id': 7, 'document_id': 11},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.current_stage_code == 'order_recognition'
|
||||
assert run.current_stage_code == 'candidate_ready'
|
||||
|
||||
run.status = 'completed'
|
||||
run.progress_version = 4
|
||||
db.session.commit()
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'hxops_persistence_started', 'job_id': 1, 'attempt_count': 1},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_finished', 'workflow_run_id': 'wf-progress', 'node_execution_id': 'n1', 'node_type': 'document-extractor'},
|
||||
) is True
|
||||
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
|
||||
) is False
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.current_stage_code == 'hxops_persistence'
|
||||
assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 6
|
||||
assert run.current_stage_code == 'candidate_ready'
|
||||
assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 4
|
||||
|
||||
|
||||
def test_progress_mapping_version_fits_persisted_column(app):
|
||||
@@ -82,7 +81,7 @@ def test_progress_mapping_version_fits_persisted_column(app):
|
||||
run = _run()
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'workflow_started', 'workflow_run_id': 'wf-version'},
|
||||
event={'event_code': 'document_queued', 'document_id': 11},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
persisted = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
@@ -90,43 +89,115 @@ def test_progress_mapping_version_fits_persisted_column(app):
|
||||
assert persisted.progress_mapping_version == MAPPING_VERSION
|
||||
|
||||
|
||||
def test_progress_event_discards_custom_node_title(app):
|
||||
"""自定义节点标题可能包含业务意图,诊断事件与幂等键均不得持久化该文本。"""
|
||||
def test_progress_event_accepts_email_supplement_merge_summary(app):
|
||||
"""正文补充合并事件必须可持久化,并把当前投影推进到 supplement 合并阶段。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'email_supplement_merged',
|
||||
'unit_id': 7,
|
||||
'document_id': 11,
|
||||
'summary': {'status': 'merged', 'relation_codes': ['po_mpn'], 'conflict_count': 0},
|
||||
},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
|
||||
assert run.current_stage_code == 'email_supplement_merged'
|
||||
assert list(run.active_stage_codes_json or []) == ['email_supplement_merged']
|
||||
assert event.summary_json == {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}
|
||||
|
||||
|
||||
def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app):
|
||||
"""计划创建、扩批启动和预算停止必须作为 Run 级事实进入统一进度流。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'plan_created',
|
||||
'summary': {'unit_count': 2, 'selection': {'selected_attachment_count': 2}},
|
||||
},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'initial_wave_started',
|
||||
'summary': {'selected_attachment_count': 2, 'max_initial_attachments': 2},
|
||||
},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'expansion_wave_started',
|
||||
'summary': {'selection_batch': 2, 'unit_count': 2, 'reason_codes': ['required_field_missing']},
|
||||
},
|
||||
) is True
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'budget_stopped',
|
||||
'reason_code': 'budget_initial_limit',
|
||||
'summary': {'budget_limited_attachment_count': 2},
|
||||
},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(
|
||||
ShippingOrderExtractionProgressEvent.sequence_no.asc(),
|
||||
).all()
|
||||
assert [row.event_code for row in events] == [
|
||||
'plan_created',
|
||||
'initial_wave_started',
|
||||
'expansion_wave_started',
|
||||
'budget_stopped',
|
||||
]
|
||||
assert events[2].summary_json == {
|
||||
'reason_codes': ['required_field_missing'],
|
||||
'selection_batch': 2,
|
||||
'unit_count': 2,
|
||||
}
|
||||
assert run.current_stage_code == 'budget_stopped'
|
||||
assert list(run.active_stage_codes_json or []) == []
|
||||
|
||||
|
||||
def test_progress_event_discards_unstructured_payload(app):
|
||||
"""自定义非结构化文本不能进入新事件表摘要。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
event = {
|
||||
'event_type': 'node_started',
|
||||
'workflow_run_id': 'wf-safe',
|
||||
'node_execution_id': 'node-safe',
|
||||
'node_type': 'llm',
|
||||
'event_code': 'profile_matching',
|
||||
'document_id': 11,
|
||||
'node_title': '客户甲秘密订单识别',
|
||||
}
|
||||
assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is True
|
||||
event['node_title'] = '另一个可能敏感的标题'
|
||||
assert record_order_extraction_progress_event(run_no=run.run_no, event=event) is False
|
||||
|
||||
row = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
|
||||
assert not hasattr(row, 'node_title')
|
||||
assert '客户甲' not in str(row.details_json)
|
||||
rows = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(ShippingOrderExtractionProgressEvent.id.asc()).all()
|
||||
assert len(rows) == 1
|
||||
assert all('客户甲' not in str(row.summary_json) for row in rows)
|
||||
|
||||
|
||||
def test_terminal_run_records_diagnostics_without_mutating_projection(app):
|
||||
"""终态后的迟到节点只保留管理员审计,绝不把用户状态改回运行中。"""
|
||||
def test_terminal_run_rejects_late_workspace_event_without_mutating_projection(app):
|
||||
"""终态后的迟到普通事件直接忽略,绝不把用户状态改回处理中。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
run.status = 'completed'
|
||||
run.current_stage_code = 'hxops_persistence'
|
||||
run.current_stage_code = 'candidate_ready'
|
||||
run.progress_version = 9
|
||||
db.session.commit()
|
||||
|
||||
assert record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={'event_type': 'node_started', 'workflow_run_id': 'wf-late', 'node_execution_id': 'late-1', 'node_type': 'llm'},
|
||||
) is True
|
||||
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
|
||||
) is False
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.status == 'completed'
|
||||
assert run.current_stage_code == 'hxops_persistence'
|
||||
assert run.current_stage_code == 'candidate_ready'
|
||||
assert run.progress_version == 9
|
||||
|
||||
|
||||
@@ -136,11 +207,11 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
|
||||
run = _run()
|
||||
now = datetime.utcnow()
|
||||
expired = ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id, event_type='node_finished', stage_code='order_recognition', event_status='completed',
|
||||
run_id=run.id, sequence_no=1, visibility='workspace', event_code='candidate_ready', status='completed',
|
||||
received_at=now - timedelta(days=91), idempotency_key='expired-progress-event', expires_at=now - timedelta(seconds=1),
|
||||
)
|
||||
retained = ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id, event_type='node_started', stage_code='document_processing', event_status='running',
|
||||
run_id=run.id, sequence_no=2, visibility='workspace', event_code='profile_matching', status='completed',
|
||||
received_at=now, idempotency_key='retained-progress-event', expires_at=now + timedelta(days=1),
|
||||
)
|
||||
db.session.add_all([expired, retained])
|
||||
@@ -152,9 +223,9 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
|
||||
|
||||
|
||||
def test_user_slow_threshold_uses_p95_after_minimum_samples_and_is_capped(app):
|
||||
"""慢响应阈值不足20样本回退60秒,满足样本后按P95且上限300秒。"""
|
||||
"""慢响应阈值不足20样本回退180秒,满足样本后按P95且上限300秒。"""
|
||||
with app.app_context():
|
||||
assert get_order_extraction_user_slow_threshold_seconds() == 60
|
||||
assert get_order_extraction_user_slow_threshold_seconds() == 180
|
||||
base = datetime.utcnow() - timedelta(minutes=10)
|
||||
for index in range(20):
|
||||
run = ShippingOrderExtractionRun(
|
||||
|
||||
@@ -1,344 +1,65 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_quality_gate.py
|
||||
|
||||
用途:验证 L7 订单抽取双人影子标签、指标、双角色批准和 Runtime Binding 自动建单门禁。
|
||||
依赖:质量服务、Agent Runtime Binding、订单抽取 Run 测试夹具。
|
||||
逻辑:构造 100 个匿名一致样本达标批次,并覆盖分歧、权限边界和批准引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
"""Verify order extraction quality batches without runtime bindings."""
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction
|
||||
from app.jobs.queue import claim_next_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentRuntimeBinding,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderExtractionQualityBatch,
|
||||
ShippingOrderExtractionQualityLabel,
|
||||
ShippingOrderExtractionRun,
|
||||
User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||||
from app.services.shipping_notice.order_extraction_quality_service import (
|
||||
approve_quality_batch,
|
||||
list_approved_quality_batches,
|
||||
quality_metrics,
|
||||
require_approved_quality_batch,
|
||||
save_quality_label,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.models import ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderExtractionRun, User
|
||||
from app.services.shipping_notice.order_extraction_quality_service import quality_metrics, save_quality_label
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
def _quality_batch(owner: Agent, schema_version_id: int, creator: User) -> ShippingOrderExtractionQualityBatch:
|
||||
"""建立 collecting 批次,供服务级测试批量注入匿名标签。"""
|
||||
batch = ShippingOrderExtractionQualityBatch(
|
||||
batch_no=f'SOQ-TEST-{owner.id}', owner_agent_id=owner.id,
|
||||
schema_version_id=schema_version_id,
|
||||
threshold_version='l7.v1', status='collecting', created_by_id=creator.id,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
return batch
|
||||
|
||||
|
||||
def _add_agreed_samples(
|
||||
batch: ShippingOrderExtractionQualityBatch, runs: list[ShippingOrderExtractionRun],
|
||||
first: User, second: User,
|
||||
) -> None:
|
||||
"""为每个 Run 写入两份完全一致且无错误的匿名标签。"""
|
||||
for run in runs:
|
||||
for reviewer in (first, second):
|
||||
db.session.add(ShippingOrderExtractionQualityLabel(
|
||||
batch_id=batch.id, run_id=run.id, reviewer_id=reviewer.id,
|
||||
core_expected_count=4, core_extracted_count=4, core_correct_count=4,
|
||||
wrong_merge=False, wrong_split=False, wrong_auto_create=False,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_quality_metrics_require_two_matching_reviews(app):
|
||||
"""单人和分歧标签不计样本;100 个一致样本才通过固定阈值。"""
|
||||
"""Only matching reviews count toward quality eligibility metrics."""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS')
|
||||
second = User(username='quality-second', email='quality-second@example.com', role='admin', password_hash='x')
|
||||
db.session.add(second)
|
||||
user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS')
|
||||
reviewer = User(username='quality-reviewer', email='quality-reviewer@example.com', role='admin', password_hash='x')
|
||||
db.session.add(reviewer)
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-QUALITY-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'quality-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 1000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
batch = ShippingOrderExtractionQualityBatch(
|
||||
batch_no='SOQ-QUALITY-METRICS', owner_agent_id=owner.id, schema_version_id=1,
|
||||
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
|
||||
)
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no='SNER-QUALITY-METRICS', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=session.session_id, schema_version_id=1,
|
||||
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
|
||||
status='completed', phase='completed', auto_freeze_policy_json={'enabled': False},
|
||||
)
|
||||
db.session.add_all([batch, run])
|
||||
db.session.flush()
|
||||
for actor in (user, reviewer):
|
||||
db.session.add(ShippingOrderExtractionQualityLabel(
|
||||
batch_id=batch.id, run_id=run.id, reviewer_id=actor.id,
|
||||
core_expected_count=4, core_extracted_count=4, core_correct_count=4,
|
||||
wrong_merge=False, wrong_split=False, wrong_auto_create=False,
|
||||
))
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, user, second)
|
||||
|
||||
metrics = quality_metrics(batch)
|
||||
|
||||
assert metrics['eligible'] is True
|
||||
assert metrics['agreed_sample_count'] == 100
|
||||
assert metrics['precision'] == 1.0
|
||||
assert metrics['recall'] == 1.0
|
||||
assert quality_metrics(batch)['agreed_sample_count'] == 1
|
||||
|
||||
|
||||
def test_quality_label_rejects_wrong_owner_or_auto_create_run(app):
|
||||
"""标签只能引用同 Owner/Schema 的终态 unit.v3 影子 Run,不能标生产自动建单结果。"""
|
||||
def test_quality_label_rejects_auto_creation_run(app):
|
||||
"""Production auto-creation Runs cannot become quality samples."""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-LABEL')
|
||||
user, owner, session, _intake, _document = _seed_run_input(suffix='QUALITY-INVALID')
|
||||
user.role = 'admin'
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
batch = ShippingOrderExtractionQualityBatch(
|
||||
batch_no='SOQ-QUALITY-INVALID', owner_agent_id=owner.id, schema_version_id=1,
|
||||
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
|
||||
)
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=session.session_id, schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
|
||||
status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': True},
|
||||
conversation_id=session.session_id, schema_version_id=1,
|
||||
input_snapshot_hash='c' * 64, input_snapshot_json={}, idempotency_key='d' * 64,
|
||||
status='completed', phase='completed', auto_freeze_policy_json={'enabled': True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add_all([batch, run])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
try:
|
||||
save_quality_label(
|
||||
batch_id=batch.id, run_no=run.run_no, actor_id=user.id,
|
||||
payload={'core_expected_count': 4, 'core_extracted_count': 4, 'core_correct_count': 4},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID'
|
||||
|
||||
|
||||
def test_approved_quality_batch_is_required_for_auto_create_binding(app):
|
||||
"""unit.v3 自动建单必须引用同 Owner、当前阈值、双人批准且仍达标的批次。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-BINDING')
|
||||
business = User(username='quality-business', email='quality-business@example.com', role='admin', password_hash='x')
|
||||
technical = User(username='quality-technical', email='quality-technical@example.com', role='admin', password_hash='x')
|
||||
db.session.add_all([business, technical])
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-APPROVE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'approve-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 2000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 3000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, business, technical)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
|
||||
provider = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
|
||||
approved = require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
|
||||
)
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True, quality_batch_id=batch.id,
|
||||
config={'auto_create_enabled': True},
|
||||
)
|
||||
|
||||
assert approved.status == 'approved'
|
||||
assert binding.quality_batch_id == batch.id
|
||||
|
||||
|
||||
def test_same_admin_cannot_approve_both_roles(app):
|
||||
"""业务和技术批准必须由不同管理员完成。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-APPROVERS')
|
||||
user.role = 'admin'
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
batch.status = 'ready'
|
||||
batch.business_approved_by_id = user.id
|
||||
batch.business_approved_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError):
|
||||
require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
|
||||
)
|
||||
with pytest.raises(ConflictError):
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=user.id)
|
||||
|
||||
|
||||
def test_first_approval_freezes_labels_and_schema_mismatch_blocks_release(app):
|
||||
"""任一角色批准后标签不可变化,且旧 Schema 批次不能给新 Schema 的执行放行。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-FREEZE')
|
||||
user.role = 'admin'
|
||||
second = User(username='quality-freeze-second', email='quality-freeze-second@example.com', role='admin', password_hash='x')
|
||||
db.session.add(second)
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-FREEZE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'freeze-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 4000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 5000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, user, second)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=user.id)
|
||||
|
||||
with pytest.raises(ConflictError) as frozen:
|
||||
save_quality_label(
|
||||
batch_id=batch.id, run_no=runs[0].run_no, actor_id=second.id,
|
||||
payload={'core_expected_count': 5, 'core_extracted_count': 5, 'core_correct_count': 5},
|
||||
)
|
||||
with pytest.raises(ConflictError):
|
||||
require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id,
|
||||
schema_version_id=batch.schema_version_id + 1,
|
||||
)
|
||||
|
||||
assert frozen.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE'
|
||||
|
||||
|
||||
def test_approved_batch_is_listed_and_frozen_on_run(app):
|
||||
"""管理端候选只含当前 Schema 已批准批次,启用后 Run 必须冻结相同批次。"""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-RUN')
|
||||
business = User(username='quality-run-business', email='quality-run-business@example.com', role='admin', password_hash='x')
|
||||
technical = User(username='quality-run-technical', email='quality-run-technical@example.com', role='admin', password_hash='x')
|
||||
db.session.add_all([business, technical])
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-RUN-GATE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'run-gate-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 6000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 7000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, business, technical)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
|
||||
binding = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id,
|
||||
config={'auto_create_enabled': True},
|
||||
)
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
|
||||
schema.auto_creation_policy_json = {'enabled': True}
|
||||
db.session.commit()
|
||||
|
||||
listed = list_approved_quality_batches(owner_agent_id=owner.id)
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=owner.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert [item['id'] for item in listed] == [batch.id]
|
||||
assert run.quality_batch_id == batch.id
|
||||
assert run.provider_config_json['auto_create_enabled'] is True
|
||||
|
||||
db.session.commit()
|
||||
batch.threshold_version = 'obsolete-threshold'
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='quality-gate-worker',
|
||||
)
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.refresh(run)
|
||||
assert run.status == 'failed'
|
||||
assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED'
|
||||
|
||||
|
||||
def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app):
|
||||
"""质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。"""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW')
|
||||
provider = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
binding = AgentRuntimeBinding.query.filter_by(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
).one()
|
||||
binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True}
|
||||
binding.provider_agent_id = provider.id
|
||||
# The missing quality batch is intentional: schema-disabled execution is shadow-only.
|
||||
binding.quality_batch_id = None
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=owner.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert run.provider_config_json['auto_create_enabled'] is False
|
||||
assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False
|
||||
assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True
|
||||
|
||||
def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client):
|
||||
"""质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-API')
|
||||
user.role = 'admin'
|
||||
db.session.flush()
|
||||
token = issue_local_access_token(user)
|
||||
db.session.commit()
|
||||
owner_id = owner.id
|
||||
admin_username = user.username
|
||||
|
||||
forbidden = client.get(
|
||||
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
|
||||
headers={'X-Username': 'missing-quality-user', 'X-Role': 'user'},
|
||||
)
|
||||
auth = {'Authorization': f'Bearer {token}'}
|
||||
created = client.post(
|
||||
'/api/admin/shipping-notice/order-extraction-quality-batches',
|
||||
json={'owner_agent_id': owner_id, 'schema_version_id': 1},
|
||||
headers=auth,
|
||||
)
|
||||
listed = client.get(
|
||||
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
|
||||
headers=auth,
|
||||
)
|
||||
|
||||
assert forbidden.status_code in {401, 403}
|
||||
assert created.status_code == 201
|
||||
created_data = parse_api_data(created.get_json())
|
||||
assert created_data['status'] == 'collecting'
|
||||
assert listed.status_code == 200
|
||||
assert parse_api_data(listed.get_json()) == []
|
||||
serialized = str(created.get_json()).lower()
|
||||
assert all(key not in serialized for key in ('document', 'quote', 'orders', 'evidence_ref', 'cell_id', 'labels'))
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID'
|
||||
else:
|
||||
raise AssertionError('auto-creation run must be rejected')
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_quality_migration.py
|
||||
|
||||
用途:验证 L7 质量批次/标签和 Runtime Binding 引用迁移可完整往返。
|
||||
用途:验证 L7 质量批次/标签迁移可完整往返。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、a71f8091a2b7 迁移。
|
||||
逻辑:构造最小父表,升级检查表/列/索引,降级确认完全移除。
|
||||
逻辑:构造最小父表,升级检查表/索引,降级确认完全移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +16,7 @@ from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_extraction_quality_migration_round_trip(monkeypatch):
|
||||
"""质量表和 Binding 外键必须可独立升级、写入并完整降级。"""
|
||||
"""质量表必须可独立升级、写入并完整降级。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a71f8091a2b7_add_order_extraction_quality_gate',
|
||||
)
|
||||
@@ -24,11 +24,6 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch):
|
||||
metadata = sa.MetaData()
|
||||
for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'agent_runtime_bindings', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('owner_agent_id', sa.Integer()),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
@@ -38,14 +33,8 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch):
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_quality_batches' in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_quality_labels' in inspector.get_table_names()
|
||||
assert 'quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_quality_batches' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_quality_labels' not in inspector.get_table_names()
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
|
||||
}
|
||||
@@ -46,42 +46,3 @@ def test_order_extraction_run_quality_migration_round_trip(monkeypatch):
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
|
||||
|
||||
def test_quality_binding_migration_round_trip(monkeypatch):
|
||||
"""Binding 与 Run 的质量批次引用必须一起升级和完整降级。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a77f8091a2c3_add_order_extraction_quality_binding',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_extraction_quality_batches', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
sa.Table(table_name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
assert 'quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns(table_name)
|
||||
}
|
||||
assert f'ix_{table_name}_quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_indexes(table_name)
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns(table_name)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,26 +13,28 @@ from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
|
||||
def test_business_review_route_transitions_unit_to_skipped_not_failed(app):
|
||||
"""模板未匹配等业务拒识使用 skipped,计划完成后由 Run 汇总为 needs_review。"""
|
||||
def test_business_review_route_transitions_unit_to_review_required_not_failed(app):
|
||||
"""模板未匹配等业务拒识使用 review_required,计划完成后由 Run 汇总为 review_required/partially_completed。"""
|
||||
with app.app_context():
|
||||
plan = SimpleNamespace(units=[])
|
||||
unit = SimpleNamespace(
|
||||
status='running', attempt_count=1, started_at=None, finished_at=None,
|
||||
result_json={'stale': True}, error_code=None, error_message=None, plan=plan,
|
||||
status='matching_profile', attempt_count=1, started_at=None, finished_at=None,
|
||||
last_activity_at=None, result_json={'stale': True}, summary_json=None,
|
||||
reason_code=None, error_code=None, error_message=None, plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='skipped',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED',
|
||||
target_status='review_required',
|
||||
error_code='profile_not_found',
|
||||
error_message='Template requires review',
|
||||
)
|
||||
|
||||
# 关键断言:业务不确定性是可复核的完成态,不能污染技术失败率。
|
||||
assert unit.status == 'skipped'
|
||||
assert unit.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
|
||||
assert unit.status == 'review_required'
|
||||
assert unit.reason_code == 'profile_not_found'
|
||||
assert unit.error_code is None
|
||||
assert plan.status == 'completed'
|
||||
|
||||
|
||||
@@ -42,16 +44,49 @@ def test_unit_transition_appends_auditable_status_event(app):
|
||||
run = SimpleNamespace(run_no='SNER-STAGE0')
|
||||
plan = SimpleNamespace(units=[], run=run)
|
||||
unit = SimpleNamespace(
|
||||
id=37, status='running', attempt_count=1, started_at=None, finished_at=None,
|
||||
result_json=None, error_code=None, error_message=None, plan=plan,
|
||||
id=37, status='matching_profile', attempt_count=1, started_at=None, finished_at=None,
|
||||
last_activity_at=None, result_json=None, summary_json=None,
|
||||
reason_code=None, error_code=None, error_message=None, plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(unit, target_status='skipped')
|
||||
transition_order_extraction_unit(unit, target_status='review_required', error_code='profile_not_found')
|
||||
db.session.commit()
|
||||
|
||||
event = ShippingAuditEvent.query.filter_by(aggregate_id='37').one()
|
||||
# 关键断言:单元业务复核状态能和 Run 关联,但不复制订单内容。
|
||||
assert event.event_type == 'order_extraction_unit_status_changed'
|
||||
assert event.run_no == 'SNER-STAGE0'
|
||||
assert event.reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
|
||||
assert event.reason_code == 'profile_not_found'
|
||||
|
||||
|
||||
def test_supplement_merge_transition_keeps_unit_on_business_path(app):
|
||||
"""正文补充合并必须走 merging_supplement -> candidate_ready,不能跳回技术态。"""
|
||||
with app.app_context():
|
||||
plan = SimpleNamespace(units=[])
|
||||
unit = SimpleNamespace(
|
||||
status='extracting', attempt_count=1, started_at=None, finished_at=None,
|
||||
last_activity_at=None, result_json=None, summary_json=None,
|
||||
reason_code=None, error_code=None, error_message=None, plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='merging_supplement',
|
||||
result={'orders': [{'po_number': '450001'}]},
|
||||
)
|
||||
assert unit.status == 'merging_supplement'
|
||||
assert unit.error_code is None
|
||||
assert plan.status == 'running'
|
||||
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='candidate_ready',
|
||||
result={'orders': [{'po_number': '450001', '_hxops_email_supplement_relation': 'po_mpn'}]},
|
||||
)
|
||||
|
||||
assert unit.status == 'candidate_ready'
|
||||
assert unit.result_json['orders'][0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
assert unit.reason_code is None
|
||||
assert plan.status == 'completed'
|
||||
@@ -0,0 +1,368 @@
|
||||
"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.jobs.handlers.shipping_order_extraction import (
|
||||
_expansion_trigger_reason_codes,
|
||||
_mark_expandable_business_gaps,
|
||||
_pending_snapshot_batches,
|
||||
_process_unit_with_retries,
|
||||
_result_requires_review,
|
||||
_should_expand_after_wave,
|
||||
_units_for_batch,
|
||||
)
|
||||
|
||||
|
||||
def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
"""深度抽取只允许在 Worker 首轮执行,且必须在读取 Unit 计划之前完成。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=1, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
|
||||
attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
plan = SimpleNamespace(id=1, unit_count=0, units=[])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
|
||||
monkeypatch.setattr(
|
||||
handler,
|
||||
'ShippingOrderExtractionRun',
|
||||
SimpleNamespace(query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
),
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler,
|
||||
'ShippingOrderExtractionUnit',
|
||||
SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
|
||||
)),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
|
||||
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', lambda _run: events.append('materialize') or plan)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
|
||||
monkeypatch.setattr(handler, '_wave_orders_for_expansion', lambda _run, *, orders: [])
|
||||
monkeypatch.setattr(handler, '_expansion_trigger_reason_codes', lambda **_kwargs: [])
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda *, run, orders: {})
|
||||
monkeypatch.setattr(handler, '_result_requires_review', lambda **_kwargs: False)
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1})
|
||||
|
||||
assert events.index('materialize') < events.index('units')
|
||||
|
||||
|
||||
def _patch_unit_transitions(monkeypatch):
|
||||
"""用轻量状态机替代 ORM transition,便于验证单元级自动重试行为。"""
|
||||
|
||||
def fake_transition(unit, *, target_status, error_code=None, error_message=None, result=None, **_kwargs):
|
||||
if target_status == 'routing':
|
||||
unit.attempt_count = int(unit.attempt_count or 0) + 1
|
||||
unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running'
|
||||
elif target_status == 'pending':
|
||||
unit.retry_status = 'pending_retry'
|
||||
elif target_status == 'failed':
|
||||
unit.retry_status = 'failed'
|
||||
unit.technical_failure_reason_code = error_code
|
||||
unit.error_code = error_code
|
||||
unit.error_message = error_message
|
||||
elif target_status == 'review_required':
|
||||
unit.retry_status = 'review_required'
|
||||
elif target_status == 'candidate_ready':
|
||||
unit.retry_status = 'succeeded'
|
||||
unit.status = target_status
|
||||
unit.result_json = result
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
fake_transition,
|
||||
)
|
||||
|
||||
|
||||
def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.commit', lambda: None)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.rollback', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_unit_progress',
|
||||
lambda *, event_code, reason_code=None, **_kwargs: event_log.append((event_code, reason_code)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
|
||||
def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch):
|
||||
"""同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
|
||||
run = SimpleNamespace(id=1, run_no='SNER-WORKER-RETRY')
|
||||
unit = SimpleNamespace(
|
||||
id=7,
|
||||
intake_id=11,
|
||||
document_id=101,
|
||||
status='pending',
|
||||
attempt_count=0,
|
||||
retry_status='not_started',
|
||||
technical_failure_reason_code=None,
|
||||
result_json=None,
|
||||
)
|
||||
job = SimpleNamespace(id=5)
|
||||
orders = [{'source_intake_no': 'SNI-1', 'primary_document_id': 101, 'header_fields': [], 'lines': []}]
|
||||
|
||||
calls = {'count': 0}
|
||||
|
||||
def fake_route(_run, *, unit):
|
||||
calls['count'] += 1
|
||||
if calls['count'] < 3:
|
||||
raise ServiceUnavailableError('layout service unavailable', code='SYSTEM.SERVICE_UNAVAILABLE')
|
||||
return SimpleNamespace(
|
||||
execution_mode='deterministic',
|
||||
orders=orders,
|
||||
decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 2},
|
||||
)
|
||||
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
|
||||
lambda *, run_id, unit_id: (run, unit),
|
||||
)
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result is orders
|
||||
assert unit.status == 'merging_supplement'
|
||||
assert unit.attempt_count == 3
|
||||
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
|
||||
|
||||
def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch):
|
||||
"""同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
|
||||
run = SimpleNamespace(id=1, run_no='SNER-WORKER-ROUTE-ATTEMPTS')
|
||||
unit = SimpleNamespace(
|
||||
id=10, intake_id=14, document_id=104, status='pending', attempt_count=0,
|
||||
retry_status='not_started', technical_failure_reason_code=None, result_json=None,
|
||||
)
|
||||
job = SimpleNamespace(id=8)
|
||||
route_attempts: list[int] = []
|
||||
calls = {'count': 0}
|
||||
|
||||
def fake_route(_run, *, unit):
|
||||
calls['count'] += 1
|
||||
return SimpleNamespace(
|
||||
execution_mode='deterministic',
|
||||
orders=[{'source_intake_no': 'SNI-ROUTE', 'primary_document_id': 104, 'header_fields': [], 'lines': []}],
|
||||
decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 1},
|
||||
)
|
||||
|
||||
def fake_validate(_run, *, unit, orders):
|
||||
if calls['count'] == 1:
|
||||
raise ServiceUnavailableError('temporary validation failure', code='SYSTEM.SERVICE_UNAVAILABLE')
|
||||
return orders
|
||||
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.route_deterministic_unit', fake_route)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', fake_validate)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
|
||||
lambda **kwargs: route_attempts.append(kwargs['attempt_no']),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
|
||||
lambda *, run_id, unit_id: (run, unit),
|
||||
)
|
||||
|
||||
assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
assert route_attempts == [1, 2]
|
||||
|
||||
|
||||
def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch):
|
||||
"""自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
|
||||
run = SimpleNamespace(id=1, run_no='SNER-WORKER-FAILED')
|
||||
unit = SimpleNamespace(
|
||||
id=8,
|
||||
intake_id=12,
|
||||
document_id=102,
|
||||
status='pending',
|
||||
attempt_count=0,
|
||||
retry_status='not_started',
|
||||
technical_failure_reason_code=None,
|
||||
result_json=None,
|
||||
)
|
||||
job = SimpleNamespace(id=6)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit',
|
||||
lambda _run, *, unit: (_ for _ in ()).throw(ServiceUnavailableError('ocr timeout', code='OCR.TIMEOUT')),
|
||||
)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
|
||||
lambda *, run_id, unit_id: (run, unit),
|
||||
)
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result is None
|
||||
assert unit.status == 'failed'
|
||||
assert unit.attempt_count == 3
|
||||
assert unit.technical_failure_reason_code == 'OCR.TIMEOUT'
|
||||
assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 2
|
||||
assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 3
|
||||
|
||||
|
||||
def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch):
|
||||
"""业务/校验类异常不得误走技术自动重试。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
|
||||
run = SimpleNamespace(id=1, run_no='SNER-WORKER-NONRETRY')
|
||||
unit = SimpleNamespace(
|
||||
id=9,
|
||||
intake_id=13,
|
||||
document_id=103,
|
||||
status='pending',
|
||||
attempt_count=0,
|
||||
retry_status='not_started',
|
||||
technical_failure_reason_code=None,
|
||||
result_json=None,
|
||||
)
|
||||
job = SimpleNamespace(id=7)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit',
|
||||
lambda _run, *, unit: (_ for _ in ()).throw(
|
||||
ValidationError('snapshot stale', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.validate_unit_orders', lambda _run, *, unit, orders: orders)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
|
||||
lambda *, run_id, unit_id: (run, unit),
|
||||
)
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result is None
|
||||
assert unit.status == 'failed'
|
||||
assert unit.attempt_count == 1
|
||||
assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'
|
||||
assert ('technical_retrying', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE') not in event_log
|
||||
assert event_log.count(('technical_failed', 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE')) == 1
|
||||
|
||||
|
||||
def test_should_expand_after_wave_when_current_wave_needs_more_evidence():
|
||||
"""只有可补证的 review/业务缺口才扩批;纯技术失败不应直接消耗下一轮预算。"""
|
||||
assert _should_expand_after_wave(
|
||||
wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')],
|
||||
wave_orders=[],
|
||||
) is True
|
||||
assert _should_expand_after_wave(
|
||||
wave_units=[SimpleNamespace(status='failed', reason_code='OCR.TIMEOUT')],
|
||||
wave_orders=[{'id': 1}],
|
||||
) is False
|
||||
|
||||
|
||||
def test_auto_freeze_blocked_task_requires_run_review():
|
||||
"""自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。"""
|
||||
assert _result_requires_review(
|
||||
units=[SimpleNamespace(status='candidate_ready')],
|
||||
result={'pending_count': 0, 'auto_freeze': {'blocked_tasks': [{'task_no': 'ST-1'}]}},
|
||||
) is True
|
||||
assert _should_expand_after_wave(
|
||||
wave_units=[SimpleNamespace(status='candidate_ready', reason_code=None)],
|
||||
wave_orders=[{'_hxops_expand_for_missing_reservation': True}],
|
||||
) is True
|
||||
assert _should_expand_after_wave(
|
||||
wave_units=[SimpleNamespace(status='merging_supplement', reason_code=None)],
|
||||
wave_orders=[{'id': 1}],
|
||||
) is False
|
||||
|
||||
|
||||
def test_expansion_trigger_reason_codes_merge_review_and_order_gaps():
|
||||
"""扩批原因应同时汇总 review reason、正文冲突和缺 Reservation。"""
|
||||
codes = _expansion_trigger_reason_codes(
|
||||
wave_units=[SimpleNamespace(status='review_required', reason_code='required_field_missing')],
|
||||
wave_orders=[{
|
||||
'_hxops_expand_for_missing_reservation': True,
|
||||
'conflicts': [{'reason': 'supplement_relation_ambiguous'}],
|
||||
}],
|
||||
)
|
||||
|
||||
assert codes == [
|
||||
'missing_reservation_id',
|
||||
'required_field_missing',
|
||||
'supplement_relation_ambiguous',
|
||||
]
|
||||
|
||||
|
||||
def test_mark_expandable_business_gaps_flags_missing_reservation_from_schema():
|
||||
"""缺 Reservation 的订单应被标记为可通过下一附件补证。"""
|
||||
run = SimpleNamespace(
|
||||
input_snapshot_json={
|
||||
'schema': {
|
||||
'definition': {
|
||||
'fields': [
|
||||
{'field_code': 'reservation_id', 'field_id': 'reservation-id'},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
orders = [{
|
||||
'lines': [
|
||||
{'fields': []},
|
||||
{'fields': [{'field_id': 'reservation-id', 'observations': [{'value': 'RSV001'}]}]},
|
||||
],
|
||||
}]
|
||||
|
||||
marked = _mark_expandable_business_gaps(run, orders=orders)
|
||||
|
||||
assert marked[0]['_hxops_expand_for_missing_reservation'] is True
|
||||
|
||||
|
||||
def test_pending_snapshot_batches_ignore_already_activated_units():
|
||||
"""冻结计划里已有的未来批次,激活后不应重复出现在待扩批列表里。"""
|
||||
run = SimpleNamespace(
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'planned_selection_batch': 2},
|
||||
{'planned_selection_batch': 3},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
plan = SimpleNamespace(units=[
|
||||
SimpleNamespace(selection_batch=1),
|
||||
SimpleNamespace(selection_batch=2),
|
||||
])
|
||||
|
||||
assert _pending_snapshot_batches(run, plan) == [3]
|
||||
assert [unit.selection_batch for unit in _units_for_batch(plan, selection_batch=1)] == [1]
|
||||
@@ -0,0 +1,42 @@
|
||||
"""订单抽取工作台投影的纯单元测试。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state
|
||||
|
||||
|
||||
def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
"""Run 级事件也应进入聊天卡 currentActivity,而不是只支持单元级事件。"""
|
||||
run = SimpleNamespace(
|
||||
status='processing',
|
||||
extraction_plan=SimpleNamespace(units=[]),
|
||||
input_snapshot_json={},
|
||||
error_code=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
|
||||
lambda _run: (
|
||||
{},
|
||||
SimpleNamespace(
|
||||
unit_id=None,
|
||||
document_id=None,
|
||||
event_code='expansion_wave_started',
|
||||
reason_code='budget_initial_limit',
|
||||
summary_json={'selection_batch': 2, 'reason_codes': ['required_field_missing']},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
result = serialize_workspace_run_chat_state(run)
|
||||
|
||||
assert result['currentActivity'] == {
|
||||
'unitId': 0,
|
||||
'fileName': None,
|
||||
'eventCode': 'expansion_wave_started',
|
||||
'selectionBatch': 2,
|
||||
'reasonCodes': ['budget_initial_limit', 'required_field_missing'],
|
||||
}
|
||||
assert result['status'] == 'processing'
|
||||
@@ -88,3 +88,22 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
|
||||
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
|
||||
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
|
||||
|
||||
|
||||
def test_profile_matcher_allows_multiple_template_regions_on_one_detected_table():
|
||||
"""续页未被检测器拆表时,页级坐标证据仍可匹配多区域模板。"""
|
||||
profile = _profile('PO_A')
|
||||
profile['definition']['table_regions'][0]['region']['y1'] = .5
|
||||
profile['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = .5
|
||||
profile['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = .5
|
||||
profile['definition']['table_regions'].append({
|
||||
'region_id': 'lines_page_2', 'page_scope': 'exact_page', 'page_no': 2,
|
||||
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [{'layout_id': 'header_page_2', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}}],
|
||||
})
|
||||
layout = _layout()
|
||||
layout['coordinate_evidence']['page_glyphs'] = {'1': layout['coordinate_evidence']['tables']['table-1']}
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
Reference in new issue
Block a user