feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -6,7 +6,7 @@ tests/services/admin/test_permission_service.py
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.admin import permission_service
|
||||
|
||||
@@ -50,6 +50,31 @@ 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')
|
||||
@@ -77,3 +102,25 @@ 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
|
||||
@@ -3,8 +3,11 @@ tests/services/admin/test_user_service.py
|
||||
|
||||
用途:user_service 管理端用户 CRUD 单元测试。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import user_service
|
||||
|
||||
|
||||
@@ -52,3 +55,22 @@ def test_list_users_sort_by_username_and_department(app):
|
||||
|
||||
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
|
||||
@@ -3,8 +3,11 @@ tests/services/admin/test_wecom_admin_service.py
|
||||
|
||||
用途:wecom_admin_service 绑定统计单元测试。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.admin import wecom_admin_service
|
||||
|
||||
|
||||
@@ -19,3 +22,27 @@ def test_binding_stats(app):
|
||||
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
|
||||
@@ -19,6 +19,7 @@ from app.services.shipping_notice.order_schema import service as order_schema_se
|
||||
|
||||
def _published_header_field(
|
||||
*, code: str = 'sender_email', available: bool = True, option_key: str | None = 'from_email',
|
||||
scope: str = 'header', field_category: str | None = None,
|
||||
) -> ShippingOrderField:
|
||||
"""创建已发布 Header 字段;available 决定是否能进入客户识别目录。"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
@@ -27,15 +28,15 @@ def _published_header_field(
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(
|
||||
schema_id=schema.id, field_code=code, scope='header', value_type='string',
|
||||
field_category='general_context' if option_key else 'order_header',
|
||||
schema_id=schema.id, field_code=code, scope=scope, value_type='string',
|
||||
field_category=field_category or ('general_context' if option_key else 'order_header'),
|
||||
collection_mode='deterministic_context' if option_key else 'llm_extraction',
|
||||
)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
config = {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': code,
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'scope': scope, 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': available, 'normalizer_key': 'lowercase_trim',
|
||||
}
|
||||
if option_key:
|
||||
@@ -78,18 +79,74 @@ def test_catalog_only_lists_published_identity_enabled_header_fields(app):
|
||||
assert 'source_adapters' not in catalog['catalog']
|
||||
|
||||
|
||||
def test_definition_uses_context_field_only_and_derives_automation(app):
|
||||
"""定义只保存 context_field_id;邮箱字段自动化上限由发布字段来源推导。"""
|
||||
def test_definition_uses_context_field_only_and_defaults_to_manual_review(app):
|
||||
"""定义只保存 context_field_id;未显式授权时任何字段都默认人工确认。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
created = _definition(field)
|
||||
|
||||
assert created['context_field_id'] == field.id
|
||||
assert created['context_field']['field_code'] == 'sender_email'
|
||||
assert created['max_automation'] == 'conditional'
|
||||
assert created['max_automation'] == 'none'
|
||||
assert not {'source_adapter_key', 'source_selector', 'order_field_id', 'attribute_key'} & set(created)
|
||||
|
||||
|
||||
def test_order_header_field_can_be_identity_evidence_without_automatic_confirmation(app):
|
||||
"""订单信息 Header 可进入客户识别,但不能单独获得自动确认能力。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
|
||||
created = _definition(field)
|
||||
catalog = service.list_definitions()
|
||||
|
||||
assert created['context_field_id'] == field.id
|
||||
assert created['max_automation'] == 'none'
|
||||
assert [item['field_id'] for item in catalog['context_fields']] == [field.id]
|
||||
|
||||
|
||||
def test_order_header_automation_can_be_explicitly_authorized(app):
|
||||
"""订单 Header 默认人工确认,但管理员可显式授权受控自动确认。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
|
||||
created = _definition(field, automation='conditional')
|
||||
|
||||
assert created['max_automation'] == 'conditional'
|
||||
|
||||
|
||||
def test_order_line_field_cannot_be_enabled_for_customer_identity(app):
|
||||
"""货品明细即使发布快照误标为可识别,也不能进入目录或建立识别定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(
|
||||
code='customer_part_number', option_key=None, scope='line', field_category='order_line',
|
||||
)
|
||||
|
||||
assert service.list_definitions()['context_fields'] == []
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_definition(field)
|
||||
assert caught.value.code == 'SHIPPING.IDENTITY_ORDER_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_published_rule_set_contains_saved_order_header_definition(app):
|
||||
"""保存规则集勾选后发布,客户证据目录必须读取同一份已发布 Header 定义。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field(code='bill_to_customer', option_key=None)
|
||||
definition = _definition(field)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
|
||||
published = service.publish_rule_set(
|
||||
draft['id'], expected_lock_version=saved['lock_version'], actor_id=1,
|
||||
)
|
||||
|
||||
published_ids = [item['id'] for item in published['definition']['definitions']]
|
||||
evidence_catalog = service.list_published_evidence_definitions(target_type='customer')
|
||||
assert published_ids == [definition['id']]
|
||||
assert [item['id'] for item in evidence_catalog['definitions']] == [definition['id']]
|
||||
|
||||
|
||||
def test_unpublished_or_identity_disabled_field_is_rejected(app):
|
||||
"""未开放客户识别的字段不能通过伪造 payload 建立定义。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -40,6 +40,74 @@ 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,6 +20,7 @@ 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,
|
||||
@@ -101,6 +102,13 @@ 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,6 +35,7 @@ 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,
|
||||
@@ -51,6 +52,7 @@ 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():
|
||||
@@ -58,6 +60,7 @@ 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},
|
||||
@@ -74,6 +77,7 @@ 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():
|
||||
|
||||
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from unittest.mock import patch
|
||||
from datetime import datetime, timedelta
|
||||
@@ -21,20 +23,28 @@ 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.handlers.shipping_order_extraction import (
|
||||
_execute_dify_unit_with_retry,
|
||||
run_shipping_order_extraction,
|
||||
)
|
||||
from app.jobs.queue import claim_next_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun, User,
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument,
|
||||
ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding
|
||||
from app.services.admin.agent_service import update_agent_permissions
|
||||
from app.services.admin.agent_service import list_agents
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
parse_order_extraction_workflow_result, validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
sync_order_extraction_run_after_job_recovery,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
@@ -63,6 +73,59 @@ def test_binding_rejects_non_internal_or_non_workflow_provider(app):
|
||||
assert caught.value.code == 'AGENT.RUNTIME_PROVIDER_INVALID'
|
||||
|
||||
|
||||
def test_binding_catalog_exposes_internal_executor_role_constraint(app):
|
||||
"""订单抽取能力目录必须明确要求 internal_executor,避免仅靠界面约定。"""
|
||||
with app.app_context():
|
||||
owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid')
|
||||
provider = Agent(
|
||||
name='Workflow Provider', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=owner.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id,
|
||||
enabled=True,
|
||||
config={},
|
||||
)
|
||||
assert binding.provider_agent.exposure_mode == 'internal'
|
||||
|
||||
|
||||
def test_internal_executor_cannot_receive_user_permissions(app):
|
||||
"""内部执行器只能被运行时绑定,不能进入用户授权关系。"""
|
||||
with app.app_context():
|
||||
user = User(username='internal-permission-user', email='internal-permission@example.com', password_hash='x')
|
||||
provider = Agent(
|
||||
name='Internal Workflow', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([user, provider])
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
update_agent_permissions(provider.id, [user.id])
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN'
|
||||
|
||||
|
||||
def test_admin_agent_list_scopes_separate_applications_and_executors(app):
|
||||
"""管理页签后端列表必须按 workspace/internal 隔离。"""
|
||||
with app.app_context():
|
||||
application = Agent(name='Workspace App', exposure_mode='workspace', agent_code='generic')
|
||||
executor = Agent(
|
||||
name='Internal Executor', exposure_mode='internal',
|
||||
runtime_provider='dify', dify_app_type='workflow', dify_app_id='scope-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1',
|
||||
)
|
||||
db.session.add_all([application, executor])
|
||||
db.session.commit()
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='applications')} == {'workspace'}
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='executors')} == {'internal'}
|
||||
|
||||
|
||||
def test_run_creation_requires_explicit_binding(app):
|
||||
"""删除显式绑定后创建 Run 必须阻断,且不得产生 Run 或 Job。"""
|
||||
with app.app_context():
|
||||
@@ -116,6 +179,18 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.get_json()['data']['provider_agent_id'] == provider_id
|
||||
assert saved.get_json()['data']['config'] == {
|
||||
'timeout_seconds': 600,
|
||||
'max_attempts': 2,
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5,
|
||||
'circuit_cooldown_seconds': 60,
|
||||
'auto_create_enabled': False,
|
||||
}
|
||||
assert 'dify_api_key' not in saved.get_json()['data']
|
||||
|
||||
listed = client.get('/api/agents', headers=auth)
|
||||
@@ -361,38 +436,463 @@ def test_workflow_request_errors_are_classified(app, upstream_error, expected_co
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
side_effect=upstream_error,
|
||||
), pytest.raises(Exception) as caught:
|
||||
execute_order_extraction_workflow(run=run, provider=provider, timeout_seconds=30)
|
||||
execute_order_extraction_workflow(run=run, unit=unit, provider=provider, timeout_seconds=30)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == expected_code
|
||||
assert getattr(caught.value, 'retryable', False) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'workflow_result',
|
||||
[
|
||||
None,
|
||||
{'status': 'failed', 'error': 'inventory_source_hint must not be a line number'},
|
||||
{'status': 'succeeded', 'outputs': {'orders': 'not-json'}},
|
||||
],
|
||||
)
|
||||
def test_workflow_terminal_or_output_contract_errors_are_not_retryable(workflow_result):
|
||||
"""Dify 已返回终态的画布/输出错误不得触发 Unit 重试或 Provider 熔断。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_order_extraction_workflow_result(workflow_result)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert caught.value.retryable is False
|
||||
|
||||
|
||||
def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
"""Dify 已返回画布校验失败时,同一 Unit 不重复调用且不累计 Provider 熔断失败。"""
|
||||
error = ValidationError(
|
||||
'inventory_source_hint must not be a line number',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
run_snapshot = {
|
||||
'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1,
|
||||
'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {},
|
||||
}
|
||||
unit_snapshot = {
|
||||
'id': 1, 'intake_id': 1, 'document_id': 1,
|
||||
'document_type': 'attachment', 'unit_type': 'document_extraction',
|
||||
}
|
||||
provider_snapshot = {'id': 998877, 'api_base_url': 'http://dify.example/v1', 'dify_api_key': 'key'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=error,
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_provider_failure',
|
||||
) as record_failure, pytest.raises(ValidationError) as caught:
|
||||
_execute_dify_unit_with_retry(
|
||||
app=app, run_snapshot=run_snapshot, unit_snapshot=unit_snapshot,
|
||||
provider_snapshot=provider_snapshot, timeout_seconds=30,
|
||||
max_attempts=3, backoff_ms=1, job_id=1, job_attempt=1,
|
||||
provider_max_concurrency=1, circuit_failure_threshold=2,
|
||||
circuit_cooldown_seconds=60,
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert execute.call_count == 1
|
||||
record_failure.assert_not_called()
|
||||
|
||||
|
||||
def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
"""Workflow 分离冻结 LLM 契约与只读上下文,完整定义和 documents 均不得旁路泄露。"""
|
||||
"""Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
inputs = build_order_extraction_workflow_inputs(run)
|
||||
schema = json.loads(inputs['schema_contract'])
|
||||
documents = json.loads(inputs['documents'])
|
||||
readonly_context = json.loads(inputs['readonly_context'])
|
||||
unit = run.extraction_plan.units[0]
|
||||
inputs = build_order_extraction_workflow_inputs(run, unit=unit)
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
schema = manifest['extraction_contract']
|
||||
documents = manifest['documents']
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert schema == run.input_snapshot_json['schema']['extraction_contract']
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['unit']['document_id'] == unit.document_id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert 'definition' not in schema
|
||||
assert schema['fields'][0]['field_id'] == 'qty-id'
|
||||
assert 'deterministic_context' not in documents[0]
|
||||
assert 'sales-' not in inputs['documents'].lower()
|
||||
assert len(documents) == 1
|
||||
assert set(documents[0]) == {'intake_id', 'intake_no', 'document'}
|
||||
assert documents[0]['document']['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(documents).lower()
|
||||
assert readonly_context == []
|
||||
assert set(inputs) == {
|
||||
'run_no', 'input_snapshot_hash', 'schema_contract', 'documents', 'readonly_context',
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
|
||||
|
||||
def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
"""Workflow 调用边界只能发送 execution_manifest,禁止回退到旧五变量契约。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
return_value={'status': 'succeeded', 'outputs': {'orders': []}, 'workflow_run_id': 'wf-manifest'},
|
||||
) as mocked_run:
|
||||
orders, metadata = execute_order_extraction_workflow(
|
||||
run=run, unit=unit, provider=provider, timeout_seconds=30,
|
||||
)
|
||||
|
||||
inputs = mocked_run.call_args.kwargs['inputs']
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert orders == []
|
||||
assert metadata['workflow_run_id'] == 'wf-manifest'
|
||||
|
||||
|
||||
def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
"""冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'aliases': ['Qty'], 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]}
|
||||
document.extracted_text = 'Part Number\tQty\nPN-001\t3'
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='deterministic-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
) as submit:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
unit = finished.extraction_plan.units[0]
|
||||
assert execute.call_count == 0
|
||||
assert submit.call_args.kwargs['orders'][0]['lines'][0]['fields']
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'deterministic'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1
|
||||
|
||||
|
||||
def test_unit_manifest_never_contains_sibling_document(app):
|
||||
"""单元级模型输入只能包含当前冻结 Document,禁止重新拼成整封邮件。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='COMPACT')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='second.pdf',
|
||||
filename='second.pdf',
|
||||
content_hash='d' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='SIBLING-SECRET-CONTENT',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=unit,
|
||||
)['execution_manifest'])
|
||||
|
||||
assert len(manifest['documents']) == 1
|
||||
assert manifest['documents'][0]['document']['document_id'] == first.id
|
||||
assert 'SIBLING-SECRET-CONTENT' not in repr(manifest)
|
||||
|
||||
|
||||
def test_unit_result_cannot_reference_sibling_document(app):
|
||||
"""即使模型猜到兄弟 Document ID,单元边界也必须在局部结果落库前拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='UNIT-SCOPE')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='sibling.pdf',
|
||||
content_hash='e' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Sibling evidence',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
orders = [{
|
||||
'source_intake_no': intake.intake_no,
|
||||
'primary_document_id': first.id,
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{
|
||||
'field_id': 'qty-id',
|
||||
'observations': [{'value': 1, 'document_id': second.id, 'quote': 'Sibling evidence'}],
|
||||
}]}],
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_unit_orders(run, unit=unit, orders=orders)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
|
||||
def test_worker_runs_dify_units_with_frozen_concurrency_limit(app):
|
||||
"""多个模型单元应实际并行,且同时在途数量不得超过 Run 冻结配置。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _first = _seed_run_input(suffix='PARALLEL')
|
||||
for index in range(2):
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment',
|
||||
attachment_key=f'parallel-{index}.pdf', content_hash=str(index + 1) * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
extracted_text=f'Unstructured document {index}',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='parallel-worker',
|
||||
)
|
||||
lock = threading.Lock()
|
||||
active = 0
|
||||
peak = 0
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
nonlocal active, peak
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
time.sleep(0.08)
|
||||
with lock:
|
||||
active -= 1
|
||||
return [], {'workflow_run_id': f'wf-{unit.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert peak == 2
|
||||
assert finished.provider_result_json['workflow']['unit_concurrency'] == 2
|
||||
assert finished.provider_result_json['workflow']['dify_unit_count'] == 3
|
||||
assert all(unit.status == 'succeeded' for unit in finished.extraction_plan.units)
|
||||
|
||||
|
||||
def test_worker_retries_only_failed_unit_locally(app):
|
||||
"""单元首次网络失败后只重试该单元,并保存 attempt/latency 指标。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCAL-RETRY')
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='local-retry-worker',
|
||||
)
|
||||
calls = 0
|
||||
|
||||
def execute(**_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
raise requests.exceptions.ReadTimeout('temporary slow unit')
|
||||
return [], {'workflow_run_id': 'wf-local-retry', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderExtractionRun, run.id).extraction_plan.units[0]
|
||||
assert calls == 2
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.attempt_count == 2
|
||||
assert unit.result_json['workflow']['attempts'] == 2
|
||||
assert unit.result_json['workflow']['latency_ms'] >= 100
|
||||
|
||||
|
||||
def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app):
|
||||
"""一个单元永久失败时,成功单元仍提交,Run 以 needs_review 收口。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='PARTIAL')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='partial-2.pdf',
|
||||
content_hash='f' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Second unstructured document',
|
||||
)
|
||||
db.session.add(second)
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='partial-worker',
|
||||
)
|
||||
submitted = {}
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
if unit.document_id == second.id:
|
||||
raise requests.exceptions.ReadTimeout('permanent unit timeout')
|
||||
return [], {'workflow_run_id': f'wf-{first.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
def submit(*, orders, **_kwargs):
|
||||
submitted['orders'] = orders
|
||||
return {
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
side_effect=submit,
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
statuses = {unit.document_id: unit.status for unit in finished.extraction_plan.units}
|
||||
assert submitted['orders'] == []
|
||||
assert statuses[first.id] == 'succeeded'
|
||||
assert statuses[second.id] == 'failed'
|
||||
assert finished.status == 'needs_review'
|
||||
assert finished.result_json['failed_unit_count'] == 1
|
||||
|
||||
|
||||
def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app):
|
||||
"""需要模型的文档数超过 Run 冻结预算时必须在发请求前阻断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='BUDGET')
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='budget-2.pdf',
|
||||
content_hash='9' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Another unstructured document',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
'max_model_units': 1, 'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5, 'circuit_cooldown_seconds': 60,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='budget-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
failed = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert failed.status == 'failed'
|
||||
assert failed.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'orders_output',
|
||||
[
|
||||
[{'classification': 'shipping_request'}],
|
||||
json.dumps([{'classification': 'shipping_request'}]),
|
||||
json.dumps(json.dumps([{'classification': 'shipping_request'}])),
|
||||
json.dumps({'orders': [{'classification': 'shipping_request'}]}),
|
||||
{'orders': json.dumps([{'classification': 'shipping_request'}])},
|
||||
],
|
||||
)
|
||||
def test_workflow_result_accepts_dify_orders_serialization_variants(orders_output):
|
||||
"""Dify End 的数组和最多两层 String 包装均须还原为订单数组。"""
|
||||
assert parse_order_extraction_workflow_result({
|
||||
'status': 'succeeded', 'outputs': {'orders': orders_output},
|
||||
}) == [{'classification': 'shipping_request'}]
|
||||
|
||||
|
||||
def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
@@ -414,7 +914,10 @@ def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
intake.structured_result_json = {'email': {'from': 'changed@later.example'}}
|
||||
db.session.commit()
|
||||
|
||||
readonly_context = json.loads(build_order_extraction_workflow_inputs(run)['readonly_context'])
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert readonly_context[0]['fields'][0]['value'] == 'frozen@example.com'
|
||||
assert 'changed@later.example' not in repr(readonly_context)
|
||||
@@ -465,6 +968,48 @@ def test_worker_recovers_persisted_run_facts_without_duplicate_dify(app):
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_manual_retry_reuses_cached_provider_result_without_duplicate_dify(app):
|
||||
"""失败卡片手工重试若已有 Provider 成功结果,只重跑 HXOPS 落库阶段。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='MANUAL-RETRY-CACHE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
original_job = db.session.get(Job, run.current_job_id)
|
||||
run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-manual-cache'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='persisting_result')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='database temporarily failed')
|
||||
original_job.status = 'failed'
|
||||
db.session.commit()
|
||||
|
||||
retried, reused = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
assert reused is False
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='manual-retry-worker',
|
||||
)
|
||||
assert job.id == retried.current_job_id
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None,
|
||||
'created_count': 0,
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed'
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_worker_recovers_consumed_empty_result_without_duplicate_dify(app):
|
||||
"""空订单/非发货结果已消费 Intake 后,重试应补 submission 并完成 Run。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -85,6 +85,43 @@ def test_workflow_streaming_normal_finished(monkeypatch):
|
||||
assert result["_workflow_retry_count"] == 0
|
||||
|
||||
|
||||
def test_workflow_streaming_observer_normalizes_node_events_and_isolates_failure(monkeypatch):
|
||||
"""节点事件应脱敏传给观察器;观察器抛错不能阻断 Workflow 结果。"""
|
||||
lines = _sse_lines(
|
||||
{"event": "workflow_started", "data": {"workflow_run_id": "wf-observe"}},
|
||||
{
|
||||
"event": "node_started",
|
||||
"data": {
|
||||
"workflow_run_id": "wf-observe",
|
||||
"node_execution_id": "node-exec-1",
|
||||
"node_data": {"type": "llm", "title": "Extract orders"},
|
||||
"inputs": {"secret": "must not be forwarded"},
|
||||
},
|
||||
},
|
||||
{"event": "workflow_finished", "data": {"status": "succeeded", "workflow_run_id": "wf-observe"}},
|
||||
)
|
||||
_mock_stream_response(monkeypatch, lines=lines)
|
||||
observed = []
|
||||
|
||||
def _observer(event):
|
||||
observed.append(event)
|
||||
if event["event_type"] == "node_started":
|
||||
raise RuntimeError("diagnostics unavailable")
|
||||
|
||||
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"}, event_observer=_observer)
|
||||
|
||||
assert result["status"] == "succeeded"
|
||||
node_event = next(event for event in observed if event["event_type"] == "node_started")
|
||||
assert node_event == {
|
||||
"event_type": "node_started",
|
||||
"workflow_run_id": "wf-observe",
|
||||
"node_execution_id": "node-exec-1",
|
||||
"node_type": "llm",
|
||||
"node_title": "Extract orders",
|
||||
"event_status": None,
|
||||
}
|
||||
|
||||
|
||||
def test_workflow_streaming_read_timeout_polls_success(monkeypatch):
|
||||
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-poll"}})
|
||||
_mock_stream_response(
|
||||
|
||||
@@ -103,6 +103,98 @@ def test_worker_keeps_same_profile_sources_in_one_session_group():
|
||||
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_US_B')]] == ['DBS_CMH']
|
||||
|
||||
|
||||
def test_worker_opens_clean_page_without_discarding_shared_login_context():
|
||||
"""批量第二站必须隔离上一站报表页,但继续使用同一浏览器登录上下文。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
closed: list[str] = []
|
||||
|
||||
class _PreviousPage:
|
||||
def close(self) -> None:
|
||||
closed.append('previous')
|
||||
|
||||
class _Context:
|
||||
def new_page(self) -> str:
|
||||
return 'fresh-page'
|
||||
|
||||
assert worker._open_clean_batch_page(_Context(), _PreviousPage()) == 'fresh-page'
|
||||
assert closed == ['previous']
|
||||
|
||||
|
||||
def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch):
|
||||
"""登录后空白授权页只刷新一次,随后回 Portal 时立即结束 SSO 等待。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
events: list[str] = []
|
||||
clock = {'value': 0.0}
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
|
||||
def title(self) -> str:
|
||||
return ''
|
||||
|
||||
def reload(self, **_kwargs) -> None:
|
||||
events.append('reload')
|
||||
self.url = 'https://s360.dbschenker.com/main/portal'
|
||||
|
||||
def monotonic() -> float:
|
||||
clock['value'] += 3.0
|
||||
return clock['value']
|
||||
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_report_debug_event', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_has_dsv_report_nav_usable', lambda page: 's360.dbschenker.com' in page.url)
|
||||
monkeypatch.setattr(session, '_wait_for_visible_selector', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_is_dsv_on_portal_home', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_has_dsv_portal_shell', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'is_dsv_blank_auth_transition', lambda _page: True)
|
||||
monkeypatch.setattr(dsv_auth, 'has_dsv_password_upgrade_prompt', lambda *_args, **_kwargs: False)
|
||||
|
||||
assert session._wait_for_dsv_app_after_login(_Page(), timeout_ms=1_000) is True
|
||||
# 关键断言:空白授权页只允许一次受控刷新,避免对认证服务形成循环压力。
|
||||
assert events == ['reload']
|
||||
|
||||
|
||||
def test_dsv_sso_return_timeout_is_explicit(monkeypatch):
|
||||
"""认证页持续不回 Portal 时,必须报 SSO 回跳超时而非笼统的测试超时。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
|
||||
def title(self) -> str:
|
||||
return ''
|
||||
|
||||
def reload(self, **_kwargs) -> None:
|
||||
pass
|
||||
|
||||
ticks = iter([0.0, 0.0, 0.0, 0.0, 0.0, 31.0, 31.0, 31.0])
|
||||
|
||||
def monotonic() -> float:
|
||||
return next(ticks)
|
||||
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_report_debug_event', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_has_dsv_report_nav_usable', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_wait_for_visible_selector', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(session, '_is_dsv_on_portal_home', lambda _page: False)
|
||||
monkeypatch.setattr(session, '_has_dsv_portal_shell', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'is_dsv_blank_auth_transition', lambda _page: False)
|
||||
monkeypatch.setattr(dsv_auth, 'has_dsv_password_upgrade_prompt', lambda *_args, **_kwargs: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match='SSO authorization return timed out'):
|
||||
session._wait_for_dsv_app_after_login(_Page(), timeout_ms=1_000)
|
||||
|
||||
|
||||
def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
"""worker 解密 Profile 密文后必须在退出执行范围时恢复原有环境。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
用途:验证内部执行器不会通过用户列表、详情、授权序列化或统一访问策略暴露。
|
||||
依赖:通用 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'
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
用途:验证内部执行器用户侧历史关系清理迁移的数据边界与幂等性。
|
||||
依赖: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'
|
||||
|
||||
@@ -486,6 +486,32 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
|
||||
|
||||
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
||||
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
||||
second_model = db.session.get(ShippingInventorySource, second['id'])
|
||||
second_model.rpa_profile_id = first['rpa_profile_id']
|
||||
second_model.config_version += 1
|
||||
db.session.commit()
|
||||
seed = _complete_test_run(first, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
|
||||
queued_run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=second['id']).one()
|
||||
queued_run.created_at = datetime.utcnow() - timedelta(seconds=15)
|
||||
db.session.commit()
|
||||
|
||||
recovered = inventory_configuration_test.get_validation_batch(batch['id'])
|
||||
# 关键断言:第二站可等待同组第一站完成,20 秒总窗口内不应被单站 10 秒误判。
|
||||
assert next(run for run in recovered['runs'] if run['inventory_source_id'] == second['id'])['status'] == 'awaiting_rpa'
|
||||
|
||||
|
||||
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
|
||||
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_merge.py
|
||||
|
||||
用途:验证跨文档订单保守合并、证据保留与错误拆分边界。
|
||||
依赖:order_extraction_merge、冻结 Schema 稳定字段 ID。
|
||||
逻辑:PO 或强行身份可合并;弱身份不得合并;冲突 Observation 全量保留给后续裁决。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
|
||||
|
||||
DEFINITION = {'fields': [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number'},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number'},
|
||||
{'field_id': 'res-id', 'field_code': 'reservation_id'},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty'},
|
||||
]}
|
||||
|
||||
|
||||
def _field(field_id, value, document_id):
|
||||
return {'field_id': field_id, 'observations': [{
|
||||
'value': value, 'document_id': document_id, 'quote': str(value), 'confidence': 0.9,
|
||||
}]}
|
||||
|
||||
|
||||
def _order(document_id, *, po='PO-1', part='PN-1', reservation='R-1', qty=1):
|
||||
return {
|
||||
'source_intake_no': 'SNI-1', 'primary_document_id': document_id,
|
||||
'header_fields': [_field('po-id', po, document_id)] if po else [],
|
||||
'lines': [{'fields': [
|
||||
_field('part-id', part, document_id), _field('res-id', reservation, document_id),
|
||||
_field('qty-id', qty, document_id),
|
||||
]}],
|
||||
}
|
||||
|
||||
|
||||
def test_same_po_merges_observations_and_preserves_conflicting_values():
|
||||
"""同一 PO 合并后 Qty 冲突证据必须同时存在,交由动态字段裁决阻断。"""
|
||||
merged = merge_unit_orders(
|
||||
orders=[_order(1, qty=1), _order(2, qty=2)], schema_definition=DEFINITION,
|
||||
)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert merged[0]['source_document_ids'] == [1, 2]
|
||||
qty = next(item for item in merged[0]['lines'][0]['fields'] if item['field_id'] == 'qty-id')
|
||||
assert {item['value'] for item in qty['observations']} == {1, 2}
|
||||
|
||||
|
||||
def test_part_number_without_same_reservation_does_not_merge_without_po():
|
||||
"""只有料号相同属于弱身份,Reservation 不同且无 PO 时必须保持两个订单。"""
|
||||
merged = merge_unit_orders(
|
||||
orders=[
|
||||
_order(1, po='', reservation='R-1'),
|
||||
_order(2, po='', reservation='R-2'),
|
||||
],
|
||||
schema_definition=DEFINITION,
|
||||
)
|
||||
|
||||
assert len(merged) == 2
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_plan_migration.py
|
||||
|
||||
用途:隔离验证抽取计划与文档单元迁移可完整 upgrade/downgrade。
|
||||
依赖:Alembic Operations、SQLAlchemy 内存数据库、a65d6e7f8091 增量迁移。
|
||||
逻辑:构造最小前置外键表,检查表/约束/索引后回滚且无残留。
|
||||
"""
|
||||
|
||||
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('shipping_order_extraction_runs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_intakes', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_documents', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.UniqueConstraint('id', 'intake_id'),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_plan_migration_round_trip():
|
||||
"""迁移应建立计划/单元唯一性和状态结构,并可完整回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a65d6e7f8091_add_order_extraction_plans'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert {
|
||||
'shipping_order_extraction_plans', 'shipping_order_extraction_units',
|
||||
} <= set(inspector.get_table_names())
|
||||
assert {
|
||||
'plan_version', 'input_snapshot_hash', 'status', 'unit_count',
|
||||
} <= {column['name'] for column in inspector.get_columns('shipping_order_extraction_plans')}
|
||||
plan_version = next(column for column in inspector.get_columns('shipping_order_extraction_plans') if column['name'] == 'plan_version')
|
||||
assert plan_version['type'].length == 32
|
||||
assert {
|
||||
'plan_id', 'intake_id', 'document_id', 'unit_type', 'content_hash',
|
||||
'attempt_count', 'result_json', 'error_code',
|
||||
} <= {column['name'] for column in inspector.get_columns('shipping_order_extraction_units')}
|
||||
assert {
|
||||
constraint['name'] for constraint in inspector.get_unique_constraints(
|
||||
'shipping_order_extraction_units'
|
||||
)
|
||||
} == {
|
||||
'uq_shipping_order_extraction_units_document',
|
||||
'uq_shipping_order_extraction_units_position',
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_units' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_plans' not in inspector.get_table_names()
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_order_extraction_plan_version_capacity_migration_round_trip():
|
||||
"""版本容量迁移必须将32字符列扩展至64字符并可回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
create_migration = importlib.import_module('migrations.versions.a65d6e7f8091_add_order_extraction_plans')
|
||||
capacity_migration = importlib.import_module('migrations.versions.a66e7f8091a2_expand_order_extraction_plan_version')
|
||||
with engine.begin() as connection:
|
||||
original_create_op = create_migration.op
|
||||
original_capacity_op = capacity_migration.op
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
create_migration.op = operations
|
||||
capacity_migration.op = operations
|
||||
try:
|
||||
create_migration.upgrade()
|
||||
capacity_migration.upgrade()
|
||||
column = next(item for item in sa.inspect(connection).get_columns('shipping_order_extraction_plans') if item['name'] == 'plan_version')
|
||||
assert column['type'].length == 64
|
||||
capacity_migration.downgrade()
|
||||
reverted = next(item for item in sa.inspect(connection).get_columns('shipping_order_extraction_plans') if item['name'] == 'plan_version')
|
||||
assert reverted['type'].length == 32
|
||||
finally:
|
||||
create_migration.op = original_create_op
|
||||
capacity_migration.op = original_capacity_op
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_progress_migration.py
|
||||
|
||||
用途:隔离验证订单抽取进度基础迁移可完整 upgrade/downgrade。
|
||||
依赖:Alembic Operations、SQLAlchemy 内存数据库、a63b4c5d6e7f/a64c5d6e7f80 增量迁移。
|
||||
逻辑:构造迁移前最小依赖表,依次检查进度基础和节点标题移除,再按相反顺序回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
RUN_PROGRESS_COLUMNS = {
|
||||
'progress_version', 'current_stage_code', 'active_stage_codes_json',
|
||||
'completed_stage_codes_json', 'progress_message_code', 'progress_health',
|
||||
'last_activity_at', 'progress_summary_json', 'progress_mapping_version',
|
||||
'attention_generated_at', 'seen_at',
|
||||
}
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建迁移外键及 batch alter 所需的最小前置结构。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', 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),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_progress_migration_round_trip():
|
||||
"""迁移应创建完整进度结构且不采集节点标题,并可无残留回滚。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
foundation = importlib.import_module(
|
||||
'migrations.versions.a63b4c5d6e7f_add_order_extraction_progress_foundation'
|
||||
)
|
||||
privacy = importlib.import_module(
|
||||
'migrations.versions.a64c5d6e7f80_remove_order_extraction_progress_node_title'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_foundation_op = foundation.op
|
||||
original_privacy_op = privacy.op
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
foundation.op = operations
|
||||
privacy.op = operations
|
||||
try:
|
||||
foundation.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert RUN_PROGRESS_COLUMNS <= {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert {
|
||||
'shipping_order_extraction_progress_events',
|
||||
'shipping_order_extraction_diagnostic_audits',
|
||||
} <= set(inspector.get_table_names())
|
||||
event_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
assert 'node_title' in event_columns
|
||||
assert {
|
||||
'run_id', 'job_id', 'workflow_run_id', 'node_execution_id', 'node_type',
|
||||
'stage_code', 'idempotency_key', 'expires_at',
|
||||
} <= event_columns
|
||||
run_indexes = {
|
||||
index['name']: index
|
||||
for index in inspector.get_indexes('shipping_order_extraction_runs')
|
||||
}
|
||||
assert run_indexes['uq_shipping_order_extraction_runs_active_conversation']['unique'] == 1
|
||||
|
||||
privacy.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'node_title' not in {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
|
||||
privacy.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'node_title' in {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_progress_events')
|
||||
}
|
||||
|
||||
foundation.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_progress_events' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_diagnostic_audits' not in inspector.get_table_names()
|
||||
assert not RUN_PROGRESS_COLUMNS & {
|
||||
column['name'] for column in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
finally:
|
||||
foundation.op = original_foundation_op
|
||||
privacy.op = original_privacy_op
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
backend/tests/test_order_extraction_provider_guard.py
|
||||
|
||||
用途:验证 Provider 进程级并发闸门与短期熔断状态机。
|
||||
依赖:order_extraction_provider_guard、统一 ServiceUnavailableError。
|
||||
逻辑:连续失败开路,成功复位;测试不接触真实 Provider。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
assert_circuit_closed,
|
||||
record_provider_failure,
|
||||
record_provider_success,
|
||||
)
|
||||
|
||||
|
||||
def test_provider_circuit_opens_at_threshold_and_success_resets():
|
||||
"""连续失败达到阈值后快速失败,成功记录可恢复关闭状态。"""
|
||||
provider_id = 987654
|
||||
record_provider_success(provider_id)
|
||||
record_provider_failure(provider_id, threshold=2, cooldown_seconds=60)
|
||||
assert_circuit_closed(provider_id)
|
||||
record_provider_failure(provider_id, threshold=2, cooldown_seconds=60)
|
||||
with pytest.raises(Exception) as caught:
|
||||
assert_circuit_closed(provider_id)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CIRCUIT_OPEN'
|
||||
record_provider_success(provider_id)
|
||||
assert_circuit_closed(provider_id)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
用途:验证订单字段目录全局顺序迁移可升级、回填并降级。
|
||||
依赖:Alembic migration、临时 SQLite 数据库。
|
||||
逻辑:构造最小字段表,执行迁移后检查 display_sequence,再验证降级移除列。
|
||||
"""
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_field_display_sequence_migration(monkeypatch, tmp_path):
|
||||
"""迁移应按稳定字段编号回填全局顺序并支持降级。"""
|
||||
engine = sa.create_engine(f"sqlite:///{tmp_path / 'order-field-sequence.db'}")
|
||||
metadata = sa.MetaData()
|
||||
fields = sa.Table(
|
||||
'shipping_order_fields', metadata,
|
||||
sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('schema_id', sa.Integer(), nullable=False),
|
||||
sa.Column('field_code', sa.String(64), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
migration = import_module('migrations.versions.a67f8091a2b3_add_order_field_display_sequence')
|
||||
with engine.begin() as connection:
|
||||
connection.execute(fields.insert(), [
|
||||
{'id': 'field-b', 'schema_id': 1, 'field_code': 'beta'},
|
||||
{'id': 'field-a', 'schema_id': 1, 'field_code': 'alpha'},
|
||||
])
|
||||
monkeypatch.setattr(migration, 'op', Operations(MigrationContext.configure(connection)))
|
||||
migration.upgrade()
|
||||
rows = connection.execute(sa.text(
|
||||
'SELECT field_code, display_sequence FROM shipping_order_fields ORDER BY display_sequence'
|
||||
)).fetchall()
|
||||
assert rows == [('alpha', 1), ('beta', 2)]
|
||||
migration.downgrade()
|
||||
assert 'display_sequence' not in {
|
||||
column['name'] for column in sa.inspect(connection).get_columns('shipping_order_fields')
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
backend/tests/test_order_schema_table_contract.py
|
||||
|
||||
用途:验证冻结动态 Schema 的确定性表头编译、碰撞门禁和运行时歧义处理。
|
||||
依赖:table_contract、notice_line_table、统一 ValidationError。
|
||||
逻辑:用最小 definition 直接验证配置变化决定解析结果,禁止生产硬编码别名或静默选首列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_line_table import (
|
||||
inspect_notice_table_text,
|
||||
parse_notice_table_text,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _field(
|
||||
code: str,
|
||||
aliases: list[str],
|
||||
*,
|
||||
value_type: str = 'string',
|
||||
enabled: bool = True,
|
||||
collection_mode: str = 'llm_extraction',
|
||||
) -> dict:
|
||||
"""构造一个启用的最小 Schema 字段配置。"""
|
||||
return {
|
||||
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
|
||||
'value_type': value_type, 'enabled': enabled, 'display_name': code,
|
||||
'aliases': aliases, 'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else [],
|
||||
'collection_mode': collection_mode,
|
||||
}
|
||||
|
||||
|
||||
def _definition(*fields: dict) -> dict:
|
||||
"""包装字段为完整 Schema definition。"""
|
||||
return {'schema_code': 'SHIPPING_ORDER', 'version': 1, 'fields': list(fields)}
|
||||
|
||||
|
||||
def test_table_contract_is_driven_only_by_explicit_schema_aliases():
|
||||
"""同一文本只有在冻结 Schema 配置对应别名时才产生确定性订单行。"""
|
||||
text = 'Custom SKU\tCustom Qty\nABC-1\t2'
|
||||
configured = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Custom SKU']), _field('qty', ['Custom Qty'], value_type='decimal'),
|
||||
))
|
||||
unconfigured = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Other SKU']), _field('qty', ['Other Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert parse_notice_table_text(text, contract=configured)[0]['part_number'] == 'ABC-1'
|
||||
assert parse_notice_table_text(text, contract=unconfigured) == []
|
||||
assert parse_notice_table_text(text, contract=None) == []
|
||||
|
||||
|
||||
def test_table_contract_rejects_normalized_alias_collision():
|
||||
"""大小写、全半角或标点差异归一后冲突时必须阻断 Schema 保存/发布。"""
|
||||
definition = _definition(
|
||||
_field('part_number', ['Customer P/N']),
|
||||
_field('customer_part_number', ['customer p n']),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(definition)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
|
||||
|
||||
def test_table_contract_rejects_forbidden_reservation_header():
|
||||
"""管理员不得把 Allocation/Internal/UUID 类表头配置成 Reservation ID。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
|
||||
|
||||
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID']
|
||||
|
||||
|
||||
def test_runtime_reports_duplicate_columns_as_ambiguous():
|
||||
"""同一字段在一行命中多个列时不得静默选第一列。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['MPN', 'Part Number']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
inspected = inspect_notice_table_text(
|
||||
'MPN\tPart Number\tQty\nA-1\tB-2\t3', contract=contract,
|
||||
)
|
||||
|
||||
assert inspected['lines'] == []
|
||||
assert inspected['ambiguous_fields'] == ['part_number']
|
||||
assert inspected['header_found'] is True
|
||||
|
||||
|
||||
def test_table_contract_excludes_disabled_and_unsupported_context_fields():
|
||||
"""禁用字段和非表格业务上下文字段不得因配置别名进入确定性表头映射。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Disabled SKU'], enabled=False),
|
||||
_field('sender_email', ['Sender'], collection_mode='deterministic_context'),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert 'disabled sku' not in contract.header_to_field
|
||||
assert 'sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['qty'] == 'qty'
|
||||
|
||||
|
||||
def test_flat_table_parser_drops_zero_quantity_row():
|
||||
"""拍平表格入口同样不得把零数量行解析为有效订单行。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('part_number', ['Vendor PN']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert parse_notice_table_text(
|
||||
'Vendor PN\tQty\nINTERNAL-ZERO\t0\nINTERNAL-VALID\t2',
|
||||
contract=contract,
|
||||
) == [{'part_number': 'INTERNAL-VALID', 'qty': 2.0}]
|
||||
@@ -0,0 +1,199 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_contract.py
|
||||
|
||||
用途:验证 shipping_document_layout.v1 的几何、引用、跨页关系、稳定 ID 和 checksum。
|
||||
依赖:document_layout.contracts、Pydantic ValidationError。
|
||||
逻辑:使用不可逆构造样本覆盖阶段 L0 契约门禁,不依赖客户原始 PDF 或敏感业务数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
canonical_layout_checksum,
|
||||
stable_layout_id,
|
||||
validate_layout_document,
|
||||
)
|
||||
|
||||
|
||||
def _bbox(x0: float, y0: float, x1: float, y1: float) -> dict:
|
||||
"""构造原始或标准化矩形。"""
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
|
||||
|
||||
def _token(token_id: str, text: str, x0: float, x1: float) -> dict:
|
||||
"""构造一页内的原生 PDF 词元。"""
|
||||
return {
|
||||
'token_id': token_id,
|
||||
'text': text,
|
||||
'normalized_text': text,
|
||||
'bbox': _bbox(x0, 10, x1, 20),
|
||||
'normalized_bbox': _bbox(x0 / 100, 0.1, x1 / 100, 0.2),
|
||||
'source': 'native_text',
|
||||
'confidence': 1,
|
||||
'line_id': 'line-1',
|
||||
}
|
||||
|
||||
|
||||
def _cell(cell_id: str, *, row: int, column: int, text: str, token_id: str) -> dict:
|
||||
"""构造可追溯到一个词元的表格单元格。"""
|
||||
x0 = 10 + column * 40
|
||||
return {
|
||||
'cell_id': cell_id,
|
||||
'row_index': row,
|
||||
'column_index': column,
|
||||
'text': text,
|
||||
'normalized_text': text,
|
||||
'bbox': _bbox(x0, 10 + row * 20, x0 + 30, 25 + row * 20),
|
||||
'normalized_bbox': _bbox(x0 / 100, (10 + row * 20) / 100, (x0 + 30) / 100, (25 + row * 20) / 100),
|
||||
'token_ids': [token_id],
|
||||
'source': 'native_text',
|
||||
'confidence': 1,
|
||||
'role': 'header' if row == 0 else 'data',
|
||||
}
|
||||
|
||||
|
||||
def _table(table_id: str, *, continuation_of: str | None = None) -> dict:
|
||||
"""构造两列表格;调用方负责提供同页对应 token。"""
|
||||
suffix = table_id.rsplit('-', 1)[-1]
|
||||
return {
|
||||
'table_id': table_id,
|
||||
'bbox': _bbox(5, 5, 95, 55),
|
||||
'normalized_bbox': _bbox(0.05, 0.05, 0.95, 0.55),
|
||||
'rows': [
|
||||
{
|
||||
'row_id': f'row-{suffix}-0',
|
||||
'row_index': 0,
|
||||
'role': 'header',
|
||||
'cells': [
|
||||
_cell(f'cell-{suffix}-0-0', row=0, column=0, text='Part', token_id=f'token-{suffix}-part'),
|
||||
_cell(f'cell-{suffix}-0-1', row=0, column=1, text='Qty', token_id=f'token-{suffix}-qty'),
|
||||
],
|
||||
},
|
||||
],
|
||||
'header_row_indices': [0],
|
||||
'continuation_of': continuation_of,
|
||||
'confidence': 1,
|
||||
'status': 'accepted',
|
||||
}
|
||||
|
||||
|
||||
def _page(page_no: int, table_id: str, *, continuation_of: str | None = None) -> dict:
|
||||
"""构造含真实坐标词元和单个表格的页面。"""
|
||||
suffix = table_id.rsplit('-', 1)[-1]
|
||||
return {
|
||||
'page_no': page_no,
|
||||
'width': 100,
|
||||
'height': 100,
|
||||
'rotation': 0,
|
||||
'tokens': [
|
||||
_token(f'token-{suffix}-part', 'Part', 10, 40),
|
||||
_token(f'token-{suffix}-qty', 'Qty', 50, 80),
|
||||
],
|
||||
'tables': [_table(table_id, continuation_of=continuation_of)],
|
||||
}
|
||||
|
||||
|
||||
def _document() -> dict:
|
||||
"""构造带合法跨页 continuation 的完整布局文档。"""
|
||||
return {
|
||||
'schema_version': 'shipping_document_layout.v1',
|
||||
'document_id': 42,
|
||||
'content_hash': 'a' * 64,
|
||||
'parser': {'name': 'fixture-parser', 'version': '1.0.0'},
|
||||
'pages': [
|
||||
_page(1, 'table-p1'),
|
||||
_page(2, 'table-p2', continuation_of='table-p1'),
|
||||
],
|
||||
'quality': {'status': 'accepted', 'confidence': 1, 'issues': []},
|
||||
}
|
||||
|
||||
|
||||
def test_layout_contract_accepts_traceable_cross_page_table():
|
||||
"""合法结果必须保留页、表、行、列、单元格、词元和向前跨页引用。"""
|
||||
result = validate_layout_document(_document())
|
||||
|
||||
assert result.schema_version == 'shipping_document_layout.v1'
|
||||
assert result.pages[1].tables[0].continuation_of == 'table-p1'
|
||||
assert result.pages[0].tables[0].rows[0].cells[0].token_ids == ['token-p1-part']
|
||||
|
||||
|
||||
def test_layout_contract_rejects_unknown_cell_token_reference():
|
||||
"""PDF/OCR 单元格引用不存在的词元时必须拒绝,防止证据链断裂。"""
|
||||
payload = _document()
|
||||
payload['pages'][0]['tables'][0]['rows'][0]['cells'][0]['token_ids'] = ['missing-token']
|
||||
|
||||
with pytest.raises(ValidationError, match='unknown token_id'):
|
||||
validate_layout_document(payload)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_out_of_page_and_non_normalized_bbox():
|
||||
"""原始坐标越界或标准化坐标超过 0..1 均不能进入下游。"""
|
||||
outside_page = _document()
|
||||
outside_page['pages'][0]['tokens'][0]['bbox']['x1'] = 101
|
||||
with pytest.raises(ValidationError, match='exceeds page bounds'):
|
||||
validate_layout_document(outside_page)
|
||||
|
||||
outside_normalized = _document()
|
||||
outside_normalized['pages'][0]['tables'][0]['normalized_bbox']['x1'] = 1.1
|
||||
with pytest.raises(ValidationError, match='within 0..1'):
|
||||
validate_layout_document(outside_normalized)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_cell_outside_table_and_overlapping_span():
|
||||
"""单元格超出表格或 rowspan/colspan 相互覆盖时必须拒绝。"""
|
||||
outside_table = _document()
|
||||
outside_table['pages'][0]['tables'][0]['rows'][0]['cells'][0]['bbox']['x0'] = 1
|
||||
with pytest.raises(ValidationError, match='within table bbox'):
|
||||
validate_layout_document(outside_table)
|
||||
|
||||
overlapping = _document()
|
||||
cells = overlapping['pages'][0]['tables'][0]['rows'][0]['cells']
|
||||
cells[0]['column_span'] = 2
|
||||
with pytest.raises(ValidationError, match='overlapping'):
|
||||
validate_layout_document(overlapping)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_forward_or_missing_continuation():
|
||||
"""跨页表只能引用更早页面的已知表,禁止循环、前向或悬空关系。"""
|
||||
forward = _document()
|
||||
forward['pages'][0]['tables'][0]['continuation_of'] = 'table-p2'
|
||||
with pytest.raises(ValidationError, match='earlier page'):
|
||||
validate_layout_document(forward)
|
||||
|
||||
missing = _document()
|
||||
missing['pages'][1]['tables'][0]['continuation_of'] = 'table-missing'
|
||||
with pytest.raises(ValidationError, match='earlier page'):
|
||||
validate_layout_document(missing)
|
||||
|
||||
|
||||
def test_layout_contract_rejects_accepted_quality_with_blocking_issue():
|
||||
"""存在阻断质量问题的布局不能伪装成 accepted。"""
|
||||
payload = _document()
|
||||
payload['quality']['issues'] = [{
|
||||
'code': 'table_columns_ambiguous',
|
||||
'severity': 'blocking',
|
||||
'page_no': 1,
|
||||
'table_id': 'table-p1',
|
||||
'details': {},
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError, match='must not contain blocking issues'):
|
||||
validate_layout_document(payload)
|
||||
|
||||
|
||||
def test_stable_id_and_checksum_are_deterministic_and_content_sensitive():
|
||||
"""相同输入必须生成相同标识/checksum,任何结构变化必须改变 checksum。"""
|
||||
payload = _document()
|
||||
copied = deepcopy(payload)
|
||||
|
||||
assert stable_layout_id('cell', 'a' * 64, 1, 0, 0) == stable_layout_id('cell', 'a' * 64, 1, 0, 0)
|
||||
assert canonical_layout_checksum(payload) == canonical_layout_checksum(copied)
|
||||
|
||||
copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['text'] = 'Changed Part'
|
||||
copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['normalized_text'] = 'Changed Part'
|
||||
assert canonical_layout_checksum(payload) != canonical_layout_checksum(copied)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_coverage.py
|
||||
|
||||
用途:验证 HTML Schema 覆盖评估只输出聚合指标,并正确区分建单与全部必填完整性。
|
||||
依赖:document_layout.coverage/html_table、order_schema.table_contract。
|
||||
逻辑:用包含字段值和证据引用的映射结果生成报告,断言统计准确且敏感内容不进入序列化结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.coverage import summarize_html_schema_coverage
|
||||
from app.services.shipping_notice.document_layout.html_table import map_html_table_to_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _field(code: str, aliases: list[str], *, required: bool = False, value_type: str = 'string') -> dict:
|
||||
"""构造覆盖评估所需的最小冻结行字段。"""
|
||||
return {
|
||||
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
|
||||
'value_type': value_type, 'enabled': True, 'required': required,
|
||||
'display_name': code, 'aliases': aliases, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'collection_mode': 'llm_extraction',
|
||||
}
|
||||
|
||||
|
||||
def _contract():
|
||||
"""创建同时包含建单字段和跨文档 Reservation 缺口的冻结契约。"""
|
||||
return compile_table_header_contract({'fields': [
|
||||
_field('part_number', ['Vendor PN'], required=True),
|
||||
_field('qty', ['Qty'], required=True, value_type='integer'),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
]})
|
||||
|
||||
|
||||
def test_coverage_report_counts_headers_columns_rows_and_missing_required_fields():
|
||||
"""报告应正确统计命中列、未命中列以及 build/all-required 两层完整率。"""
|
||||
contract = _contract()
|
||||
complete_build = map_html_table_to_schema(
|
||||
'<table><tr><th>Vendor PN</th><th>Qty</th><th>Description</th></tr>'
|
||||
'<tr><td>SECRET-PART</td><td>2</td><td>SECRET-DESC</td></tr></table>',
|
||||
page_no=1, table_id='secret-table', contract=contract,
|
||||
)
|
||||
no_header = map_html_table_to_schema(
|
||||
'<table><tr><th>Unknown A</th><th>Unknown B</th></tr>'
|
||||
'<tr><td>SECRET-A</td><td>SECRET-B</td></tr></table>',
|
||||
page_no=2, table_id='other-table', contract=contract,
|
||||
)
|
||||
|
||||
report = summarize_html_schema_coverage([complete_build, no_header])
|
||||
|
||||
assert report.table_count == 2
|
||||
assert report.tables_with_mapped_header == 1
|
||||
assert report.tables_without_mapped_header == 1
|
||||
assert (report.mapped_columns, report.unmapped_columns, report.ambiguous_columns) == (2, 3, 0)
|
||||
assert report.mapped_column_rate == 0.4
|
||||
assert report.data_rows == 1
|
||||
assert report.build_complete_rows == 1
|
||||
assert report.all_required_complete_rows == 0
|
||||
assert report.build_complete_rate == 1.0
|
||||
assert report.all_required_complete_rate == 0.0
|
||||
assert report.field_code_frequency == {'part_number': 1, 'qty': 1}
|
||||
|
||||
|
||||
def test_coverage_report_serialization_contains_no_source_content_or_evidence_identity():
|
||||
"""聚合报告不得泄露字段值、表格 ID、单元格引用、表头或证据文本。"""
|
||||
mapping = map_html_table_to_schema(
|
||||
'<table><tr><th>Vendor PN</th><th>Qty</th></tr>'
|
||||
'<tr><td>PRIVATE-PART-9988</td><td>7</td></tr></table>',
|
||||
page_no=9, table_id='private-table-id', contract=_contract(),
|
||||
)
|
||||
|
||||
serialized = summarize_html_schema_coverage([mapping]).model_dump_json()
|
||||
|
||||
for forbidden in ('PRIVATE-PART-9988', 'private-table-id', 'Vendor PN', 'evidence_ref', 'cell_id'):
|
||||
assert forbidden not in serialized
|
||||
|
||||
|
||||
def test_empty_coverage_report_has_zero_rates_and_empty_frequencies():
|
||||
"""没有表格时报告必须给出稳定零值,便于自动 Review 比较。"""
|
||||
report = summarize_html_schema_coverage([])
|
||||
|
||||
assert report.table_count == 0
|
||||
assert report.mapped_column_rate == 0
|
||||
assert report.build_complete_rate == 0
|
||||
assert report.all_required_complete_rate == 0
|
||||
assert report.field_code_frequency == {}
|
||||
assert report.issue_code_frequency == {}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_evaluation.py
|
||||
|
||||
用途:验证阶段 L0 人工真值契约和表格/单元格评测指标。
|
||||
依赖:document_layout.evaluation、布局契约测试构造器。
|
||||
逻辑:以不可逆构造样本模拟完整命中、漏单元格、字段错配和哈希漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.evaluation import evaluate_layout
|
||||
from tests.test_shipping_document_layout_contract import _document
|
||||
|
||||
|
||||
def _annotation() -> dict:
|
||||
"""为构造布局生成两页、两表、四单元格的人工真值。"""
|
||||
tables = []
|
||||
for page_no, suffix, continuation in ((1, 'p1', None), (2, 'p2', 'truth-p1')):
|
||||
cells = []
|
||||
for column, text, field_code in ((0, 'Part', 'part_number'), (1, 'Qty', 'qty')):
|
||||
x0 = 10 + column * 40
|
||||
cells.append({
|
||||
'annotation_id': f'truth-cell-{suffix}-{column}',
|
||||
'page_no': page_no,
|
||||
'table_index': 0,
|
||||
'row_index': 0,
|
||||
'column_index': column,
|
||||
'normalized_bbox': {
|
||||
'x0': x0 / 100, 'y0': 0.1, 'x1': (x0 + 30) / 100, 'y1': 0.25,
|
||||
},
|
||||
'normalized_text': text,
|
||||
'role': 'header',
|
||||
'expected_field_code': field_code,
|
||||
})
|
||||
tables.append({
|
||||
'annotation_id': f'truth-{suffix}',
|
||||
'page_no': page_no,
|
||||
'table_index': 0,
|
||||
'normalized_bbox': {'x0': 0.05, 'y0': 0.05, 'x1': 0.95, 'y1': 0.55},
|
||||
'cells': cells,
|
||||
'continuation_of': continuation,
|
||||
})
|
||||
return {
|
||||
'schema_version': 'shipping_document_layout_annotation.v1',
|
||||
'layout_schema_version': 'shipping_document_layout.v1',
|
||||
'sample_id': 'synthetic-two-page-table',
|
||||
'content_hash': 'a' * 64,
|
||||
'categories': ['native_pdf', 'cross_page_table'],
|
||||
'tables': tables,
|
||||
}
|
||||
|
||||
|
||||
def test_evaluation_reports_perfect_layout_and_field_mapping():
|
||||
"""几何、行列和字段映射全部正确时四项指标均为 1。"""
|
||||
mapped = {
|
||||
'cell-p1-0-0': 'part_number', 'cell-p1-0-1': 'qty',
|
||||
'cell-p2-0-0': 'part_number', 'cell-p2-0-1': 'qty',
|
||||
}
|
||||
|
||||
result = evaluate_layout(_annotation(), _document(), mapped_field_codes=mapped)
|
||||
|
||||
assert result.table_detection_recall == 1
|
||||
assert result.cell_detection_recall == 1
|
||||
assert result.cell_position_accuracy == 1
|
||||
assert result.field_mapping_accuracy == 1
|
||||
|
||||
|
||||
def test_evaluation_separates_detection_position_and_field_errors():
|
||||
"""漏单元格与字段错配必须反映在不同指标,便于定位解析层或映射层问题。"""
|
||||
candidate = _document()
|
||||
candidate['pages'][1]['tables'][0]['rows'][0]['cells'].pop()
|
||||
mapped = {
|
||||
'cell-p1-0-0': 'qty',
|
||||
'cell-p1-0-1': 'qty',
|
||||
'cell-p2-0-0': 'part_number',
|
||||
}
|
||||
|
||||
result = evaluate_layout(_annotation(), candidate, mapped_field_codes=mapped)
|
||||
|
||||
assert result.table_detection_recall == 1
|
||||
assert result.cell_detection_recall == 0.75
|
||||
assert result.cell_position_accuracy == 1
|
||||
assert result.field_mapping_accuracy == 0.5
|
||||
|
||||
|
||||
def test_evaluation_rejects_annotation_for_another_file():
|
||||
"""人工真值与候选文件哈希不一致时不得产生误导性指标。"""
|
||||
annotation = deepcopy(_annotation())
|
||||
annotation['content_hash'] = 'b' * 64
|
||||
|
||||
with pytest.raises(ValueError, match='content_hash'):
|
||||
evaluate_layout(annotation, _document())
|
||||
|
||||
|
||||
def test_evaluation_rejects_invalid_annotation_geometry():
|
||||
"""人工真值坐标越界或单元格超出父表时必须在评测前拒绝。"""
|
||||
outside_page = _annotation()
|
||||
outside_page['tables'][0]['normalized_bbox']['x1'] = 1.1
|
||||
with pytest.raises(ValidationError, match='within 0..1'):
|
||||
evaluate_layout(outside_page, _document())
|
||||
|
||||
outside_table = _annotation()
|
||||
outside_table['tables'][0]['cells'][0]['normalized_bbox']['x0'] = 0.01
|
||||
with pytest.raises(ValidationError, match='within parent table'):
|
||||
evaluate_layout(outside_table, _document())
|
||||
@@ -0,0 +1,318 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_html_table.py
|
||||
|
||||
用途:验证 HTML 表格网格恢复和冻结订单 Schema 的确定性列映射不会发生跨列猜测。
|
||||
依赖:document_layout.html_table、order_schema.table_contract、统一 ValidationError。
|
||||
逻辑:构造最小 HTML 与动态别名契约,覆盖合并格、后置表头、特殊行和历史错位场景。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.html_table import (
|
||||
map_html_table_to_schema,
|
||||
parse_html_grid,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
compile_table_header_contract,
|
||||
)
|
||||
|
||||
|
||||
def _field(
|
||||
code: str,
|
||||
aliases: list[str],
|
||||
*,
|
||||
value_type: str = 'string',
|
||||
required: bool = False,
|
||||
normalizer_key: str = 'trim',
|
||||
validator_keys: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""构造由测试显式控制别名和校验器的最小行字段配置。"""
|
||||
return {
|
||||
'field_id': f'id-{code}',
|
||||
'field_code': code,
|
||||
'scope': 'line',
|
||||
'value_type': value_type,
|
||||
'enabled': True,
|
||||
'required': required,
|
||||
'display_name': code,
|
||||
'aliases': aliases,
|
||||
'normalizer_key': normalizer_key,
|
||||
'validator_keys': validator_keys or [],
|
||||
'collection_mode': 'llm_extraction',
|
||||
}
|
||||
|
||||
|
||||
def _contract(*fields: dict):
|
||||
"""把测试字段冻结为与生产 Run 相同形态的表头契约。"""
|
||||
return compile_table_header_contract({
|
||||
'schema_code': 'SHIPPING_ORDER',
|
||||
'version': 1,
|
||||
'fields': list(fields),
|
||||
})
|
||||
|
||||
|
||||
def _map(html: str, *fields: dict):
|
||||
"""以固定页码和表 ID 映射 HTML,便于断言短证据引用。"""
|
||||
return map_html_table_to_schema(
|
||||
html,
|
||||
page_no=2,
|
||||
table_id='table-1',
|
||||
contract=_contract(*fields),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_html_grid_expands_rowspan_and_colspan():
|
||||
"""rowspan/colspan 必须展开成矩形 Slot,同时保留共同原始 cell_id。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th rowspan="2">PO</th><th colspan="2">Line</th></tr>'
|
||||
'<tr><th>Part</th><th>Qty</th></tr><tr><td>P1</td><td>A1</td><td>2</td></tr></table>',
|
||||
table_id='t',
|
||||
)
|
||||
|
||||
assert (grid.row_count, grid.column_count) == (3, 3)
|
||||
assert grid.rows[0][0].cell_id == grid.rows[1][0].cell_id
|
||||
assert grid.rows[0][1].cell_id == grid.rows[0][2].cell_id
|
||||
|
||||
|
||||
def test_multilevel_header_maps_only_explicit_combined_aliases():
|
||||
"""多层表头可按组合路径命中,但没有配置的兄弟列必须保持未映射。"""
|
||||
result = _map(
|
||||
'<table><tr><th colspan="2">Order</th></tr>'
|
||||
'<tr><th>Part</th><th>Description</th></tr><tr><td>A-1</td><td>Rack</td></tr></table>',
|
||||
_field('part_number', ['Order Part'], required=True),
|
||||
)
|
||||
|
||||
assert result.header_row_index == 1
|
||||
assert [column.status for column in result.columns] == ['mapped', 'unmapped']
|
||||
data = next(row for row in result.rows if row.role == 'data')
|
||||
assert [(field.field_code, field.value) for field in data.fields] == [('part_number', 'A-1')]
|
||||
assert data.complete_required_fields is True
|
||||
|
||||
|
||||
def test_header_can_appear_after_an_unrelated_intro_row():
|
||||
"""表头不在首行时仍按最高精确命中选择,前置说明行不得改变列归属。"""
|
||||
result = _map(
|
||||
'<table><tr><td>Customer supplied table</td><td></td></tr>'
|
||||
'<tr><td>SKU</td><td>Quantity</td></tr><tr><td>A-1</td><td>3</td></tr></table>',
|
||||
_field('part_number', ['SKU']),
|
||||
_field('qty', ['Quantity'], value_type='decimal', validator_keys=['positive_decimal']),
|
||||
)
|
||||
|
||||
assert result.header_row_index == 1
|
||||
data = result.rows[-1]
|
||||
assert {field.field_code: field.value for field in data.fields} == {
|
||||
'part_number': 'A-1',
|
||||
'qty': Decimal('3'),
|
||||
}
|
||||
|
||||
|
||||
def test_repeated_header_deleted_summary_and_empty_rows_are_not_data():
|
||||
"""分页重复表头、删除、合计与空行必须显式分类,禁止生成订单行字段。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>Part</td><td>Qty</td></tr><tr><td>Item deleted</td><td></td></tr>'
|
||||
'<tr><td>Total</td><td>2</td></tr><tr><td></td><td></td></tr></table>',
|
||||
_field('part_number', ['Part']),
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == [
|
||||
'repeated_header', 'deleted', 'summary', 'empty',
|
||||
]
|
||||
assert all(not row.fields for row in result.rows)
|
||||
|
||||
|
||||
def test_explicit_zero_quantity_row_is_deleted_without_field_candidates():
|
||||
"""冻结 Qty 列明确为零的订单行必须删除,不能作为不完整 Candidate 流入后续。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-ZERO</td><td>0 EA</td></tr>'
|
||||
'<tr><td>INTERNAL-VALID</td><td>3 EA</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert result.rows[0].role == 'deleted'
|
||||
assert result.rows[0].fields == []
|
||||
assert result.rows[1].role == 'data'
|
||||
assert {field.field_code: field.value for field in result.rows[1].fields} == {
|
||||
'part_number': 'INTERNAL-VALID',
|
||||
'qty': 3,
|
||||
}
|
||||
|
||||
|
||||
def test_negative_or_invalid_quantity_is_not_classified_as_deleted():
|
||||
"""负数或非法数量不是业务删除指令,必须保留为数据质量问题而非静默删除。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-NEG</td><td>-1</td></tr>'
|
||||
'<tr><td>INTERNAL-BAD</td><td>N/A</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True, validator_keys=['positive_integer']),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == ['data', 'data']
|
||||
assert all(row.missing_required_field_codes == ['qty'] for row in result.rows)
|
||||
|
||||
|
||||
def test_unknown_business_columns_never_shift_into_known_fields():
|
||||
"""历史错位值只能留在未映射列,不能按值形态变成 AWS、Reservation 或料号。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Description</th><th>Legacy Ref</th><th>Hub</th><th>Material</th><th>Qty</th></tr>'
|
||||
'<tr><td>A01 SET,RACK,ENCLOSURE</td><td>D4-A08AR12000002</td>'
|
||||
'<td>AWS HUB</td><td>6Y70B2501901</td><td>30</td></tr></table>',
|
||||
_field('aws_part_number', ['AWS Part Number']),
|
||||
_field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'),
|
||||
_field('part_number', ['Part Number']),
|
||||
_field('inventory_source_hint', ['Inventory Source']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == [
|
||||
'unmapped', 'unmapped', 'unmapped', 'unmapped', 'mapped',
|
||||
]
|
||||
data = result.rows[0]
|
||||
assert [(field.field_code, field.value) for field in data.fields] == [('qty', 30)]
|
||||
|
||||
|
||||
def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it():
|
||||
"""同一 Hub 表头仅在冻结 Schema 明确声明别名后才映射库存来源。"""
|
||||
result = _map(
|
||||
'<table><tr><th>AWS HUB</th><th>Qty</th></tr><tr><td>SIN</td><td>1</td></tr></table>',
|
||||
_field('inventory_source_hint', ['AWS HUB']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'inventory_source_hint': 'SIN',
|
||||
'qty': 1,
|
||||
}
|
||||
|
||||
|
||||
def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>',
|
||||
_field('customer_part_number', ['Material No']),
|
||||
_field('part_number', ['Vendor Part Number']),
|
||||
_field('aws_part_number', ['AWS SKU']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1',
|
||||
'aws_part_number': 'AWS-1',
|
||||
'qty': 2,
|
||||
}
|
||||
|
||||
|
||||
def test_missing_reservation_preserves_build_complete_order_row():
|
||||
"""PDF 缺 Reservation 时仍保留 part_number+qty 候选,并显式列出跨文档补充缺口。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
)
|
||||
|
||||
row = result.rows[0]
|
||||
assert row.complete_build_fields is True
|
||||
assert row.complete_required_fields is False
|
||||
assert row.missing_required_field_codes == ['reservation_id']
|
||||
|
||||
|
||||
def test_customer_material_without_internal_part_is_not_build_complete():
|
||||
"""只有客户 Material+Qty 时不得冒充内部料号形成可建单行。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>2</td></tr></table>',
|
||||
_field('customer_part_number', ['Material No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
_field('reservation_id', ['Reservation ID'], required=True),
|
||||
)
|
||||
|
||||
row = result.rows[0]
|
||||
assert row.complete_build_fields is False
|
||||
assert row.missing_required_field_codes == ['part_number', 'reservation_id']
|
||||
|
||||
|
||||
def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed():
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('line_no', ['Item No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert result.columns[0].status == 'unmapped'
|
||||
assert 'html_table_header_value_contamination' in result.issues
|
||||
assert {field.field_code for field in result.rows[0].fields} == {'part_number', 'qty'}
|
||||
|
||||
|
||||
def test_legitimate_alphanumeric_header_is_not_numeric_value_contamination():
|
||||
"""未命中“精确别名+纯数字后缀”的普通业务表头不得被污染规则误报。"""
|
||||
result = _map(
|
||||
'<table><tr><th>RoHS2</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>Y</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
assert 'html_table_header_value_contamination' not in result.issues
|
||||
|
||||
|
||||
def test_duplicate_columns_for_one_field_are_all_blocked():
|
||||
"""同一字段命中多个列时所有冲突列都标歧义,数据行不得静默选首列。"""
|
||||
result = _map(
|
||||
'<table><tr><th>MPN</th><th>Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>A-1</td><td>B-2</td><td>3</td></tr></table>',
|
||||
_field('part_number', ['MPN', 'Part Number']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == ['ambiguous', 'ambiguous', 'mapped']
|
||||
assert 'html_table_columns_ambiguous' in result.issues
|
||||
assert 'html_table_duplicate_field_columns' in result.issues
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 3)]
|
||||
|
||||
|
||||
def test_reservation_validator_rejects_line_number_shape():
|
||||
"""即使表头正确,Reservation 安全校验仍须拒绝纯行号,避免历史错误进入候选。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Reservation ID</th><th>Qty</th></tr><tr><td>00010</td><td>1</td></tr></table>',
|
||||
_field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 1)]
|
||||
|
||||
|
||||
def test_nested_table_rows_do_not_pollute_parent_grid():
|
||||
"""主表单元格内的嵌套展示表格不得被重复解析成主表数据行。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>Part</th><th>Detail</th></tr><tr><td>A-1</td>'
|
||||
'<td><table><tr><td>nested</td></tr></table></td></tr></table>',
|
||||
table_id='outer',
|
||||
)
|
||||
|
||||
assert (grid.row_count, grid.column_count) == (2, 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('attribute', ['rowspan="0"', 'colspan="bad"'])
|
||||
def test_invalid_span_is_rejected(attribute: str):
|
||||
"""零值或非数字跨度必须拒绝,禁止产生不稳定网格。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_html_grid(f'<table><tr><td {attribute}>A</td></tr></table>', table_id='t')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID'
|
||||
@@ -0,0 +1,275 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_mineru.py
|
||||
|
||||
用途:验证 MinerU 客户端资源门禁、字符串 JSON 解包、HTML 表格候选和单元格证据准入。
|
||||
依赖:document_layout.mineru、统一 AppError、requests Response 协议最小替身。
|
||||
逻辑:全部使用脱敏构造响应,不访问真实 MinerU 服务,也不把文件正文写入失败输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
|
||||
|
||||
def _mineru_payload(*, with_cell_coordinates: bool = False) -> dict:
|
||||
"""构造与 MinerU 3.1.14 pipeline 相同的字符串 JSON 包装。"""
|
||||
cell_coordinate = ([
|
||||
{'row_idx': 0, 'col_idx': 0, 'bbox': [10, 20, 50, 40]},
|
||||
{'row_idx': 0, 'col_idx': 1, 'bbox': [50, 20, 90, 40]},
|
||||
{'row_idx': 1, 'col_idx': 0, 'bbox': [10, 40, 50, 60]},
|
||||
{'row_idx': 1, 'col_idx': 1, 'bbox': [50, 40, 90, 60]},
|
||||
] if with_cell_coordinates else [])
|
||||
return {
|
||||
'task_id': 'task-layout-fixture',
|
||||
'status': 'completed',
|
||||
'backend': 'pipeline',
|
||||
'version': '3.1.14',
|
||||
'results': {
|
||||
'fixture': {
|
||||
'middle_json': json.dumps({
|
||||
'pdf_info': [{
|
||||
'page_idx': 0,
|
||||
'page_size': [100, 200],
|
||||
'blocks': [{'type': 'text', 'bbox': [5, 5, 20, 15]}],
|
||||
}],
|
||||
'cell_coordinates': cell_coordinate,
|
||||
}),
|
||||
'model_output': json.dumps([{
|
||||
'page_info': {'page_no': 0, 'width': 100, 'height': 200},
|
||||
'layout_dets': [{'label': 'table', 'bbox': [10, 20, 90, 120]}],
|
||||
}]),
|
||||
'content_list': json.dumps([{
|
||||
'type': 'table',
|
||||
'page_idx': 0,
|
||||
'bbox': [10, 20, 90, 120],
|
||||
'table_body': (
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>A-1</td><td>2</td></tr></table>'
|
||||
),
|
||||
}, {
|
||||
'type': 'text',
|
||||
'page_idx': 0,
|
||||
'bbox': [5, 5, 20, 15],
|
||||
'text': 'Header context',
|
||||
}]),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
"""实现 MinerUClient 使用的 requests.Response 最小协议。"""
|
||||
|
||||
def __init__(self, payload: dict, *, status_code: int = 200, content_length: int | None = None):
|
||||
self.status_code = status_code
|
||||
self.encoding = 'utf-8'
|
||||
self.raw = json.dumps(payload, separators=(',', ':')).encode('utf-8')
|
||||
self.headers = {
|
||||
'Content-Length': str(len(self.raw) if content_length is None else content_length),
|
||||
}
|
||||
self.closed = False
|
||||
|
||||
def iter_content(self, chunk_size: int):
|
||||
"""按客户端指定大小分块返回构造 JSON。"""
|
||||
for index in range(0, len(self.raw), chunk_size):
|
||||
yield self.raw[index:index + chunk_size]
|
||||
|
||||
def close(self):
|
||||
"""记录响应已关闭,验证资源上限分支不泄漏连接。"""
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
"""记录 multipart 调用并返回预设响应。"""
|
||||
|
||||
def __init__(self, response: _FakeResponse):
|
||||
self.response = response
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def post(self, url: str, **kwargs):
|
||||
"""保存非敏感调用元数据;文件字节仅验证长度,不保存到测试输出。"""
|
||||
files = kwargs.get('files') or []
|
||||
self.calls.append({
|
||||
'url': url,
|
||||
'timeout': kwargs.get('timeout'),
|
||||
'stream': kwargs.get('stream'),
|
||||
'file_size': len(files[0][1][1]) if files else 0,
|
||||
'data': list(kwargs.get('data') or []),
|
||||
})
|
||||
return self.response
|
||||
|
||||
|
||||
def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence():
|
||||
"""只有整表 bbox + HTML 时必须保留行列候选并阻止确定性单元格证据。"""
|
||||
candidate = parse_mineru_candidate(_mineru_payload())
|
||||
|
||||
assert len(candidate.pages) == 1
|
||||
assert candidate.pages[0].text_blocks[0].text == 'Header context'
|
||||
assert candidate.pages[0].tables[0].row_count == 2
|
||||
assert candidate.pages[0].tables[0].cell_count == 4
|
||||
assert candidate.pages[0].tables[0].normalized_bbox.model_dump() == {
|
||||
'x0': 0.01, 'y0': 0.02, 'x1': 0.09, 'y1': 0.12,
|
||||
}
|
||||
assert candidate.pages[0].tables[0].bbox.model_dump() == {
|
||||
'x0': 1.0, 'y0': 4.0, 'x1': 9.0, 'y1': 24.0,
|
||||
}
|
||||
assert candidate.capability.has_page_coordinates is True
|
||||
assert candidate.capability.has_table_structure is True
|
||||
assert candidate.capability.has_cell_coordinates is False
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is False
|
||||
assert candidate.capability.issues == ['mineru_cell_coordinates_missing']
|
||||
|
||||
|
||||
def test_mineru_capability_accepts_explicit_cell_coordinate_objects():
|
||||
"""服务未来直接返回带行列身份的 cell bbox 时能力报告才能标记证据就绪。"""
|
||||
candidate = parse_mineru_candidate(_mineru_payload(with_cell_coordinates=True))
|
||||
|
||||
assert candidate.capability.cell_bbox_count == 4
|
||||
assert candidate.capability.has_cell_coordinates is True
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is True
|
||||
assert candidate.capability.issues == []
|
||||
|
||||
|
||||
def test_mineru_capability_rejects_partial_cell_coordinates():
|
||||
"""部分单元格有坐标仍不足以证明整表,必须保持确定性证据未就绪。"""
|
||||
payload = _mineru_payload(with_cell_coordinates=True)
|
||||
middle = json.loads(payload['results']['fixture']['middle_json'])
|
||||
middle['cell_coordinates'] = middle['cell_coordinates'][:1]
|
||||
payload['results']['fixture']['middle_json'] = json.dumps(middle)
|
||||
|
||||
candidate = parse_mineru_candidate(payload)
|
||||
|
||||
assert candidate.capability.cell_bbox_count == 1
|
||||
assert candidate.capability.html_cell_count == 4
|
||||
assert candidate.capability.has_cell_coordinates is False
|
||||
assert candidate.capability.deterministic_cell_evidence_ready is False
|
||||
assert candidate.capability.issues == ['mineru_cell_coordinates_incomplete']
|
||||
|
||||
|
||||
def test_mineru_client_sends_bounded_single_file_request():
|
||||
"""客户端只提交单文件、关闭图片/公式输出,并使用配置化超时。"""
|
||||
response = _FakeResponse(_mineru_payload())
|
||||
session = _FakeSession(response)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(
|
||||
base_url='http://mineru.internal:8100/',
|
||||
backend='pipeline',
|
||||
connect_timeout_seconds=3,
|
||||
read_timeout_seconds=45,
|
||||
),
|
||||
session=session,
|
||||
)
|
||||
|
||||
payload = client.parse_file(filename='fixture.pdf', content=b'%PDF-fixture')
|
||||
|
||||
assert payload['status'] == 'completed'
|
||||
assert session.calls == [{
|
||||
'url': 'http://mineru.internal:8100/file_parse',
|
||||
'timeout': (3, 45),
|
||||
'stream': True,
|
||||
'file_size': 12,
|
||||
'data': [
|
||||
('backend', 'pipeline'), ('parse_method', 'auto'), ('formula_enable', 'false'),
|
||||
('table_enable', 'true'), ('image_analysis', 'false'), ('return_md', 'false'),
|
||||
('return_middle_json', 'true'), ('return_model_output', 'true'),
|
||||
('return_content_list', 'true'), ('return_images', 'false'),
|
||||
('response_format_zip', 'false'), ('lang_list', 'ch'),
|
||||
],
|
||||
}]
|
||||
assert response.closed is True
|
||||
|
||||
|
||||
def test_mineru_client_rejects_unsupported_empty_and_large_files_before_network():
|
||||
"""文件类型、空内容和上传上限必须在 HTTP 请求前拒绝。"""
|
||||
session = _FakeSession(_FakeResponse(_mineru_payload()))
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100', max_upload_bytes=4),
|
||||
session=session,
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as unsupported:
|
||||
client.parse_file(filename='fixture.xlsx', content=b'1234')
|
||||
assert unsupported.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED'
|
||||
|
||||
with pytest.raises(ValidationError) as empty:
|
||||
client.parse_file(filename='fixture.pdf', content=b'')
|
||||
assert empty.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_EMPTY'
|
||||
|
||||
with pytest.raises(ValidationError) as large:
|
||||
client.parse_file(filename='fixture.pdf', content=b'12345')
|
||||
assert large.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE'
|
||||
assert session.calls == []
|
||||
|
||||
|
||||
def test_mineru_client_stops_oversized_response_and_closes_connection():
|
||||
"""Content-Length 已超限时不得读取响应正文,并必须关闭连接。"""
|
||||
response = _FakeResponse(_mineru_payload(), content_length=10_000)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100', max_response_bytes=100),
|
||||
session=_FakeSession(response),
|
||||
)
|
||||
|
||||
with pytest.raises(ServiceUnavailableError) as caught:
|
||||
client.parse_file(filename='fixture.pdf', content=b'%PDF')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE'
|
||||
assert response.closed is True
|
||||
|
||||
|
||||
def test_mineru_client_classifies_terminal_provider_error_without_filename_leak():
|
||||
"""MinerU 409 终态失败应返回稳定非重试错误,details 不得包含上传文件名。"""
|
||||
response = _FakeResponse({
|
||||
'task_id': 'failed-task',
|
||||
'status': 'failed',
|
||||
'backend': 'hybrid-auto-engine',
|
||||
'file_names': ['sensitive-order-name'],
|
||||
'error': 'Device string must not be empty',
|
||||
}, status_code=409)
|
||||
client = MinerUClient(
|
||||
MinerUClientConfig(base_url='http://mineru.internal:8100'),
|
||||
session=_FakeSession(response),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
client.parse_file(filename='sensitive-order-name.pdf', content=b'%PDF')
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED'
|
||||
assert caught.value.retryable is False
|
||||
assert 'sensitive-order-name' not in json.dumps(caught.value.details)
|
||||
assert caught.value.details['provider_error_code'] == 'device_not_configured'
|
||||
|
||||
|
||||
def test_mineru_candidate_rejects_invalid_nested_json_and_multiple_files():
|
||||
"""嵌套 JSON 损坏或批量结果不得被单 Document 适配器接受。"""
|
||||
invalid_json = _mineru_payload()
|
||||
invalid_json['results']['fixture']['middle_json'] = 'not-json'
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_mineru_candidate(invalid_json)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
multiple = _mineru_payload()
|
||||
multiple['results']['other'] = dict(multiple['results']['fixture'])
|
||||
with pytest.raises(ValidationError, match='exactly one file'):
|
||||
parse_mineru_candidate(multiple)
|
||||
|
||||
|
||||
def test_mineru_candidate_rejects_content_bbox_outside_provider_canvas():
|
||||
"""content_list bbox 超过 MinerU 0..1000 画布时不得截断或猜测坐标。"""
|
||||
payload = _mineru_payload()
|
||||
content = json.loads(payload['results']['fixture']['content_list'])
|
||||
content[0]['bbox'] = [10, 20, 1001, 120]
|
||||
payload['results']['fixture']['content_list'] = json.dumps(content)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_mineru_candidate(payload)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'
|
||||
@@ -0,0 +1,230 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_opencv_table.py
|
||||
|
||||
用途:验证 OpenCV 有框表多参数共识只在网格完整稳定时输出 HTML cell 几何候选。
|
||||
依赖:numpy、opencv_table、html_table、LayoutBBox。
|
||||
逻辑:使用合成页面覆盖标准网格、rowspan/colspan、无框表、形状不匹配和参数不足门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
DEFAULT_GRID_CONFIGS,
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
|
||||
|
||||
def _page_with_grid(*, rows: int, columns: int, width: int = 600, height: int = 400) -> np.ndarray:
|
||||
"""生成具有清晰闭合边界的合成灰度表格页面。"""
|
||||
image = np.full((height, width), 255, dtype=np.uint8)
|
||||
x_values = np.linspace(100, 500, columns + 1).astype(int)
|
||||
y_values = np.linspace(80, 320, rows + 1).astype(int)
|
||||
for x in x_values:
|
||||
cv2.line(image, (x, y_values[0]), (x, y_values[-1]), 0, 2)
|
||||
for y in y_values:
|
||||
cv2.line(image, (x_values[0], y), (x_values[-1], y), 0, 2)
|
||||
return image
|
||||
|
||||
|
||||
def _bbox() -> LayoutBBox:
|
||||
"""返回与合成表格略带外边距的页面单位 bbox。"""
|
||||
return LayoutBBox(x0=95, y0=75, x1=505, y1=325)
|
||||
|
||||
|
||||
def test_opencv_grid_consensus_returns_all_html_cell_geometries():
|
||||
"""多参数检测一致且形状匹配时应为每个 HTML cell 返回页面 bbox。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='t',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
assert result.consensus_count >= 2
|
||||
assert len(result.cells) == 4
|
||||
assert result.cells[0].bbox.x0 < result.cells[1].bbox.x0
|
||||
assert result.cells[0].normalized_bbox.x1 <= 1
|
||||
|
||||
|
||||
def test_opencv_grid_uses_html_spans_to_merge_base_cells():
|
||||
"""rowspan/colspan 由 HTML 决定,几何候选必须跨越对应基础网格边界。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th rowspan="2">A</th><th>B</th></tr><tr><td>C</td></tr></table>',
|
||||
table_id='span',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
merged = next(cell for cell in result.cells if cell.row_span == 2)
|
||||
ordinary = next(cell for cell in result.cells if cell.row_index == 0 and cell.column_index == 1)
|
||||
assert merged.bbox.y1 > ordinary.bbox.y1
|
||||
|
||||
|
||||
def test_opencv_grid_rejects_shape_mismatch_without_exposing_cells():
|
||||
"""图像三列表与 HTML 两列表不一致时必须失败,不能裁剪或合并到预期形状。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='mismatch',
|
||||
)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=3),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
assert result.issues
|
||||
|
||||
|
||||
def test_opencv_grid_rejects_borderless_table():
|
||||
"""无框页面不得按 HTML 行列数均分生成伪 cell bbox。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='borderless',
|
||||
)
|
||||
page = np.full((400, 600), 255, dtype=np.uint8)
|
||||
cv2.putText(page, 'A B', (120, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 0, 2)
|
||||
cv2.putText(page, 'C D', (120, 220), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 0, 2)
|
||||
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
page,
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
|
||||
|
||||
def test_opencv_grid_requires_multiple_detection_configurations():
|
||||
"""单参数结果不能形成共识,避免特定阈值偶然命中进入证据链。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='config',
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='at least two configurations'):
|
||||
reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
configs=(DEFAULT_GRID_CONFIGS[0],),
|
||||
)
|
||||
|
||||
|
||||
def test_opencv_text_validation_accepts_matching_cells_and_required_subset():
|
||||
"""几何候选文本全部一致且高风险 cell 命中时才通过独立验收。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr><tr><td>A-1</td><td>2</td></tr></table>',
|
||||
table_id='text-ok',
|
||||
)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
values = {cell.cell_id: cell.text for cell in grid.cells}
|
||||
by_box = {
|
||||
(item.bbox.x0, item.bbox.y0, item.bbox.x1, item.bbox.y1): values[item.cell_id]
|
||||
for item in geometry.cells
|
||||
}
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda box: by_box[(box.x0, box.y0, box.x1, box.y1)],
|
||||
required_cell_ids={grid.cells[2].cell_id, grid.cells[3].cell_id},
|
||||
)
|
||||
|
||||
assert result.accepted is True
|
||||
assert result.match_rate == 1
|
||||
assert result.mismatched_cell_ids == []
|
||||
|
||||
|
||||
def test_opencv_text_validation_rejects_required_cell_mismatch_even_above_rate():
|
||||
"""高风险 cell 文本不一致时,即使总体比例达到阈值也必须拒绝整表。"""
|
||||
html = '<table><tr>' + ''.join(f'<th>H{i}</th>' for i in range(10)) + '</tr></table>'
|
||||
grid = parse_html_grid(html, table_id='required-fail')
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=1, columns=10),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
required_id = grid.cells[-1].cell_id
|
||||
values = {cell.cell_id: cell.text for cell in grid.cells}
|
||||
by_box = {
|
||||
(item.bbox.x0, item.bbox.y0, item.bbox.x1, item.bbox.y1): (
|
||||
'WRONG' if item.cell_id == required_id else values[item.cell_id]
|
||||
)
|
||||
for item in geometry.cells
|
||||
}
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda box: by_box[(box.x0, box.y0, box.x1, box.y1)],
|
||||
minimum_match_rate=0.9,
|
||||
required_cell_ids={required_id},
|
||||
)
|
||||
|
||||
assert result.match_rate == 0.9
|
||||
assert result.accepted is False
|
||||
assert 'opencv_table_required_cell_text_mismatch' in result.issues
|
||||
|
||||
|
||||
def test_opencv_text_validation_rejects_low_overall_match_rate():
|
||||
"""非高风险 cell 大量错位也必须因整表一致率不足而拒绝。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='rate-fail',
|
||||
)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
_page_with_grid(rows=2, columns=2),
|
||||
page_width=600,
|
||||
page_height=400,
|
||||
table_bbox=_bbox(),
|
||||
grid=grid,
|
||||
)
|
||||
|
||||
result = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=lambda _box: 'WRONG',
|
||||
)
|
||||
|
||||
assert result.accepted is False
|
||||
assert result.match_rate == 0
|
||||
assert 'opencv_table_text_match_rate_low' in result.issues
|
||||
@@ -21,6 +21,33 @@ from app.services.shipping_notice.reservation_id import (
|
||||
looks_like_reservation_id,
|
||||
normalize_reservation_id,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _table_schema_definition() -> dict:
|
||||
"""构造本文件表格样本使用的显式动态 Schema,禁止依赖生产硬编码别名。"""
|
||||
aliases = {
|
||||
'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'],
|
||||
'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'],
|
||||
'amount': ['Amount'], 'currency': ['Currency'],
|
||||
'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'],
|
||||
'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'],
|
||||
'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'],
|
||||
'inventory_source_hint': ['source type'], 'po_number': ['PO'],
|
||||
}
|
||||
decimal_fields = {'qty', 'unit_price', 'amount'}
|
||||
return {'fields': [{
|
||||
'field_id': f'test-{code}', 'field_code': code,
|
||||
'scope': 'header' if code == 'po_number' else 'line',
|
||||
'value_type': 'decimal' if code in decimal_fields else 'date' if code == 'required_date' else 'string',
|
||||
'enabled': True, 'display_name': code, 'aliases': values, 'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else [],
|
||||
} for code, values in aliases.items()]}
|
||||
|
||||
|
||||
def _table_contract():
|
||||
"""编译测试共享的冻结表头契约。"""
|
||||
return compile_table_header_contract(_table_schema_definition())
|
||||
|
||||
|
||||
def _minimal_pdf_bytes(marker: str) -> bytes:
|
||||
@@ -146,7 +173,7 @@ S-ENC-FOBU260702-286\t2000485916\tVMI-FRA01\tTEMP-S000218922\t504-006043-001\t30
|
||||
S-BRA-FOBU260702-187\t2000485915\tVMI-FRA01\tTEMP-S000196207\t504-006076-001\t60\tD4-AR1200115A1\tFRA01\t4510039228
|
||||
S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD4-A08AR12000001\tDUB\t4510039229
|
||||
"""
|
||||
rows = build_email_order_index(body)
|
||||
rows = build_email_order_index(body, schema_definition=_table_schema_definition())
|
||||
assert len(rows) == 3
|
||||
assert rows[0]['po_number'] == '4510039227'
|
||||
assert rows[0]['reservation_id'] == '2000485916'
|
||||
@@ -1247,7 +1274,9 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "3000092917"
|
||||
@@ -1280,7 +1309,9 @@ def test_flattened_text_does_not_guess_external_reservation_id():
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "needs_review"
|
||||
assert "reservation_id" not in adjudicated[0]
|
||||
@@ -1293,28 +1324,30 @@ def test_adjudication_supports_non_numeric_reservation_templates():
|
||||
raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2"
|
||||
lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
lines, raw_text=raw_text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "AWS-311"
|
||||
assert issues[0]["reason"] == "value_corrected"
|
||||
|
||||
|
||||
def test_wistron_po_table_with_pr_number_in_document():
|
||||
def test_wistron_po_table_does_not_broadcast_document_reservation_to_every_line():
|
||||
text = """
|
||||
Vendor: HOXIN
|
||||
PR Number: ADU_S-ENCWIW260528126265@1000140351
|
||||
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
|
||||
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 1
|
||||
assert lines[0]["part_number"] == "B3-A08AR11000001"
|
||||
assert lines[0]["line_no"] == "10"
|
||||
assert lines[0]["qty"] == 9.0
|
||||
assert lines[0]["unit_price"] == 1607.72
|
||||
assert lines[0]["amount"] == 14469.48
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
assert "reservation_id" not in lines[0]
|
||||
assert lines[0]["required_date"] == "2026-06-15"
|
||||
assert lines[0]["aws_part_number"] == "504-010213-001"
|
||||
assert lines[0]["currency"] == "USD"
|
||||
@@ -1331,15 +1364,15 @@ def test_parse_notice_table_numeric_reservation_id():
|
||||
Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
10-40594-001\t1000140351\t2\t15.5\t31.0
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
|
||||
|
||||
def test_infer_reservation_id_without_header():
|
||||
def test_does_not_infer_reservation_id_without_configured_header():
|
||||
headers = ["Part Number", "Ref", "Qty"]
|
||||
rows = [["10-40594-001", 1000140351, 2]]
|
||||
lines = parse_notice_table_rows(headers, rows)
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
lines = parse_notice_table_rows(headers, rows, contract=_table_contract())
|
||||
assert "reservation_id" not in lines[0]
|
||||
|
||||
|
||||
def test_parse_notice_table_with_all_fields():
|
||||
@@ -1348,7 +1381,7 @@ Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
10-40594-001\tAWS-311\t2\t15.5\t31.0
|
||||
10-40594-002\tORD-3002\t1\t20\t20
|
||||
"""
|
||||
lines = parse_notice_table_text(text)
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 2
|
||||
assert lines[0]["part_number"] == "10-40594-001"
|
||||
assert lines[0]["reservation_id"] == "AWS-311"
|
||||
@@ -1375,7 +1408,6 @@ def test_normalize_notice_line_aliases():
|
||||
"line_no": "10",
|
||||
"part_number": "A-001",
|
||||
"qty": 3.0,
|
||||
"uom": "EA",
|
||||
"reservation_id": "COM-99",
|
||||
"unit_price": 12.5,
|
||||
"amount": 37.5,
|
||||
@@ -1412,6 +1444,7 @@ def test_parse_notice_table_maps_three_part_number_roles():
|
||||
lines = parse_notice_table_rows(
|
||||
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
|
||||
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
|
||||
contract=_table_contract(),
|
||||
)
|
||||
|
||||
assert lines == [{
|
||||
@@ -1419,7 +1452,6 @@ def test_parse_notice_table_maps_three_part_number_roles():
|
||||
"customer_part_number": "TEMP-S000218929",
|
||||
"aws_part_number": "504-006055-001",
|
||||
"qty": 10.0,
|
||||
"uom": "EA",
|
||||
}]
|
||||
|
||||
|
||||
@@ -1428,6 +1460,7 @@ def test_parse_notice_table_rejects_aws_only_as_internal_part_number():
|
||||
assert parse_notice_table_rows(
|
||||
["AWS Sku", "Reservation ID", "Qty"],
|
||||
[["504-006055-001", "3000092917", 10]],
|
||||
contract=_table_contract(),
|
||||
) == []
|
||||
|
||||
|
||||
@@ -1500,7 +1533,7 @@ Shipping Notice
|
||||
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
|
||||
10-40594-001\tORD-3002\t4\t5\t20
|
||||
"""
|
||||
parsed, confidence, _ = _heuristic_extract(text)
|
||||
parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition())
|
||||
assert len(parsed["lines"]) == 1
|
||||
assert parsed["lines"][0]["part_number"] == "10-40594-001"
|
||||
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
|
||||
@@ -1530,7 +1563,9 @@ def test_extract_notice_fields_structured_over_heuristic():
|
||||
def test_extract_notice_fields_heuristic_fallback():
|
||||
"""无 structured 时走后端启发式兜底。"""
|
||||
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
|
||||
parsed, _, warnings = extract_notice_fields(raw_text=text)
|
||||
parsed, _, warnings = extract_notice_fields(
|
||||
raw_text=text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
assert parsed["parse_source"] == "heuristic"
|
||||
assert parsed["lines"][0]["part_number"] == "10-40594-001"
|
||||
assert "parse_fallback_heuristic" in warnings
|
||||
@@ -17,6 +17,27 @@ from app.services.shipping_notice.field_adjudication import (
|
||||
)
|
||||
|
||||
|
||||
def _schema_definition() -> dict:
|
||||
"""构造裁决测试使用的显式行字段 Schema。"""
|
||||
return {'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['MPN'],
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Qty'],
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'display_name': '预约单号', 'aliases': ['Reservation ID'],
|
||||
'normalizer_key': 'trim', 'validator_keys': ['reservation_id'],
|
||||
},
|
||||
]}
|
||||
|
||||
|
||||
def _document(document_id: int, text: str):
|
||||
"""构造裁决服务所需的最小 Document 测试替身。"""
|
||||
return SimpleNamespace(id=document_id, extracted_text=text)
|
||||
@@ -55,6 +76,7 @@ def test_adjudication_uses_verified_dify_when_backend_has_no_table():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -72,6 +94,7 @@ def test_adjudication_uses_backend_when_dify_field_is_missing():
|
||||
{"lines": [{"qty": 10}]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
)
|
||||
|
||||
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
|
||||
@@ -89,6 +112,7 @@ def test_adjudication_marks_consensus_without_overwriting_observations():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -113,6 +137,7 @@ def test_adjudication_blocks_two_trusted_different_values():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -132,6 +157,7 @@ def test_adjudication_prefers_backend_when_dify_quote_is_unverified():
|
||||
{"lines": [line]},
|
||||
raw_order=raw_order,
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
field_confidence=raw_order["field_confidence"],
|
||||
)
|
||||
|
||||
@@ -151,6 +177,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
|
||||
{"lines": []},
|
||||
raw_order={"lines": [], "evidence": []},
|
||||
documents=[document],
|
||||
schema_definition=_schema_definition(),
|
||||
)
|
||||
|
||||
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
|
||||
|
||||
@@ -23,6 +23,9 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
@@ -478,6 +481,16 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Candidate batch test')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', checksum='c' * 64,
|
||||
definition_json={'schema_code': 'SHIPPING_ORDER', 'version': 1, 'fields': []},
|
||||
published_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
|
||||
candidate_nos = []
|
||||
hashes = []
|
||||
@@ -545,6 +558,17 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
|
||||
content_fingerprint_version=content['version'],
|
||||
duplicate_status='none',
|
||||
)
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id,
|
||||
schema_version_id=schema_version.id,
|
||||
input_snapshot_hash=(str(index) * 64)[:64],
|
||||
status='accepted',
|
||||
normalized_result_json={'header': {}, 'lines': summary['lines']},
|
||||
validation_result_json={'blocked_fields': []},
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
candidate.order_extraction_id = extraction.id
|
||||
db.session.add(candidate)
|
||||
candidate_nos.append(candidate.candidate_no)
|
||||
hashes.append(attachment.content_hash)
|
||||
|
||||
@@ -43,7 +43,7 @@ from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.task_order_field_editor import current_line_field_values
|
||||
from app.services.shipping_notice.task_order_field_editor import current_line_field_values, current_order_field_display
|
||||
|
||||
|
||||
def _ensure_order_schema() -> dict[str, str]:
|
||||
@@ -260,6 +260,26 @@ def _persist_test_orders(payload: dict) -> dict:
|
||||
run_id=None,
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
|
||||
|
||||
def _persist_shadow_orders(payload: dict) -> dict:
|
||||
"""以默认关闭的自动建单门禁执行影子提交。"""
|
||||
session = ChatSession.query.filter_by(session_id='shipping-order-extraction-session').one()
|
||||
intakes = ShippingNoticeIntake.query.filter_by(user_id=int(session.user_id)).order_by(
|
||||
ShippingNoticeIntake.id.asc()
|
||||
).all()
|
||||
documents = ShippingNoticeDocument.query.filter(
|
||||
ShippingNoticeDocument.intake_id.in_([int(item.id) for item in intakes])
|
||||
).order_by(ShippingNoticeDocument.id.asc()).all()
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
return persist_order_extraction_result(
|
||||
session=session, intakes=intakes, documents=documents,
|
||||
current_snapshot=str(payload.get('input_snapshot_hash') or ''),
|
||||
request_id='test-order-extraction-shadow-run', orders=payload.get('orders'),
|
||||
run_id=None, schema_version_id=int(schema.id), extraction_source='test_shadow',
|
||||
auto_create_enabled=False,
|
||||
)
|
||||
|
||||
def _order(
|
||||
@@ -393,6 +413,33 @@ def _attach_existing_task_dynamic_order(task: ShippingTask) -> None:
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_order_field_display_uses_locked_schema_sequence(app):
|
||||
"""对话字段顺序必须来自任务锁定 Schema,且通用上下文不能混入订单信息。"""
|
||||
with app.app_context():
|
||||
_ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
fields = [dict(item) for item in (version.definition_json or {}).get('fields') or []]
|
||||
sequence_by_code = {'qty': 1, 'part_number': 2, 'reservation_id': 3, 'po_number': 4}
|
||||
for field in fields:
|
||||
field['sequence'] = sequence_by_code.get(str(field.get('field_code')), 99)
|
||||
version.definition_json = {**(version.definition_json or {}), 'fields': fields}
|
||||
task = ShippingTask(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
|
||||
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
db.session.commit()
|
||||
|
||||
display = current_order_field_display(task)
|
||||
|
||||
assert [item['field_code'] for item in display['header_fields']] == ['po_number']
|
||||
assert [item['field_code'] for item in display['line_fields']][:3] == [
|
||||
'qty', 'part_number', 'reservation_id',
|
||||
]
|
||||
|
||||
|
||||
def _add_extraction_intake(
|
||||
*,
|
||||
user: User,
|
||||
@@ -540,6 +587,34 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
|
||||
assert session.user_id == user.id
|
||||
|
||||
|
||||
def test_shadow_mode_persists_ready_candidate_without_creating_task(app):
|
||||
"""自动建单默认关闭时,合格订单只形成可审核 Candidate,不产生 Task。"""
|
||||
with app.app_context():
|
||||
user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
|
||||
payload = {
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'orders': [_order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
part_number='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=True,
|
||||
)],
|
||||
}
|
||||
|
||||
result = _persist_shadow_orders(payload)
|
||||
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert result['created_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled']
|
||||
assert candidate.validation_status == 'ready'
|
||||
assert candidate.selected is False
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app):
|
||||
"""空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_document_profile.py
|
||||
|
||||
用途:验证订单模板 Profile 精确结构匹配、列语义覆盖、复合 cell 和零数量门禁。
|
||||
依赖:document_layout.order_profile/html_table、冻结订单 Schema 表头契约。
|
||||
逻辑:使用合成模板证明特例不污染全局 Schema;结构不匹配或行关系丢失时显式阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
order_profile_structure_fingerprint,
|
||||
parse_html_table_with_order_profile,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _field(code: str, *, value_type: str = 'string', required: bool = False) -> dict:
|
||||
"""构造模板 Profile 执行所需的最小冻结字段配置。"""
|
||||
return {
|
||||
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
|
||||
'value_type': value_type, 'enabled': True, 'required': required,
|
||||
'display_name': code, 'aliases': [], 'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else [],
|
||||
'collection_mode': 'llm_extraction',
|
||||
}
|
||||
|
||||
|
||||
def _contract():
|
||||
"""创建覆盖行号、三料号和数量的冻结 Schema 契约。"""
|
||||
return compile_table_header_contract({'fields': [
|
||||
_field('line_no'), _field('customer_part_number'),
|
||||
_field('part_number', required=True), _field('aws_part_number'),
|
||||
_field('qty', value_type='decimal', required=True),
|
||||
]})
|
||||
|
||||
|
||||
def _profile(html: str, rules: list[OrderProfileColumnRule]) -> OrderDocumentProfile:
|
||||
"""从合成样本表头生成只用于测试的精确结构 Profile。"""
|
||||
grid = parse_html_grid(html, table_id='sample')
|
||||
return OrderDocumentProfile(
|
||||
profile_code='ORDER_TEMPLATE_A',
|
||||
version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0,
|
||||
data_start_row_index=1,
|
||||
column_rules=rules,
|
||||
)
|
||||
|
||||
|
||||
def test_template_profile_overrides_global_part_number_semantics_without_collision():
|
||||
"""特定模板可把 Part Number 与 Vendor Item 映射到客户/内部料号,不修改全局别名。"""
|
||||
html = (
|
||||
'<table><tr><th>LN</th><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
|
||||
'<tr><td>1</td><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr></table>'
|
||||
)
|
||||
profile = _profile(html, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['customer_part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=3, extractor_key='direct', target_field_codes=['qty']),
|
||||
])
|
||||
|
||||
result = parse_html_table_with_order_profile(
|
||||
html, table_id='runtime', profile=profile, contract=_contract(),
|
||||
)
|
||||
|
||||
assert result.matched is True
|
||||
assert result.rows[0].status == 'parsed'
|
||||
assert result.rows[0].fields == {
|
||||
'line_no': '1', 'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1', 'qty': 3.0,
|
||||
}
|
||||
|
||||
|
||||
def test_template_profile_extracts_registered_temp_and_internal_parts_from_composite_cell():
|
||||
"""已注册复合解析器可从单 cell 提取客户 TEMP 与内部 D4,描述文本不进入料号值。"""
|
||||
html = (
|
||||
'<table><tr><th>Line</th><th>Parts & Description</th><th>QTY</th></tr>'
|
||||
'<tr><td>10</td><td>AMTEMP-S000001 supplier D4-A08AR12000001 enclosure</td><td>2</td></tr></table>'
|
||||
)
|
||||
profile = _profile(html, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(
|
||||
column_index=1,
|
||||
extractor_key='temp_internal_parts',
|
||||
target_field_codes=['customer_part_number', 'part_number'],
|
||||
),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
|
||||
])
|
||||
|
||||
row = parse_html_table_with_order_profile(
|
||||
html, table_id='runtime', profile=profile, contract=_contract(),
|
||||
).rows[0]
|
||||
|
||||
assert row.status == 'parsed'
|
||||
assert row.fields['customer_part_number'] == 'AMTEMP-S000001'
|
||||
assert row.fields['part_number'] == 'D4-A08AR12000001'
|
||||
|
||||
|
||||
def test_template_profile_drops_explicit_zero_qty_row():
|
||||
"""管理员确认的零数量业务规则必须在模板解析入口删除整行。"""
|
||||
html = (
|
||||
'<table><tr><th>Vendor PN</th><th>Qty</th></tr>'
|
||||
'<tr><td>INTERNAL-ZERO</td><td>0 EA</td></tr></table>'
|
||||
)
|
||||
profile = _profile(html, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['qty']),
|
||||
])
|
||||
|
||||
row = parse_html_table_with_order_profile(
|
||||
html, table_id='runtime', profile=profile, contract=_contract(),
|
||||
).rows[0]
|
||||
|
||||
assert row.status == 'deleted'
|
||||
assert row.fields == {}
|
||||
|
||||
|
||||
def test_template_profile_requires_exact_structure_fingerprint():
|
||||
"""列数或表头变化时不得采用最相似模板或按旧位置解析。"""
|
||||
sample = '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>A</td><td>1</td></tr></table>'
|
||||
runtime = '<table><tr><th>Part</th><th>Description</th><th>Qty</th></tr><tr><td>A</td><td>X</td><td>1</td></tr></table>'
|
||||
profile = _profile(sample, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['qty']),
|
||||
])
|
||||
|
||||
result = parse_html_table_with_order_profile(
|
||||
runtime, table_id='runtime', profile=profile, contract=_contract(),
|
||||
)
|
||||
|
||||
assert result.matched is False
|
||||
assert result.rows == []
|
||||
assert result.issues == ['order_profile_structure_mismatch']
|
||||
|
||||
|
||||
def test_template_profile_routes_lost_row_structure_without_column_mapping():
|
||||
"""MinerU 已丢失订单行关系的模板只能识别并阻断,不能配置固定列伪装修复。"""
|
||||
html = '<table><tr><th>Item</th><th>Material</th></tr><tr><td>fragment</td><td>fragment</td></tr></table>'
|
||||
grid = parse_html_grid(html, table_id='lost')
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='LOST_ROW_TEMPLATE',
|
||||
version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0,
|
||||
data_start_row_index=1,
|
||||
row_structure='unsupported_row_structure',
|
||||
)
|
||||
|
||||
result = parse_html_table_with_order_profile(
|
||||
html, table_id='runtime', profile=profile, contract=_contract(),
|
||||
)
|
||||
|
||||
assert result.matched is True
|
||||
assert result.rows == []
|
||||
assert result.issues == ['order_profile_row_structure_unsupported']
|
||||
|
||||
|
||||
def test_template_profile_rejects_freeform_or_invalid_extractor_targets():
|
||||
"""Profile 只能引用注册 parser key 和固定输出字段,禁止自由代码/正则。"""
|
||||
with pytest.raises(ValidationError):
|
||||
OrderProfileColumnRule(
|
||||
column_index=0,
|
||||
extractor_key='custom_regex',
|
||||
target_field_codes=['part_number'],
|
||||
)
|
||||
with pytest.raises(ValidationError, match='targets are fixed'):
|
||||
OrderProfileColumnRule(
|
||||
column_index=0,
|
||||
extractor_key='temp_internal_parts',
|
||||
target_field_codes=['part_number'],
|
||||
)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""订单抽取进度事件的去重、并行归并与终态保护测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRun, User
|
||||
from app.services.shipping_notice.order_extraction_progress import MAPPING_VERSION, record_order_extraction_progress_event
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
cleanup_expired_order_extraction_progress_events,
|
||||
get_order_extraction_user_slow_threshold_seconds,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
|
||||
DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH,
|
||||
ensure_default_order_extraction_progress_cleanup_schedule,
|
||||
)
|
||||
|
||||
|
||||
def _run() -> ShippingOrderExtractionRun:
|
||||
"""创建不依赖订单输入的最小Run,专门验证进度投影。"""
|
||||
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',
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
def test_progress_events_dedupe_parallel_stages_and_protect_hxops_persistence(app):
|
||||
"""重复SSE不重复落库;并行阶段合并,持久化阶段不被迟到Dify节点覆盖。"""
|
||||
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'},
|
||||
) 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'},
|
||||
) 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'},
|
||||
) 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'},
|
||||
) 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 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'},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.current_stage_code == 'order_recognition'
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
def test_progress_mapping_version_fits_persisted_column(app):
|
||||
"""进度映射版本必须小于等于 Run 表列宽,避免状态投影反而导致订单失败。"""
|
||||
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-version'},
|
||||
) is True
|
||||
db.session.expire_all()
|
||||
persisted = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert len(MAPPING_VERSION) <= 32
|
||||
assert persisted.progress_mapping_version == MAPPING_VERSION
|
||||
|
||||
|
||||
def test_progress_event_discards_custom_node_title(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',
|
||||
'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)
|
||||
|
||||
|
||||
def test_terminal_run_records_diagnostics_without_mutating_projection(app):
|
||||
"""终态后的迟到节点只保留管理员审计,绝不把用户状态改回运行中。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
run.status = 'completed'
|
||||
run.current_stage_code = 'hxops_persistence'
|
||||
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
|
||||
db.session.expire_all()
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert run.status == 'completed'
|
||||
assert run.current_stage_code == 'hxops_persistence'
|
||||
assert run.progress_version == 9
|
||||
|
||||
|
||||
def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
|
||||
"""90天清理只删除到期进度明细,绝不删除业务 Run 或未到期事件。"""
|
||||
with app.app_context():
|
||||
run = _run()
|
||||
now = datetime.utcnow()
|
||||
expired = ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id, event_type='node_finished', stage_code='order_recognition', event_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',
|
||||
received_at=now, idempotency_key='retained-progress-event', expires_at=now + timedelta(days=1),
|
||||
)
|
||||
db.session.add_all([expired, retained])
|
||||
db.session.commit()
|
||||
|
||||
assert cleanup_expired_order_extraction_progress_events(now=now) == {'deleted_count': 1}
|
||||
assert db.session.get(ShippingOrderExtractionRun, run.id) is not None
|
||||
assert ShippingOrderExtractionProgressEvent.query.filter_by(id=retained.id).one() is not None
|
||||
|
||||
|
||||
def test_user_slow_threshold_uses_p95_after_minimum_samples_and_is_capped(app):
|
||||
"""慢响应阈值不足20样本回退60秒,满足样本后按P95且上限300秒。"""
|
||||
with app.app_context():
|
||||
assert get_order_extraction_user_slow_threshold_seconds() == 60
|
||||
base = datetime.utcnow() - timedelta(minutes=10)
|
||||
for index in range(20):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-SLOW-{index}', user_id=1, owner_agent_id=1, conversation_id=f'slow-{index}',
|
||||
schema_version_id=1, input_snapshot_hash=f'{index:064x}', input_snapshot_json={}, idempotency_key=f'{index + 100:064x}',
|
||||
status='completed', phase='completed', created_at=base, finished_at=base + timedelta(seconds=400 if index >= 18 else 90),
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
assert get_order_extraction_user_slow_threshold_seconds() == 300
|
||||
|
||||
|
||||
def test_progress_cleanup_default_schedule_is_idempotent(app):
|
||||
"""每日清理排程只补种一次,并绑定已注册的平台 Job。"""
|
||||
with app.app_context():
|
||||
db.session.add(User(username='cleanup-admin', email='cleanup-admin@example.com', role='admin', password_hash='x'))
|
||||
db.session.commit()
|
||||
first = ensure_default_order_extraction_progress_cleanup_schedule()
|
||||
second = ensure_default_order_extraction_progress_cleanup_schedule()
|
||||
assert first is not None
|
||||
assert second is not None
|
||||
assert first.id == second.id
|
||||
assert first.platform_api_path == DEFAULT_PROGRESS_CLEANUP_PLATFORM_PATH
|
||||
@@ -15,25 +15,34 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ConflictError, ForbiddenError, ValidationError
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentRuntimeBinding,
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
Job,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
mark_order_extraction_run_seen,
|
||||
retry_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
|
||||
def _seed_run_input(
|
||||
@@ -159,9 +168,21 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert run.input_snapshot_json['schema']['extraction_contract']['fields'][0]['field_id'] == 'qty-id'
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'][0]['document_id'] == document.id
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'] == 'PO 451883815A QTY 30 EA'
|
||||
# 确定性上下文保留在HXOPS冻结快照;Workflow编译时才从documents强制剔除。
|
||||
assert run.input_snapshot_json['intakes'][0]['deterministic_context'] == {
|
||||
'from_email': 'sales-a@example.com', 'from_domain': 'example.com',
|
||||
}
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one()
|
||||
assert plan.plan_version == 'shipping_order_extraction.plan.v1'
|
||||
assert len(plan.plan_version) == 33
|
||||
assert plan.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert plan.status == 'planned'
|
||||
assert plan.unit_count == 1
|
||||
unit = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).one()
|
||||
assert unit.document_id == document.id
|
||||
assert unit.intake_id == intake.id
|
||||
assert unit.unit_type == 'document_extraction'
|
||||
assert unit.status == 'pending'
|
||||
|
||||
replay, replayed = create_order_extraction_run(
|
||||
user=user,
|
||||
@@ -174,6 +195,90 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert replayed is True
|
||||
assert replay.id == run.id
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
assert ShippingOrderExtractionPlan.query.count() == 1
|
||||
assert ShippingOrderExtractionUnit.query.count() == 1
|
||||
|
||||
|
||||
def test_run_plan_creates_email_relation_and_attachment_units_in_frozen_order(app):
|
||||
"""邮件正文和附件必须成为彼此隔离、顺序稳定的计划单元。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, attachment = _seed_run_input(suffix='PLAN')
|
||||
body = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='email-body',
|
||||
filename=None,
|
||||
content_hash='b' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Email body relationship facts',
|
||||
)
|
||||
db.session.add(body)
|
||||
db.session.commit()
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one()
|
||||
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(
|
||||
ShippingOrderExtractionUnit.position.asc()
|
||||
).all()
|
||||
assert [unit.document_id for unit in units] == sorted([attachment.id, body.id])
|
||||
assert {unit.document_id: unit.unit_type for unit in units} == {
|
||||
attachment.id: 'document_extraction',
|
||||
body.id: 'email_relation',
|
||||
}
|
||||
assert all(unit.result_json is None and unit.error_code is None for unit in units)
|
||||
|
||||
|
||||
def test_plan_unit_state_machine_is_local_and_rolls_up_partial_failure(app):
|
||||
"""一个单元失败不得清除其他成功结果,计划仅在全部单元终态后汇总部分失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _attachment = _seed_run_input(suffix='STATE')
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='email-body',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Body relationship facts',
|
||||
))
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one()
|
||||
units = list(plan.units)
|
||||
|
||||
transition_order_extraction_unit(units[0], target_status='running')
|
||||
transition_order_extraction_unit(
|
||||
units[0], target_status='succeeded', result={'orders': [{'key': 'A'}]},
|
||||
)
|
||||
transition_order_extraction_unit(units[1], target_status='running')
|
||||
transition_order_extraction_unit(
|
||||
units[1], target_status='failed', error_code='UNIT_TIMEOUT', error_message='timeout',
|
||||
)
|
||||
|
||||
assert plan.status == 'partial_failed'
|
||||
assert units[0].result_json == {'orders': [{'key': 'A'}]}
|
||||
assert units[0].status == 'succeeded'
|
||||
assert units[1].status == 'failed'
|
||||
assert units[1].error_code == 'UNIT_TIMEOUT'
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
transition_order_extraction_unit(units[0], target_status='running')
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_TRANSITION_INVALID'
|
||||
|
||||
transition_order_extraction_unit(units[1], target_status='pending')
|
||||
assert plan.status == 'running'
|
||||
assert units[0].result_json == {'orders': [{'key': 'A'}]}
|
||||
|
||||
|
||||
def test_run_submission_rejects_changed_frozen_mail_context(app):
|
||||
@@ -210,6 +315,31 @@ def test_active_run_blocks_different_snapshot_for_same_intake(app):
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE'
|
||||
|
||||
|
||||
def test_active_run_blocks_different_intake_in_same_conversation(app):
|
||||
"""同一会话只能有一个活动 Run,防止不同附件的状态卡和工作台事实并行串扰。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='CONV-A')
|
||||
_, _, _, second_intake, _ = _seed_run_input(suffix='CONV-B')
|
||||
second_intake.user_id = user.id
|
||||
second_intake.conversation_id = session.session_id
|
||||
db.session.commit()
|
||||
|
||||
first, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[second_intake.intake_no],
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_ACTIVE'
|
||||
assert caught.value.details == {'run_no': first.run_no}
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
|
||||
@@ -240,6 +370,9 @@ def test_ten_integrity_races_reuse_database_winner(app):
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service._active_run_for_intakes',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service._active_run_for_conversation',
|
||||
return_value=None,
|
||||
), patch.object(
|
||||
db.session,
|
||||
'flush',
|
||||
@@ -336,10 +469,25 @@ def test_run_api_create_get_list_and_user_isolation(app, client):
|
||||
payload = response.get_json()['data']
|
||||
assert payload['reused'] is False
|
||||
assert payload['run']['status'] == 'queued'
|
||||
assert payload['run']['progress'] == {
|
||||
'version': 1,
|
||||
'current_stage_code': 'queued',
|
||||
'active_stage_codes': [],
|
||||
'completed_stage_codes': [],
|
||||
'message_code': None,
|
||||
'health': 'normal',
|
||||
'last_activity_at': None,
|
||||
}
|
||||
assert 'input_snapshot_json' not in payload['run']
|
||||
assert 'provider_snapshot_json' not in payload['run']
|
||||
assert 'provider_result_json' not in payload['run']
|
||||
assert 'provider_config_json' not in payload['run']
|
||||
serialized = str(payload['run']).lower()
|
||||
for forbidden_key in (
|
||||
'workflow_run_id', 'node_execution_id', 'node_type', 'node_title',
|
||||
'job_id', 'provider_agent_id', 'provider_snapshot', 'prompt',
|
||||
):
|
||||
assert forbidden_key not in serialized
|
||||
run_no = payload['run']['run_no']
|
||||
|
||||
replay = client.post(
|
||||
@@ -364,6 +512,441 @@ def test_run_api_create_get_list_and_user_isolation(app, client):
|
||||
assert hidden.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND'
|
||||
|
||||
|
||||
def test_run_progress_events_api_returns_only_generic_stages(app, client):
|
||||
"""用户进度明细只返回通用阶段、状态和时间,且继续执行 Run 所有权隔离。"""
|
||||
from app.models import ShippingOrderExtractionProgressEvent
|
||||
|
||||
with app.app_context():
|
||||
owner, agent, session, intake, _document = _seed_run_input(suffix='PROGRESS-API')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
other = User(username='progress-other', email='progress-other@example.com', password_hash='x')
|
||||
db.session.add(other)
|
||||
db.session.add(ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id,
|
||||
job_id=run.current_job_id,
|
||||
workflow_run_id='wf-secret',
|
||||
node_execution_id='node-secret',
|
||||
event_type='node_started',
|
||||
node_type='llm',
|
||||
stage_code='order_recognition',
|
||||
event_status='running',
|
||||
received_at=datetime.utcnow(),
|
||||
details_json={'source': 'dify_workflow_observer'},
|
||||
idempotency_key='progress-api-key',
|
||||
))
|
||||
db.session.commit()
|
||||
owner_token = issue_local_access_token(owner)
|
||||
other_token = issue_local_access_token(other)
|
||||
run_no = run.run_no
|
||||
|
||||
response = client.get(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/progress-events',
|
||||
headers={'Authorization': f'Bearer {owner_token}'},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
items = response.get_json()['data']['items']
|
||||
assert len(items) == 1
|
||||
assert set(items[0]) == {'stage_code', 'status', 'occurred_at'}
|
||||
assert items[0]['stage_code'] == 'order_recognition'
|
||||
assert items[0]['status'] == 'running'
|
||||
assert 'secret' not in str(items).lower()
|
||||
|
||||
hidden = client.get(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/progress-events',
|
||||
headers={'Authorization': f'Bearer {other_token}'},
|
||||
)
|
||||
assert hidden.status_code == 404
|
||||
|
||||
|
||||
def test_run_progress_health_is_computed_server_side(app):
|
||||
"""用户摘要按最后活动时间投影 idle/slow,不信任浏览器本地时间或前端状态。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='PROGRESS-HEALTH')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
run.status = 'running'
|
||||
run.last_activity_at = now - timedelta(seconds=60)
|
||||
assert serialize_order_extraction_run(run)['progress']['health'] == 'idle'
|
||||
|
||||
run.last_activity_at = now - timedelta(seconds=180)
|
||||
assert serialize_order_extraction_run(run)['progress']['health'] == 'slow'
|
||||
|
||||
run.status = 'completed'
|
||||
assert serialize_order_extraction_run(run)['progress']['health'] == 'normal'
|
||||
|
||||
|
||||
def test_terminal_run_attention_is_new_only_seen_idempotently_and_resets_on_retry(app):
|
||||
"""终态才生成提醒;确认幂等,失败重试清除旧周期并为下一次终态重新生成提醒。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='ATTENTION')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
# 已存在的历史终态没有提醒标记,不会因新代码读取而补发。
|
||||
historical = ShippingOrderExtractionRun(
|
||||
run_no='SNER-HISTORICAL-ATTENTION', user_id=user.id, owner_agent_id=agent.id,
|
||||
conversation_id='historical-conversation', schema_version_id=run.schema_version_id,
|
||||
input_snapshot_hash='c' * 64, input_snapshot_json={}, idempotency_key='d' * 64,
|
||||
status='completed', phase='completed', finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(historical)
|
||||
db.session.flush()
|
||||
assert mark_order_extraction_run_seen(user_id=user.id, run_no=historical.run_no) is False
|
||||
assert historical.attention_generated_at is None
|
||||
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable')
|
||||
assert run.attention_generated_at is not None
|
||||
assert run.seen_at is None
|
||||
assert mark_order_extraction_run_seen(user_id=user.id, run_no=run.run_no) is True
|
||||
assert run.seen_at is not None
|
||||
assert mark_order_extraction_run_seen(user_id=user.id, run_no=run.run_no) is False
|
||||
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
job.status = 'failed'
|
||||
db.session.flush()
|
||||
retried, _ = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
assert retried.attention_generated_at is None
|
||||
assert retried.seen_at is None
|
||||
transition_order_extraction_run(retried, target_status='running')
|
||||
transition_order_extraction_run(retried, target_status='result_persisted', result={})
|
||||
transition_order_extraction_run(retried, target_status='completed')
|
||||
assert retried.attention_generated_at is not None
|
||||
assert retried.seen_at is None
|
||||
|
||||
|
||||
def test_run_seen_api_keeps_cross_user_isolation(app, client):
|
||||
"""确认接口只能确认本人终态 Run,活动 Run 请求保持无副作用。"""
|
||||
with app.app_context():
|
||||
owner, agent, session, intake, _document = _seed_run_input(suffix='SEEN-API')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(run, target_status='result_persisted', result={})
|
||||
transition_order_extraction_run(run, target_status='completed')
|
||||
other = User(username='seen-other', email='seen-other@example.com', password_hash='x')
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
owner_token = issue_local_access_token(owner)
|
||||
other_token = issue_local_access_token(other)
|
||||
run_no = run.run_no
|
||||
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/seen',
|
||||
headers={'Authorization': f'Bearer {owner_token}'},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()['data'] == {'seen': True}
|
||||
replay = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/seen',
|
||||
headers={'Authorization': f'Bearer {owner_token}'},
|
||||
)
|
||||
assert replay.get_json()['data'] == {'seen': False}
|
||||
hidden = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/seen',
|
||||
headers={'Authorization': f'Bearer {other_token}'},
|
||||
)
|
||||
assert hidden.status_code == 404
|
||||
|
||||
|
||||
def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app):
|
||||
"""侧栏只聚合同用户同Agent的新提醒,并把失败优先级提升到 error。"""
|
||||
from app.api.chat import _order_extraction_attention_by_conversation
|
||||
|
||||
with app.app_context():
|
||||
owner, agent, session, intake, _document = _seed_run_input(suffix='SESSION-ATTENTION')
|
||||
ignored_agent = Agent(
|
||||
name='Other owner', agent_code='generic', runtime_provider='dify', dify_app_id='other-owner',
|
||||
dify_api_key='key', is_active=True,
|
||||
)
|
||||
db.session.add(ignored_agent)
|
||||
db.session.flush()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable')
|
||||
historical = ShippingOrderExtractionRun(
|
||||
run_no='SNER-HISTORICAL-SESSION', user_id=owner.id, owner_agent_id=agent.id,
|
||||
conversation_id=session.session_id, schema_version_id=run.schema_version_id,
|
||||
input_snapshot_hash='e' * 64, input_snapshot_json={}, idempotency_key='f' * 64,
|
||||
status='completed', phase='completed', finished_at=datetime.utcnow(),
|
||||
)
|
||||
other_owner_run = ShippingOrderExtractionRun(
|
||||
run_no='SNER-OTHER-OWNER', user_id=owner.id, owner_agent_id=ignored_agent.id,
|
||||
conversation_id=session.session_id, schema_version_id=run.schema_version_id,
|
||||
input_snapshot_hash='g' * 64, input_snapshot_json={}, idempotency_key='h' * 64,
|
||||
status='completed', phase='completed', finished_at=datetime.utcnow(), attention_generated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add_all([historical, other_owner_run])
|
||||
db.session.commit()
|
||||
aggregate = _order_extraction_attention_by_conversation(
|
||||
user_id=owner.id,
|
||||
agent_id=agent.id,
|
||||
conversation_ids={session.session_id},
|
||||
)
|
||||
|
||||
assert aggregate == {session.session_id: (1, 'error')}
|
||||
|
||||
|
||||
def test_failed_run_retry_reuses_snapshot_and_provider_result(app):
|
||||
"""手工重试复用同一 Run/快照/Provider 缓存,只创建新的执行 Job。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='RETRY')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
original_job_id = run.current_job_id
|
||||
frozen_snapshot = run.input_snapshot_json
|
||||
run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-cached'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', error_code='TEST.FAILED', error_message='failed once',
|
||||
)
|
||||
original_job = db.session.get(Job, original_job_id)
|
||||
original_job.status = 'failed'
|
||||
db.session.commit()
|
||||
|
||||
retried, reused = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
|
||||
assert reused is False
|
||||
assert retried.id == run.id
|
||||
assert retried.status == 'queued'
|
||||
assert retried.phase == 'manual_retry_queued'
|
||||
assert retried.current_job_id != original_job_id
|
||||
assert retried.input_snapshot_json == frozen_snapshot
|
||||
assert retried.provider_result_json == {'orders': [], 'workflow': {'workflow_run_id': 'wf-cached'}}
|
||||
assert retried.error_code is None
|
||||
assert intake.order_extraction_status == 'extracting'
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
assert Job.query.filter_by(business_ref=run.run_no).count() == 2
|
||||
|
||||
replay, replayed = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
assert replayed is True
|
||||
assert replay.current_job_id == retried.current_job_id
|
||||
assert Job.query.filter_by(business_ref=run.run_no).count() == 2
|
||||
|
||||
|
||||
def test_run_retry_rejects_non_failed_status_and_other_user(app):
|
||||
"""非 failed 状态不能重试,跨用户仍统一表现为 Run 不存在。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='RETRY-GATE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
other = User(username='retry-other', email='retry-other@example.com', password_hash='x')
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as invalid:
|
||||
retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
assert invalid.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_RETRYABLE'
|
||||
|
||||
with pytest.raises(NotFoundError) as hidden:
|
||||
retry_order_extraction_run(user_id=other.id, run_no=run.run_no)
|
||||
assert getattr(hidden.value, 'code', None) == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND'
|
||||
|
||||
|
||||
def test_run_retry_rejects_obsolete_frozen_snapshot(app):
|
||||
"""旧 Run 缺少当前必需的冻结上下文时必须新建识别,禁止重试后在落库阶段必然失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='RETRY-OBSOLETE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
snapshot['intakes'] = [dict(item) for item in snapshot['intakes']]
|
||||
snapshot['intakes'][0].pop('deterministic_context')
|
||||
run.input_snapshot_json = snapshot
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='legacy snapshot')
|
||||
original_job_count = Job.query.filter_by(business_ref=run.run_no).count()
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'
|
||||
assert run.status == 'failed'
|
||||
assert Job.query.filter_by(business_ref=run.run_no).count() == original_job_count
|
||||
|
||||
|
||||
def test_terminal_transition_updates_persisted_chat_state(app):
|
||||
"""Run 终态必须在同一事务覆盖聊天卡,刷新历史不能继续显示识别中。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-TERMINAL')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=session.session_id,
|
||||
conversation_id=session.session_id,
|
||||
query='',
|
||||
answer='',
|
||||
message_type='text',
|
||||
payload={
|
||||
'formId': f'shipping-order-extraction-run:{run.run_no}',
|
||||
'order_extraction_run_no': run.run_no,
|
||||
'shipping_order_extraction_state': {'status': 'extracting', 'terminal': False},
|
||||
},
|
||||
)
|
||||
db.session.add(log)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
error_code='TEST.FAILED',
|
||||
error_message='failed once',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(log)
|
||||
assert log.payload['shipping_order_extraction_state']['status'] == 'failed'
|
||||
assert log.payload['shipping_order_extraction_state']['terminal'] is True
|
||||
assert log.payload['shipping_order_extraction_state']['message'] == 'failed once'
|
||||
|
||||
|
||||
def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client):
|
||||
"""终态后晚到的旧卡必须在历史 GET 时按 Run 事实纠正,不能永久显示运行中。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-HISTORY')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
error_code='TEST.FAILED',
|
||||
error_message='failed before card persisted',
|
||||
)
|
||||
db.session.add(ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=session.session_id,
|
||||
conversation_id=session.session_id,
|
||||
query='',
|
||||
answer='',
|
||||
message_type='text',
|
||||
payload={
|
||||
'formId': f'shipping-order-extraction-run:{run.run_no}',
|
||||
'order_extraction_run_no': run.run_no,
|
||||
'shipping_order_extraction_state': {'status': 'extracting', 'terminal': False},
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
session_id = session.session_id
|
||||
agent_id = agent.id
|
||||
|
||||
response = client.get(
|
||||
f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}',
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
state = response.get_json()[-1]['payload']['shipping_order_extraction_state']
|
||||
assert state['status'] == 'failed'
|
||||
assert state['terminal'] is True
|
||||
assert state['message'] == 'failed before card persisted'
|
||||
|
||||
|
||||
def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client):
|
||||
"""同一 Run 的上传记录与状态记录共存时,历史回放只能出现一张助手状态卡。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-DEDUPLICATE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='failed once')
|
||||
db.session.add_all([
|
||||
ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=session.session_id,
|
||||
conversation_id=session.session_id,
|
||||
query='上传附件',
|
||||
answer='',
|
||||
message_type='text',
|
||||
payload={
|
||||
'formId': f'shipping-order-extraction-user:{run.run_no}',
|
||||
'order_extraction_run_no': run.run_no,
|
||||
},
|
||||
),
|
||||
ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=session.session_id,
|
||||
conversation_id=session.session_id,
|
||||
query='',
|
||||
answer='',
|
||||
message_type='text',
|
||||
payload={
|
||||
'formId': f'shipping-order-extraction-run:{run.run_no}',
|
||||
'order_extraction_run_no': run.run_no,
|
||||
},
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
run_no = run.run_no
|
||||
session_id = session.session_id
|
||||
agent_id = agent.id
|
||||
|
||||
response = client.get(
|
||||
f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}',
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
messages = response.get_json()
|
||||
state_cards = [
|
||||
item for item in messages
|
||||
if item['role'] == 'assistant'
|
||||
and item.get('payload', {}).get('order_extraction_run_no') == run_no
|
||||
]
|
||||
assert len(state_cards) == 1
|
||||
assert state_cards[0]['payload']['shipping_order_extraction_state']['status'] == 'failed'
|
||||
assert [item['role'] for item in messages] == ['user', 'assistant']
|
||||
|
||||
|
||||
def test_failed_run_retry_api_returns_queued_run(app, client):
|
||||
"""用户点击重新识别后 API 返回 202,并原位恢复同一 Run。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='RETRY-API')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='workflow failed')
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
run_no = run.run_no
|
||||
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/retry',
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
|
||||
assert response.status_code == 202
|
||||
payload = response.get_json()['data']
|
||||
assert payload['reused'] is False
|
||||
assert payload['run']['run_no'] == run_no
|
||||
assert payload['run']['status'] == 'queued'
|
||||
assert payload['run']['phase'] == 'manual_retry_queued'
|
||||
|
||||
|
||||
def test_run_api_rejects_non_object_json(app, client):
|
||||
"""请求体为 JSON 数组时应返回标准 400,而不是调用 `.get` 产生 500。"""
|
||||
with app.app_context():
|
||||
@@ -526,9 +1109,7 @@ def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app):
|
||||
assert report['health_status'] == 'degraded'
|
||||
assert report['counts']['stale'] == 1
|
||||
assert report['status_counts']['queued'] == 1
|
||||
assert report['stale_runs'] == [{
|
||||
'run_no': run.run_no, 'status': 'queued', 'phase': 'queued', 'attempt_count': 0,
|
||||
}]
|
||||
assert report['stale_run_nos'] == [run.run_no]
|
||||
assert 'error_message' not in str(report)
|
||||
assert 'provider_snapshot' not in str(report)
|
||||
|
||||
@@ -561,6 +1142,7 @@ def test_order_extraction_health_calculates_segments_and_failure_rate(app):
|
||||
assert report['latency']['hxops_persistence']['avg_ms'] == 2000
|
||||
assert report['latency']['total']['avg_ms'] == 7000
|
||||
assert report['error_code_counts'] == {'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT': 1}
|
||||
assert report['thresholds']['user_slow_response_seconds'] >= 60
|
||||
|
||||
|
||||
def test_order_extraction_health_api_is_admin_only_and_validates_params(app, client):
|
||||
@@ -580,3 +1162,50 @@ def test_order_extraction_health_api_is_admin_only_and_validates_params(app, cli
|
||||
response = client.get('/api/admin/shipping-notice/order-extraction-runs/health?window_hours=24', headers={'Authorization': f'Bearer {admin_token}'})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()['success'] is True
|
||||
|
||||
|
||||
def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(app, client):
|
||||
"""管理员诊断只给安全元数据并留痕,普通用户不得读取任意 Run 或上游正文。"""
|
||||
with app.app_context():
|
||||
owner, agent, session, intake, _document = _seed_run_input(suffix='DIAGNOSTIC')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.dify_workflow_run_id = 'wf-diagnostic'
|
||||
run.provider_snapshot_json = {'prompt': 'must not leak'}
|
||||
run.provider_result_json = {'raw_output': 'must not leak'}
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', error_code='UPSTREAM.TIMEOUT', error_message='secret provider stack trace',
|
||||
)
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
job.error_message = 'secret job error'
|
||||
job.payload_json = {'documents': 'secret document body'}
|
||||
job_id = job.id
|
||||
admin = User(username='diagnostic-admin', email='diagnostic-admin@example.com', role='admin', password_hash='x')
|
||||
normal = User(username='diagnostic-normal', email='diagnostic-normal@example.com', role='user', password_hash='x')
|
||||
db.session.add_all([admin, normal])
|
||||
db.session.commit()
|
||||
admin_token = issue_local_access_token(admin)
|
||||
normal_token = issue_local_access_token(normal)
|
||||
run_no = run.run_no
|
||||
|
||||
forbidden = client.get('/api/admin/shipping-notice/order-extraction-runs', headers={'Authorization': f'Bearer {normal_token}'})
|
||||
assert forbidden.status_code == 403
|
||||
listed = client.get('/api/admin/shipping-notice/order-extraction-runs?page=1&page_size=25', headers={'Authorization': f'Bearer {admin_token}'})
|
||||
assert listed.status_code == 200
|
||||
listing = listed.get_json()['data']
|
||||
summary = next(item for item in listing['items'] if item['run_no'] == run_no)
|
||||
assert summary['workflow_run_id'] == 'wf-diagnostic'
|
||||
serialized_listing = str(listing).lower()
|
||||
for forbidden_text in ('must not leak', 'secret provider', 'secret job', 'documents', 'prompt', 'raw_output'):
|
||||
assert forbidden_text not in serialized_listing
|
||||
|
||||
detail = client.get(f'/api/admin/shipping-notice/order-extraction-runs/{run_no}', headers={'Authorization': f'Bearer {admin_token}'})
|
||||
assert detail.status_code == 200
|
||||
payload = detail.get_json()['data']
|
||||
assert payload['run']['error_code'] == 'UPSTREAM.TIMEOUT'
|
||||
assert payload['job_attempts'][0]['job_id'] == job_id
|
||||
assert str(payload).lower().count('secret') == 0
|
||||
with app.app_context():
|
||||
assert ShippingOrderExtractionDiagnosticAudit.query.filter_by(admin_user_id=admin.id).count() == 2
|
||||
@@ -470,6 +470,52 @@ def test_order_schema_draft_save_replaces_previous_field_configs(app):
|
||||
assert saved['definition']['fields'][0]['field_id'] == po['id']
|
||||
|
||||
|
||||
def test_order_schema_draft_save_preserves_submitted_field_order(app):
|
||||
"""拖拽后的数组顺序保存并重新读取后必须保持不变。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
first = service.save_field({
|
||||
'field_code': 'first_header', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
second = service.save_field({
|
||||
'field_code': 'second_header', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
first_config = _field_config(first['id'], name='第一字段')
|
||||
second_config = _field_config(second['id'], name='第二字段')
|
||||
for config in (first_config, second_config):
|
||||
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
|
||||
|
||||
saved = _save_draft(draft['id'], [second_config, first_config])
|
||||
reloaded_row = db.session.get(ShippingOrderSchemaVersion, draft['id'])
|
||||
assert reloaded_row is not None
|
||||
reloaded_fields = (reloaded_row.definition_json or {}).get('fields') or []
|
||||
|
||||
expected = [second['id'], first['id']]
|
||||
assert [item['field_id'] for item in saved['definition']['fields']] == expected
|
||||
assert [item['field_id'] for item in reloaded_fields] == expected
|
||||
assert [item['sequence'] for item in reloaded_fields] == [1, 2]
|
||||
|
||||
|
||||
def test_order_field_global_order_persists_without_schema_draft(app):
|
||||
"""字段目录顺序独立保存,刷新管理状态后仍保持且不创建草稿。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
first = service.save_field({
|
||||
'field_code': 'first_header', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
second = service.save_field({
|
||||
'field_code': 'second_header', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
|
||||
service.reorder_fields({'field_ids': [second['id'], first['id']]}, actor_id=None)
|
||||
refreshed = service.get_state()
|
||||
|
||||
assert [item['id'] for item in refreshed['fields']] == [second['id'], first['id']]
|
||||
assert [item['display_sequence'] for item in refreshed['fields']] == [1, 2]
|
||||
assert not any(item['status'] == 'draft' for item in refreshed['versions'])
|
||||
|
||||
|
||||
def test_order_schema_draft_uses_optimistic_lock_and_writes_audit(app):
|
||||
"""过期锁版本必须拒绝覆盖,成功保存和发布均产生不可变审计事件。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
FileAsset, ShippingContextProvider, ShippingContextProviderOption, ShippingNoticeDocument,
|
||||
ShippingNoticeIntake, ShippingOrderExtraction, ShippingOrderFieldDecision,
|
||||
@@ -19,6 +20,8 @@ from app.models import (
|
||||
from app.services.shipping_notice.context_fields.runtime import persist_deterministic_context_fields
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
|
||||
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _config(field_id: str, name: str, *, value_type: str) -> dict:
|
||||
@@ -67,6 +70,119 @@ def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
|
||||
)
|
||||
|
||||
|
||||
def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
"""草稿保存阶段即应拒绝不同字段占用同一标准化表头,避免歧义进入发布版本。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
customer = service.save_field({'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
first = _config(part['id'], '内部料号', value_type='string')
|
||||
first['aliases'] = ['Customer P/N']
|
||||
second = _config(customer['id'], '客户料号', value_type='string')
|
||||
second['aliases'] = ['customer p n']
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
service.save_draft(draft['id'], {
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
|
||||
|
||||
def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
"""新版本改动别名后,锁定旧版本的 Run 仍必须按旧 definition 解析后端表格。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
first_draft = service.create_draft({}, actor_id=None)
|
||||
first_part = _config(part['id'], '内部料号', value_type='string')
|
||||
first_part['aliases'] = ['Legacy SKU']
|
||||
first_qty = _config(qty['id'], '数量', value_type='decimal')
|
||||
first_qty['aliases'] = ['Legacy Qty']
|
||||
first = _save_and_publish(first_draft, [first_part, first_qty])
|
||||
|
||||
second_draft = service.create_draft({}, actor_id=None)
|
||||
second_part = _config(part['id'], '内部料号', value_type='string')
|
||||
second_part['aliases'] = ['Current SKU']
|
||||
second_qty = _config(qty['id'], '数量', value_type='decimal')
|
||||
second_qty['aliases'] = ['Current Qty']
|
||||
_save_and_publish(second_draft, [second_part, second_qty])
|
||||
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
documents[1].extracted_text = 'Legacy SKU\tLegacy Qty\nPART-FROZEN\t4'
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
|
||||
frozen_version = db.session.get(ShippingOrderSchemaVersion, first['id'])
|
||||
frozen_contract = compile_table_header_contract(frozen_version.definition_json or {})
|
||||
assert frozen_contract.header_to_field['legacy sku'] == 'part_number'
|
||||
assert parse_notice_table_text(documents[1].extracted_text, contract=frozen_contract) == [{
|
||||
'part_number': 'PART-FROZEN', 'qty': 4.0,
|
||||
}]
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': first['id'], 'schema_checksum': first['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{
|
||||
'field_id': qty['id'],
|
||||
'observations': [{
|
||||
'value': 4, 'document_id': documents[1].id,
|
||||
'quote': 'Legacy Qty\nPART-FROZEN\t4', 'confidence': 0.9,
|
||||
}],
|
||||
}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='f' * 64, documents=documents,
|
||||
actor_id=actor_id, schema_version_id=first['id'],
|
||||
)
|
||||
|
||||
assert result['lines'][0]['part_number'] == 'PART-FROZEN'
|
||||
assert result['lines'][0]['qty'] == '4'
|
||||
assert result['blocked_fields'] == []
|
||||
|
||||
|
||||
def test_duplicate_table_columns_force_dynamic_run_review(app):
|
||||
"""一个文档中同一字段命中多个列时,即使 LLM 有值也必须保留结果并强制复核。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
part_config = _config(part['id'], '内部料号', value_type='string')
|
||||
part_config['aliases'] = ['MPN', 'Part Number']
|
||||
qty_config = _config(qty['id'], '数量', value_type='decimal')
|
||||
qty_config['aliases'] = ['Qty']
|
||||
published = _save_and_publish(draft, [part_config, qty_config])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
documents[1].extracted_text = 'MPN\tPart Number\tQty\nA-1\tB-2\t3'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': part['id'], 'observations': [{
|
||||
'value': 'A-1', 'document_id': documents[1].id, 'quote': 'A-1', 'confidence': 0.9,
|
||||
}]},
|
||||
{'field_id': qty['id'], 'observations': [{
|
||||
'value': 3, 'document_id': documents[1].id, 'quote': 'Qty\nA-1\tB-2\t3', 'confidence': 0.9,
|
||||
}]},
|
||||
]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='e' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert result['lines'][0]['part_number'] == 'A-1'
|
||||
assert 'part_number' in result['blocked_fields']
|
||||
assert result['extraction'].status == 'needs_review'
|
||||
assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == {
|
||||
'document_id': int(documents[1].id),
|
||||
'reason': 'ambiguous_table_headers',
|
||||
'field_codes': ['part_number'],
|
||||
}
|
||||
|
||||
|
||||
def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]:
|
||||
"""创建同一 Intake 下的邮件正文和 PDF Document,供跨文档证据验证。"""
|
||||
user = User(username='dynamic-runtime', email='dynamic-runtime@example.com', password_hash='x')
|
||||
@@ -498,4 +614,4 @@ def test_dynamic_schema_accepts_equivalent_number_and_date_evidence_formats(app)
|
||||
|
||||
# 断言格式化差异不会阻断三类字段,但每条证据仍必须引用当前文档中的原文片段。
|
||||
assert result['blocked_fields'] == []
|
||||
assert result['lines'] == [{'qty': '30.0', 'amount': '28252.8', 'required_date': '2026-06-29'}]
|
||||
assert result['lines'] == [{'qty': '30', 'amount': '28252.8', 'required_date': '2026-06-29'}]
|
||||
Reference in new issue
Block a user