259 lines
13 KiB
Python
259 lines
13 KiB
Python
"""
|
||
backend/tests/test_shipping_customer_shadow_resolution.py
|
||
|
||
用途:验证规则集只消费 accepted/corroborated Header FieldValue,并保持客户/站点隔离。
|
||
依赖:身份规则服务、统一订单字段链、Candidate/Intake 与客户主数据。
|
||
逻辑:每个场景发布可识别字段与规则,再将字段值绑定 Candidate Extraction,禁止邮件头和原始 LLM 旁路。
|
||
"""
|
||
|
||
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 = ''):
|
||
"""创建带可疑邮件元数据和原始 LLM 摘要的 Candidate,证明两者不会被旁路读取。"""
|
||
user = User(username=f'shadow-{db.session.query(User).count()}', email=f'{db.session.query(User).count()}@example.com')
|
||
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='template 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_field(*, code: str, option_key: str | None = None):
|
||
"""发布允许客户识别的 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=code, scope='header', value_type='string',
|
||
field_category='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()
|
||
current = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||
if current is not None:
|
||
current.status = 'retired'
|
||
config = {
|
||
'field_id': field.id, 'field_code': code, 'display_name': code, 'scope': 'header',
|
||
'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True,
|
||
'normalizer_key': 'lowercase_trim' if option_key == 'from_email' else 'uppercase_trim',
|
||
}
|
||
if option_key:
|
||
config['context_source'] = {'provider_key': 'mail_header', 'option_key': option_key}
|
||
version = ShippingOrderSchemaVersion(
|
||
schema_id=schema.id, version=ShippingOrderSchemaVersion.query.count() + 1,
|
||
status='published', definition_json={'fields': [config]}, checksum=f'{ShippingOrderSchemaVersion.query.count() + 1:064x}',
|
||
lock_version=1,
|
||
)
|
||
db.session.add(version)
|
||
db.session.flush()
|
||
return field, version
|
||
|
||
|
||
def _definition(field, *, target='customer', weight=100):
|
||
"""创建并发布引用 context_field_id 的规则定义。"""
|
||
definition = identity_rules.save_definition({
|
||
'definition_code': f'rule_{field.field_code}', 'display_name': field.field_code,
|
||
'evidence_label': field.field_code, 'target_type': target,
|
||
'context_field_id': field.id, 'default_weight': weight,
|
||
}, actor_id=1)
|
||
draft = identity_rules.create_rule_set({}, actor_id=1)
|
||
saved = identity_rules.save_rule_set(draft['id'], {
|
||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||
}, actor_id=1)
|
||
rule_set = identity_rules.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||
return definition, rule_set
|
||
|
||
|
||
def _attach_value(candidate, version, field, value, status='accepted'):
|
||
"""为 Candidate 写入统一 Header Decision/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'}]},
|
||
)
|
||
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, value_json=value,
|
||
))
|
||
candidate.order_extraction_id = extraction.id
|
||
db.session.flush()
|
||
return extraction
|
||
|
||
|
||
def _customer(name, code):
|
||
row = ShippingCustomer(standard_name=name, short_code=code, status='active')
|
||
db.session.add(row)
|
||
db.session.flush()
|
||
return row
|
||
|
||
|
||
def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||
"""客户命中必须来自 accepted FieldValue;Intake 邮件头即使不同也不能覆盖。"""
|
||
with app.app_context():
|
||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||
definition, rule_set = _definition(field)
|
||
customer = _customer('无锡宇辰有限公司', 'WYC')
|
||
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='spoof@example.net')
|
||
_attach_value(candidate, version, field, 'buyer@wyc.example.com')
|
||
case = ShippingCase(case_no='CASE-SHADOW')
|
||
db.session.add(case)
|
||
|
||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||
|
||
assert resolution.status == 'unique_candidate'
|
||
assert resolution.top_customer_id == customer.id
|
||
assert resolution.identity_rule_set_id == rule_set['id']
|
||
assert resolution.evidence_json[0]['context_field_id'] == field.id
|
||
assert resolution.evidence_json[0]['source']['kind'] == 'field_value'
|
||
assert case.customer_id is None and case.business_no is None
|
||
|
||
|
||
@pytest.mark.parametrize('status', ['needs_review', 'blocked', 'missing'])
|
||
def test_unaccepted_field_values_never_become_identity_evidence(app, status):
|
||
"""非 accepted/corroborated 值及原始 LLM JSON 均不能进入客户识别。"""
|
||
with app.app_context():
|
||
field, version = _published_field(code=f'customer_{status}')
|
||
definition, _rule_set = _definition(field)
|
||
customer = _customer('受控客户', 'CTL')
|
||
identity_rules.create_evidence(
|
||
target_type='customer', target_id=customer.id,
|
||
data={'definition_id': definition['id'], 'raw_value': '受控客户', 'status': 'approved'}, actor_id=1,
|
||
)
|
||
_intake, candidate = _seed_candidate(sender='受控客户')
|
||
_attach_value(candidate, version, field, '受控客户', status=status)
|
||
|
||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||
|
||
assert resolution.status == 'unmatched'
|
||
assert resolution.evidence_json == []
|
||
|
||
|
||
def test_site_field_resolves_site_only_and_freezes_context_field_snapshot(app):
|
||
"""站点字段只产生站点候选,解释链冻结 context_field_id 和 Extraction。"""
|
||
with app.app_context():
|
||
field, version = _published_field(code='ship_to_address')
|
||
definition, rule_set = _definition(field, target='site', weight=50)
|
||
customer = _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_value(candidate, version, field, '上海市浦东新区', status='corroborated')
|
||
|
||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||
|
||
assert resolution.status == 'unmatched' and resolution.top_customer_id is None
|
||
assert resolution.identity_rule_set_version == rule_set['version']
|
||
site_match = resolution.resolution_context_json['site_matches'][0]
|
||
assert site_match['site_id'] == site.id
|
||
assert site_match['reasons'][0]['source'] == {
|
||
'kind': 'field_value', 'context_field_id': field.id,
|
||
'field_value_id': site_match['reasons'][0]['source']['field_value_id'],
|
||
'decision_id': site_match['reasons'][0]['source']['decision_id'],
|
||
'extraction_id': extraction.id, 'order_schema_version_id': version.id,
|
||
}
|
||
assert resolution.resolution_context_json['rule_set']['definitions'][0]['context_field_id'] == field.id
|
||
|
||
|
||
def test_equal_customer_matches_remain_ambiguous(app):
|
||
"""同一已裁决字段值映射多个客户时必须保留歧义。"""
|
||
with app.app_context():
|
||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||
definition, _rule_set = _definition(field)
|
||
for customer in (_customer('客户甲', 'AAA'), _customer('客户乙', 'BBB')):
|
||
identity_rules.create_evidence(
|
||
target_type='customer', target_id=customer.id,
|
||
data={'definition_id': definition['id'], 'raw_value': 'shared@example.com', 'status': 'approved'}, actor_id=1,
|
||
)
|
||
_intake, candidate = _seed_candidate()
|
||
_attach_value(candidate, version, field, 'shared@example.com')
|
||
|
||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||
|
||
assert resolution.status == 'ambiguous'
|
||
assert resolution.top_customer_id is None
|
||
assert len(resolution.candidate_matches_json) == 2
|
||
|
||
|
||
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||
"""重算复用同一记录;准确率只统计人工标签且不反向绑定业务。"""
|
||
with app.app_context():
|
||
field, version = _published_field(code='sender_email', option_key='from_email')
|
||
definition, _rule_set = _definition(field)
|
||
customer = _customer('ACME', 'ACM')
|
||
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()
|
||
_attach_value(candidate, version, field, 'buyer@acme.example')
|
||
first = refresh_candidate_shadow_resolution(candidate)
|
||
second = refresh_candidate_shadow_resolution(candidate)
|
||
db.session.commit()
|
||
assert second.id == first.id
|
||
assert ShippingCustomerShadowResolution.query.count() == 1
|
||
assert ShippingCustomerShadowMatch.query.filter_by(customer_id=customer.id).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 and report['accuracy'] == 1.0
|