304 lines
15 KiB
Python
304 lines
15 KiB
Python
"""
|
|
用途:验证规则集驱动的客户影子识别、订单字段裁决门禁和客户/站点隔离。
|
|
依赖:身份规则服务、受控订单 FieldValue、Candidate/Intake 与客户主数据。
|
|
逻辑:仅已发布定义和 accepted/corroborated Header 值可进入候选;影子结果只记录审计,绝不绑定业务单。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.models import (
|
|
FileAsset,
|
|
ShippingCase,
|
|
ShippingCustomer,
|
|
ShippingCustomerShadowMatch,
|
|
ShippingCustomerShadowResolution,
|
|
ShippingCustomerSite,
|
|
ShippingNoticeCandidate,
|
|
ShippingNoticeDocument,
|
|
ShippingNoticeIntake,
|
|
ShippingOrderExtraction,
|
|
ShippingOrderField,
|
|
ShippingOrderFieldDecision,
|
|
ShippingOrderFieldValue,
|
|
ShippingOrderSchema,
|
|
ShippingOrderSchemaVersion,
|
|
User,
|
|
)
|
|
from app.services.shipping_notice.customer_shadow_resolution import (
|
|
get_shadow_quality_report,
|
|
label_shadow_resolution,
|
|
refresh_candidate_shadow_resolution,
|
|
)
|
|
from app.services.shipping_notice.identity_rules import service as identity_rules
|
|
|
|
|
|
def _seed_candidate(*, sender: str = '', document_text: str = 'Order template for supplied goods'):
|
|
"""创建带邮件元数据、主文档和 Candidate 的最小影子识别上下文。"""
|
|
user = User(username=f'shadow-{db.session.query(User).count()}', email=f'{db.session.query(User).count()}@example.com', role='user')
|
|
db.session.add(user)
|
|
db.session.flush()
|
|
asset = FileAsset(
|
|
asset_no=f'FA-{user.id}', owner_user_id=user.id, original_filename='notice.eml',
|
|
storage_provider='minio', storage_bucket='test', storage_key=f'notice-{user.id}',
|
|
content_hash=f'{user.id:064d}', file_size=1, upload_status='uploaded', lifecycle_status='temporary',
|
|
)
|
|
db.session.add(asset)
|
|
db.session.flush()
|
|
intake = ShippingNoticeIntake(
|
|
intake_no=f'SNI-{user.id}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
|
|
structured_result_json={'email': {'from': sender}},
|
|
)
|
|
db.session.add(intake)
|
|
db.session.flush()
|
|
document = ShippingNoticeDocument(
|
|
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
|
|
filename='notice.pdf', classification='order_notice', parse_status='parsed', extracted_text=document_text,
|
|
)
|
|
db.session.add(document)
|
|
db.session.flush()
|
|
candidate = ShippingNoticeCandidate(
|
|
candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id,
|
|
candidate_key='document:1', validation_status='ready',
|
|
structured_result_json={'business_summary': {'customer_name': 'RAW LLM VALUE MUST NOT BE USED'}},
|
|
)
|
|
db.session.add(candidate)
|
|
db.session.flush()
|
|
return intake, candidate
|
|
|
|
|
|
def _published_header_field(*, field_code: str, value_type: str = 'string'):
|
|
"""建立当前已发布 Header 字段,作为业务识别定义唯一合法来源。"""
|
|
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
|
if schema is None:
|
|
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
|
db.session.add(schema)
|
|
db.session.flush()
|
|
field = ShippingOrderField(schema_id=schema.id, field_code=field_code, scope='header', value_type=value_type)
|
|
db.session.add(field)
|
|
db.session.flush()
|
|
current = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='published').one_or_none()
|
|
if current is not None:
|
|
current.status = 'retired'
|
|
version = ShippingOrderSchemaVersion(
|
|
schema_id=schema.id,
|
|
version=(db.session.query(ShippingOrderSchemaVersion).filter_by(schema_id=schema.id).count() + 1),
|
|
status='published', lock_version=1,
|
|
definition_json={'fields': [{
|
|
'field_id': field.id, 'field_code': field.field_code, 'scope': 'header',
|
|
'value_type': value_type, 'enabled': True,
|
|
}]},
|
|
)
|
|
db.session.add(version)
|
|
db.session.flush()
|
|
return field, version
|
|
|
|
|
|
def _publish_rule_set(*, definition_ids: list[str] | None = None):
|
|
"""发布测试规则集;运行时只读取该不可变快照而非当前定义表。"""
|
|
draft = identity_rules.create_rule_set({}, actor_id=1)
|
|
ids = definition_ids or [item['id'] for item in identity_rules.list_definitions(active_only=True)['definitions']]
|
|
saved = identity_rules.save_rule_set(draft['id'], {
|
|
'expected_lock_version': draft['lock_version'], 'definition_ids': ids,
|
|
}, actor_id=1)
|
|
return identity_rules.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
|
|
|
|
|
def _attach_header_value(candidate, version, field, value: str, status: str = 'accepted'):
|
|
"""写入受控订单抽取、裁决和 Header FieldValue,模拟运行期唯一允许的业务证据来源。"""
|
|
extraction = ShippingOrderExtraction(
|
|
intake_id=candidate.intake_id, schema_version_id=version.id, input_snapshot_hash='a' * 64,
|
|
status='accepted', raw_llm_output_json={'header_fields': [{'value': 'ATTACKER CONTROLLED'}]},
|
|
)
|
|
db.session.add(extraction)
|
|
db.session.flush()
|
|
decision = ShippingOrderFieldDecision(
|
|
extraction_id=extraction.id, field_id=field.id, decision_status=status, resolved_value_json=value,
|
|
)
|
|
db.session.add(decision)
|
|
db.session.flush()
|
|
db.session.add(ShippingOrderFieldValue(
|
|
extraction_id=extraction.id, field_id=field.id, decision_id=decision.id, value_text=value,
|
|
))
|
|
candidate.order_extraction_id = extraction.id
|
|
db.session.flush()
|
|
return extraction
|
|
|
|
|
|
def _create_customer(name: str, code: str) -> ShippingCustomer:
|
|
"""创建启用客户并返回 ORM 记录。"""
|
|
customer = ShippingCustomer(standard_name=name, short_code=code, status='active')
|
|
db.session.add(customer)
|
|
db.session.flush()
|
|
return customer
|
|
|
|
|
|
def _email_definition(code: str = 'sender_email') -> dict:
|
|
"""创建管理员配置的 EML 发件人邮箱定义。"""
|
|
return identity_rules.save_definition({
|
|
'definition_code': code, 'target_type': 'customer', 'attribute_key': 'email',
|
|
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'default_weight': 100,
|
|
'max_automation': 'conditional', 'source_adapter_key': 'email_metadata',
|
|
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
|
}, actor_id=1)
|
|
|
|
|
|
def _template_definition(code: str = 'notice_template') -> dict:
|
|
"""创建管理员配置的主文档模板指纹定义。"""
|
|
return identity_rules.save_definition({
|
|
'definition_code': code, 'target_type': 'customer', 'attribute_key': 'template_fingerprint',
|
|
'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact', 'default_weight': 90,
|
|
'max_automation': 'conditional', 'source_adapter_key': 'document_template',
|
|
'source_selector': {'document': 'primary'},
|
|
}, actor_id=1)
|
|
|
|
|
|
def test_shadow_resolution_uses_published_email_definition_without_binding_case(app):
|
|
"""管理员配置的邮箱定义按规则集命中唯一客户,业务单客户和业务编号仍保持为空。"""
|
|
with app.app_context():
|
|
customer = _create_customer('无锡宇辰有限公司', 'WYC')
|
|
definition = _email_definition()
|
|
rule_set = _publish_rule_set(definition_ids=[definition['id']])
|
|
identity_rules.create_evidence(
|
|
target_type='customer', target_id=customer.id,
|
|
data={'definition_id': definition['id'], 'raw_value': 'buyer@wyc.example.com', 'status': 'approved'}, actor_id=1,
|
|
)
|
|
_intake, candidate = _seed_candidate(sender='Buyer <buyer@wyc.example.com>')
|
|
case = ShippingCase(case_no='CASE-SHADOW-1')
|
|
db.session.add(case)
|
|
|
|
resolution = refresh_candidate_shadow_resolution(candidate)
|
|
db.session.commit()
|
|
|
|
assert resolution.status == 'unique_candidate'
|
|
assert resolution.top_customer_id == customer.id
|
|
assert resolution.identity_rule_set_id == rule_set['id']
|
|
assert resolution.identity_rule_set_checksum == rule_set['checksum']
|
|
assert resolution.top_score == 100.0
|
|
assert any(item['definition_code'] == definition['definition_code'] for item in resolution.evidence_json)
|
|
assert resolution.evidence_json[0]['source_adapter_key'] == 'email_metadata'
|
|
assert db.session.query(ShippingCustomerShadowMatch).filter_by(customer_id=customer.id).count() == 1
|
|
assert case.customer_id is None
|
|
assert case.business_no is None
|
|
assert get_shadow_quality_report()['auto_bound_count'] == 0
|
|
|
|
|
|
@pytest.mark.parametrize('decision_status', ['needs_review', 'blocked', 'missing'])
|
|
def test_unaccepted_header_values_never_become_identity_evidence(app, decision_status):
|
|
"""关键断言:needs_review、blocked、missing 的 Header 值和原始 LLM JSON 都不能参与识别。"""
|
|
with app.app_context():
|
|
field, version = _published_header_field(field_code=f'bill_to_{decision_status}')
|
|
definition = identity_rules.save_definition({
|
|
'definition_code': f'bill_to_{decision_status}', 'target_type': 'customer', 'attribute_key': 'customer_name',
|
|
'order_field_id': field.id, 'normalizer_key': 'name', 'comparator_key': 'normalized_exact',
|
|
'default_weight': 60, 'max_automation': 'none',
|
|
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
|
}, actor_id=1)
|
|
customer = _create_customer('受控客户', 'CTL')
|
|
_publish_rule_set(definition_ids=[definition['id']])
|
|
_intake, candidate = _seed_candidate()
|
|
_attach_header_value(candidate, version, field, '受控客户', decision_status)
|
|
|
|
resolution = refresh_candidate_shadow_resolution(candidate)
|
|
|
|
assert resolution.status == 'unmatched'
|
|
assert resolution.evidence_json == []
|
|
assert resolution.candidate_matches_json == []
|
|
|
|
|
|
def test_address_field_resolves_site_only_and_freezes_rule_schema_field_snapshots(app):
|
|
"""地址业务字段只产出站点候选,并冻结规则集、Schema、字段 ID 和命中证据的解释链。"""
|
|
with app.app_context():
|
|
field, version = _published_header_field(field_code='ship_to_address')
|
|
definition = identity_rules.save_definition({
|
|
'definition_code': 'ship_to_address', 'target_type': 'site', 'attribute_key': 'ship_to_address',
|
|
'order_field_id': field.id, 'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact',
|
|
'default_weight': 50, 'max_automation': 'none',
|
|
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
|
}, actor_id=1)
|
|
rule_set = _publish_rule_set(definition_ids=[definition['id']])
|
|
customer = _create_customer('账款客户', 'BIL')
|
|
site = ShippingCustomerSite(customer_id=customer.id, site_name='上海仓', site_code='SHA', address='上海市浦东新区', status='active')
|
|
db.session.add(site)
|
|
db.session.flush()
|
|
identity_rules.create_evidence(
|
|
target_type='site', target_id=site.id,
|
|
data={'definition_id': definition['id'], 'raw_value': '上海市浦东新区', 'status': 'approved'}, actor_id=1,
|
|
)
|
|
_intake, candidate = _seed_candidate()
|
|
extraction = _attach_header_value(candidate, version, field, '上海市浦东新区', 'corroborated')
|
|
|
|
resolution = refresh_candidate_shadow_resolution(candidate)
|
|
|
|
assert resolution.status == 'unmatched'
|
|
assert resolution.top_customer_id is None
|
|
assert resolution.order_schema_version_id == version.id
|
|
assert resolution.identity_rule_set_version == rule_set['version']
|
|
assert resolution.resolution_context_json['order_extraction_id'] == extraction.id
|
|
assert resolution.resolution_context_json['site_matches'][0]['site_id'] == site.id
|
|
reason = resolution.resolution_context_json['site_matches'][0]['reasons'][0]
|
|
assert reason['source']['order_field_id'] == field.id
|
|
assert reason['evidence_id'] is not None
|
|
assert resolution.resolution_context_json['rule_set']['definitions'][0]['order_field_id'] == field.id
|
|
|
|
|
|
def test_equal_scores_remain_ambiguous_and_template_fingerprint_is_supported(app):
|
|
"""同分邮箱命中保留歧义;后端模板指纹也能经已审核证据产生可解释候选。"""
|
|
with app.app_context():
|
|
first = _create_customer('客户甲', 'AAA')
|
|
second = _create_customer('客户乙', 'BBB')
|
|
email_definition = _email_definition('shared_sender_email')
|
|
template_definition = _template_definition()
|
|
_publish_rule_set(definition_ids=[email_definition['id']])
|
|
for customer in (first, second):
|
|
identity_rules.create_evidence(
|
|
target_type='customer', target_id=customer.id,
|
|
data={'definition_id': email_definition['id'], 'raw_value': 'shared@example.com', 'status': 'approved'}, actor_id=1,
|
|
)
|
|
_intake, candidate = _seed_candidate(sender='shared@example.com')
|
|
ambiguous = refresh_candidate_shadow_resolution(candidate)
|
|
assert ambiguous.status == 'ambiguous'
|
|
assert ambiguous.top_customer_id is None
|
|
assert len(ambiguous.candidate_matches_json) == 2
|
|
|
|
fingerprint_customer = _create_customer('模板客户', 'TMP')
|
|
_publish_rule_set(definition_ids=[template_definition['id']])
|
|
_intake, fingerprint_candidate = _seed_candidate(document_text='SHIPMENT NOTICE\nCustomer: example\nPO: 10001')
|
|
first_pass = refresh_candidate_shadow_resolution(fingerprint_candidate)
|
|
fingerprint = first_pass.evidence_json[0]['raw_value']
|
|
identity_rules.create_evidence(
|
|
target_type='customer', target_id=fingerprint_customer.id,
|
|
data={'definition_id': template_definition['id'], 'raw_value': fingerprint, 'status': 'approved'}, actor_id=1,
|
|
)
|
|
matched = refresh_candidate_shadow_resolution(fingerprint_candidate)
|
|
assert matched.status == 'unique_candidate'
|
|
assert matched.top_customer_id == fingerprint_customer.id
|
|
assert matched.evidence_json[0]['source']['kind'] == 'document_template_fingerprint'
|
|
|
|
|
|
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
|
"""重算复用同一记录;准确率只统计人工标签且不会反向绑定业务。"""
|
|
with app.app_context():
|
|
customer = _create_customer('ACME', 'ACM')
|
|
definition = _email_definition('accuracy_sender_email')
|
|
_publish_rule_set(definition_ids=[definition['id']])
|
|
identity_rules.create_evidence(
|
|
target_type='customer', target_id=customer.id,
|
|
data={'definition_id': definition['id'], 'raw_value': 'buyer@acme.example', 'status': 'approved'}, actor_id=1,
|
|
)
|
|
_intake, candidate = _seed_candidate(sender='buyer@acme.example')
|
|
first = refresh_candidate_shadow_resolution(candidate)
|
|
second = refresh_candidate_shadow_resolution(candidate)
|
|
db.session.commit()
|
|
assert second.id == first.id
|
|
assert db.session.query(ShippingCustomerShadowResolution).count() == 1
|
|
|
|
labeled = label_shadow_resolution(first.id, customer_id=customer.id, actor_id=None)
|
|
report = get_shadow_quality_report()
|
|
assert labeled['is_correct'] is True
|
|
assert report['labeled_count'] == 1
|
|
assert report['correct_count'] == 1
|
|
assert report['accuracy'] == 1.0
|