feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则

This commit is contained in:
hugo committed 2026-07-20 19:28:17 +08:00
1 parent 88408490d7
commit 34d489a2d1
167 files changed
+10365 -7978

No files matched your search

@@ -1,38 +1,43 @@
"""
backend/tests/test_shipping_customer_shadow_resolution.py
用途:验证客户影子识别的确定性候选、幂等、质量标签和零副作用边界。
依赖:内存数据库、客户主数据、Candidate/Intake、customer_shadow_resolution。
逻辑:构造真实 ORM 样本后刷新影子结果,断言业务单客户与业务编号始终不被写入。
用途:验证规则集驱动的客户影子识别、订单字段裁决门禁和客户/站点隔离。
依赖:身份规则服务、受控订单 FieldValue、Candidate/Intake 与客户主数据。
逻辑:仅已发布定义和 accepted/corroborated Header 值可进入候选;影子结果只记录审计,绝不绑定业务单。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingCustomerShadowResolution,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingCustomerSite,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
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(*, customer_name: str, sender: str = '') -> ShippingNoticeCandidate:
"""创建影子识别所需的最小 Intake、Document 与 Candidate。"""
user = User(username=f'user-{customer_name}-{sender}', email=f'{db.session.query(User).count()}@example.com', role='user')
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(
@@ -50,18 +55,76 @@ def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCa
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',
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': customer_name, 'lines': [{'sku': 'A', 'quantity': 1}]}},
structured_result_json={'business_summary': {'customer_name': 'RAW LLM VALUE MUST NOT BE USED'}},
)
db.session.add(candidate)
db.session.flush()
return candidate
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:
@@ -72,109 +135,169 @@ def _create_customer(name: str, code: str) -> ShippingCustomer:
return customer
def test_shadow_resolution_uses_strong_evidence_without_binding_case(app):
"""完整邮箱可形成唯一候选,但业务单客户和业务编号保持为空。"""
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')
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id, identifier_type='email', raw_value='buyer@wyc.example.com',
normalized_value='buyer@wyc.example.com', status='approved', source='manual', auto_match_allowed=True,
))
candidate = _seed_candidate(customer_name='不稳定解析名称', sender='Buyer <buyer@wyc.example.com>')
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)
db.session.flush()
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
def test_shadow_resolution_reports_ambiguous_and_unmatched(app):
"""同名客户必须保留歧义,无证据样本必须标记未匹配。"""
@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():
_create_customer('ACME', 'ACA')
_create_customer('ACME', 'ACB')
ambiguous = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='ACME'))
unmatched = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='UNKNOWN'))
db.session.commit()
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
assert len(ambiguous.matches) == 2
assert unmatched.status == 'unmatched'
assert unmatched.candidate_matches_json == []
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')
candidate = _seed_candidate(customer_name='ACME')
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)
first_id = first.id
second = refresh_candidate_shadow_resolution(candidate)
db.session.commit()
assert second.id == first_id
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)
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
assert report['auto_bound_count'] == 0
def test_shadow_failure_does_not_block_candidate_persistence(app, monkeypatch):
"""影子规则异常时 Candidate 主流程仍须创建并可提交。"""
with app.app_context():
user = User(username='shadow-safe-user', email='shadow-safe@example.com', role='user')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-SHADOW-SAFE', owner_user_id=user.id, original_filename='notice.txt',
storage_provider='minio', storage_bucket='test', storage_key='shadow-safe',
content_hash='a' * 64, file_size=10, upload_status='uploaded', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-SHADOW-SAFE', asset_id=asset.id, user_id=user.id,
parser_version='v6', parse_status='parsed', structured_result_json={},
)
db.session.add(intake)
db.session.flush()
monkeypatch.setattr(
'app.services.shipping_notice.customer_shadow_resolution.refresh_candidate_shadow_resolution',
lambda _candidate: (_ for _ in ()).throw(RuntimeError('shadow failure')),
)
result = NoticeIntakeResult(
filename='notice.txt', source_type='manual', source_file_type='text/plain',
text='Customer: ACME\nPO: PO-1\nSKU: A001 Qty: 1', content_hash='a' * 64,
file_size=10, status='accepted',
)
persisted = persist_documents_and_candidates(
intake=intake,
parent_asset=asset,
result=result,
run_duplicate_detection=False,
create_candidates=True,
)
db.session.commit()
assert persisted['candidate_count'] == 1
candidate = db.session.query(ShippingNoticeCandidate).one()
assert candidate.validation_status == 'ready'
shadow = db.session.query(ShippingCustomerShadowResolution).one()
assert shadow.status == 'failed'