""" backend/tests/test_shipping_customer_auto_resolution.py 用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。 依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。 """ from copy import deepcopy import pytest from app import db from app.models import ( FileAsset, ShippingCustomer, ShippingCustomerShadowResolution, ShippingIdentityDefinition, ShippingIdentityEvidence, ShippingIdentityRuleSet, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, ShippingNotice, ShippingTaskEvent, User, ) from app.services.shipping_notice.customer_auto_resolution import ( AUTO_RESOLUTION_VERSION, get_auto_resolution_metrics, resolve_auto_customer_from_shadow, try_auto_confirm_task_customer, ) def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]: """创建管理员配置的识别定义及冻结发布规则集快照(使用标准 bill_to_customer)。""" from app.services.shipping_notice import field_asset_service field_asset_service.ensure_standard_assets_seeded() schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none() if schema is None: schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') db.session.add(schema) db.session.flush() field = ShippingOrderField.query.filter_by(field_code='bill_to_customer').one() field_config = { 'field_id': field.id, 'field_code': field.field_code, 'display_name': 'Bill To Customer', 'scope': 'header', 'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim', } schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() if schema_version is None: schema_version = ShippingOrderSchemaVersion( schema_id=schema.id, version=1, status='published', definition_json={'fields': [field_config]}, checksum='1' * 64, ) db.session.add(schema_version) db.session.flush() definition = ShippingIdentityDefinition.query.filter_by(definition_code='test_mail_sender_email').one_or_none() if definition is None: definition = ShippingIdentityDefinition( definition_code='test_mail_sender_email', target_type='customer', context_field_id=field.id, default_weight=100, max_automation='conditional', status='active', ) db.session.add(definition) db.session.flush() rule_set = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none() if rule_set is None: rule_set = ShippingIdentityRuleSet( version=1, status='published', checksum='a' * 64, definition_json={'order_schema': { 'id': schema_version.id, 'version': schema_version.version, 'checksum': schema_version.checksum, }, 'definitions': [{ 'id': definition.id, 'definition_code': definition.definition_code, 'target_type': 'customer', 'context_field_id': field.id, 'max_automation': 'conditional', 'field_config': field_config, }]}, ) db.session.add(rule_set) db.session.flush() return definition, rule_set def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): """创建带邮件证据的 Candidate、影子记录和待确认任务。""" user = User(username=f"auto-user-{db.session.query(User).count()}", email="auto@example.com", role="user") db.session.add(user) db.session.flush() asset = FileAsset( asset_no=f"AUTO-ASSET-{user.id}", owner_user_id=user.id, original_filename="notice.eml", storage_provider="minio", storage_bucket="test", storage_key=f"auto-{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 = ShippingOrderIntake( intake_no=f"AUTO-INTAKE-{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 = ShippingOrderDocument( intake_id=intake.id, asset_id=asset.id, document_type="attachment", attachment_key="file", filename="notice.pdf", classification="order_notice", parse_status="parsed", ) db.session.add(document) db.session.flush() candidate = ShippingOrderCandidate( candidate_no=f"AUTO-CAND-{user.id}", intake_id=intake.id, primary_document_id=document.id, candidate_key="document:1", validation_status="ready", selected=True, structured_result_json={"business_summary": {"customer_name": "unstable name"}}, ) db.session.add(candidate) db.session.flush() task = ShippingOrderTask( task_no=f"OT-AUTO-{user.id}", user_id=user.id, candidate_id=candidate.id, source_type="eml", ) db.session.add(task) db.session.flush() definition, rule_set = _auto_definition() schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() extraction = ShippingOrderExtraction( intake_id=intake.id, schema_version_id=schema_version.id, input_snapshot_hash='a' * 64, status='accepted', raw_llm_output_json={}, ) db.session.add(extraction) db.session.flush() decision = ShippingOrderFieldDecision( extraction_id=extraction.id, field_id=definition.context_field_id, decision_status='accepted', resolved_value_json=sender, ) db.session.add(decision) db.session.flush() field_value = ShippingOrderFieldValue( extraction_id=extraction.id, field_id=definition.context_field_id, decision_id=decision.id, value_text=sender, value_json=sender, ) db.session.add(field_value) db.session.flush() candidate.order_extraction_id = extraction.id shadow = ShippingCustomerShadowResolution( candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1", identity_rule_set_id=rule_set.id, identity_rule_set_version=rule_set.version, identity_rule_set_checksum=rule_set.checksum, order_schema_version_id=schema_version.id, status="unique_candidate", evidence_json=[ {"definition_id": definition.id, "definition_code": definition.definition_code, "raw_value": sender, "normalized_value": sender, "source": { "kind": "field_value", "context_field_id": definition.context_field_id, "field_value_id": field_value.id, "decision_id": decision.id, "extraction_id": extraction.id, "order_schema_version_id": schema_version.id, }}, ], candidate_matches_json=[], resolution_context_json={'rule_set': { 'id': rule_set.id, 'version': rule_set.version, 'checksum': rule_set.checksum, 'order_schema': rule_set.definition_json['order_schema'], 'definitions': [{ 'id': definition.id, 'definition_code': definition.definition_code, 'target_type': 'customer', 'context_field_id': definition.context_field_id, 'max_automation': 'conditional', 'field_config': rule_set.definition_json['definitions'][0]['field_config'], }], }, 'order_extraction_id': extraction.id}, ) db.session.add(shadow) db.session.commit() return task def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, status: str = "approved"): """创建客户及冻结邮箱定义对应的可审核证据。""" customer = ShippingCustomer(standard_name=f"客户 {code}", short_code=code, status="active") db.session.add(customer) db.session.flush() definition, _ = _auto_definition() db.session.add(ShippingIdentityEvidence( definition_id=definition.id, customer_id=customer.id, raw_value=value, normalized_value=value, status=status, auto_match_allowed=allowed, )) db.session.flush() return customer def _allow_auto_confirmation(app) -> None: """为自动确认专项用例显式放宽门禁,不改变生产默认安全阈值。""" app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 0 app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None: """断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。""" assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0 def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app): """开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。""" with app.app_context(): _allow_auto_confirmation(app) customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() result = try_auto_confirm_task_customer(task) assert result["status"] == "auto_confirmed" assert result["rule_version"] == AUTO_RESOLUTION_VERSION shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() assert shadow.status == "confirmed" assert shadow.confirmation_method == "auto_rule" assert shadow.confirmed_customer_id == customer.id assert shadow.evidence_json[0]['definition_id'] metrics = get_auto_resolution_metrics() assert result['business_no'] is None _assert_ot_did_not_create_notice(task) assert metrics["auto_confirmed_count"] == 1 def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): """总开关关闭或证据未审核/未授权时保持 pending,不占用业务流水。""" with app.app_context(): _customer_with_identifier(code="WYC", value="buyer@wyc.example.com", allowed=False) task = _seed_candidate_task() app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False disabled = try_auto_confirm_task_customer(task) assert disabled["status"] == "disabled" _assert_ot_did_not_create_notice(task) _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" _assert_ot_did_not_create_notice(task) def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): """同一强证据映射多个客户时必须降级人工确认。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code="AAA", value="buyer@wyc.example.com") _customer_with_identifier(code="BBB", value="buyer@wyc.example.com") task = _seed_candidate_task() result = try_auto_confirm_task_customer(task) assert result["status"] == "ambiguous" assert len(result["candidate_customer_ids"]) == 2 assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" _assert_ot_did_not_create_notice(task) def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): """批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() task_id = task.id result = try_auto_confirm_task_customer(task) assert result["status"] == "auto_confirmed" db.session.rollback() db.session.expire_all() persisted_task = db.session.get(ShippingOrderTask, task_id) assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate" assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insufficient(app): """总开关开启但没有足够人工真值时,必须保持人工客户复核和未编号状态。""" with app.app_context(): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1 app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() result = try_auto_confirm_task_customer(task) assert result["status"] == "insufficient_labeled_samples" assert result["quality_gate"]["labeled_sample_count"] == 0 assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" _assert_ot_did_not_create_notice(task) def test_business_evidence_never_auto_confirms(app): """规则快照被篡改为业务字段上限时必须拒绝该快照,不能自动绑定客户。""" with app.app_context(): _allow_auto_confirmation(app) customer = ShippingCustomer(standard_name='业务字段客户', short_code='BIZ', status='active') definition = ShippingIdentityDefinition( definition_code='test_business_contact', target_type='customer', context_field_id=_auto_definition()[0].context_field_id, default_weight=100, max_automation='none', status='active', ) db.session.add_all([customer, definition]) db.session.flush() db.session.add(ShippingIdentityEvidence( definition_id=definition.id, customer_id=customer.id, raw_value='ACME', normalized_value='ACME', status='approved', auto_match_allowed=True, )) task = _seed_candidate_task() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() original_source = shadow.evidence_json[0]['source'] field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id']) decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id']) field_value.value_text = 'ACME' field_value.value_json = 'ACME' decision.resolved_value_json = 'ACME' shadow.evidence_json = [{ 'definition_id': definition.id, 'normalized_value': 'ACME', 'source': original_source, }] context = deepcopy(shadow.resolution_context_json) context['rule_set']['definitions'] = [{ 'id': definition.id, 'target_type': 'customer', 'context_field_id': definition.context_field_id, 'max_automation': 'none', }] shadow.resolution_context_json = context db.session.commit() result = try_auto_confirm_task_customer(task) assert result['status'] == 'rule_snapshot_missing' assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): """公共域名和无法验证的冻结规则快照均不可触发自动绑定。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code='PUB', value='buyer@gmail.com') task = _seed_candidate_task(sender='buyer@gmail.com') assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.resolution_context_json = {} db.session.commit() missing = resolve_auto_customer_from_shadow(task) assert missing['status'] == 'rule_snapshot_missing' assert missing['customer_id'] is None def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app): """影子值或 Schema 锚点被篡改时必须回到人工复核,不能仅信任 JSON 中的追溯主键。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code='WYC', value='buyer@wyc.example.com') task = _seed_candidate_task() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() evidence = deepcopy(shadow.evidence_json) evidence[0]['normalized_value'] = 'attacker@example.com' shadow.evidence_json = evidence db.session.commit() assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' shadow.evidence_json = [] context = deepcopy(shadow.resolution_context_json) context['rule_set']['order_schema']['checksum'] = 'f' * 64 shadow.resolution_context_json = context db.session.commit() assert resolve_auto_customer_from_shadow(task)['status'] == 'rule_snapshot_missing' def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app): """有足够样本但强规则与人工真值不一致时,自动确认必须安全降级。""" with app.app_context(): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1 app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 matched = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") truth = ShippingCustomer(standard_name="真实客户", short_code="TRU", status="active") db.session.add(truth) db.session.flush() task = _seed_candidate_task() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.manual_customer_id = truth.id db.session.commit() result = try_auto_confirm_task_customer(task) assert matched.id != truth.id assert result["status"] == "insufficient_accuracy" assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["accuracy"] == 0 assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" _assert_ot_did_not_create_notice(task) def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None: """把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。""" shadow.order_schema_version_id = new_version.id # JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。 evidence = deepcopy(shadow.evidence_json) evidence[0]['source']['order_schema_version_id'] = new_version.id shadow.evidence_json = evidence extraction = db.session.get( ShippingOrderExtraction, evidence[0]['source']['extraction_id'], ) extraction.schema_version_id = new_version.id def test_schema_republish_with_same_semantics_still_auto_confirms(app): """Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) old_version.status = 'retired' new_version = ShippingOrderSchemaVersion( schema_id=old_version.schema_id, version=old_version.version + 1, status='published', definition_json={'fields': [{ 'field_id': old_version.definition_json['fields'][0]['field_id'], 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', 'scope': 'header', 'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim', }]}, checksum='f' * 64, ) db.session.add(new_version) db.session.flush() _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() result = resolve_auto_customer_from_shadow(task) assert result['status'] == 'unique_strong_match' assert result['customer_id'] is not None def test_schema_republish_changes_semantics_never_auto_confirms(app): """Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。""" with app.app_context(): _allow_auto_confirmation(app) _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) old_version.status = 'retired' new_version = ShippingOrderSchemaVersion( schema_id=old_version.schema_id, version=old_version.version + 1, status='published', definition_json={'fields': [{ 'field_id': old_version.definition_json['fields'][0]['field_id'], 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', 'scope': 'header', 'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True, 'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。 }]}, checksum='e' * 64, ) db.session.add(new_version) db.session.flush() _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() result = resolve_auto_customer_from_shadow(task) assert result['status'] == 'rule_snapshot_missing' assert result['customer_id'] is None