feat(shipping-notice): 客户识别证据命中分级为三层匹配

- 归一层新增 canonical 等值键与包含分级(完整/截断),统一证据标准化入口
- 影子识别升至 shadow-v3:等值 > 完整包含 > 截断包含层级裁决,邮箱/域名仅精确等值
- 自动确认升至 auto-v3:完整包含可自动确认,截断包含仅供人工建议不进自动裁决
- 影子候选状态与复核侧重新识别统一复用 resolver 分级裁决,移除本地分数重复判定
- 新增客户身份三层匹配契约测试
This commit is contained in:
hugo committed 2026-09-17 15:54:52 +08:00
1 parent e472abc4e3
commit 241d8d48ab
6 files changed
+655 -49

No files matched your search

@@ -2,6 +2,8 @@
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议);
邮箱/域名指纹只做精确等值,禁止包含比较。
"""
from __future__ import annotations
@@ -23,12 +25,14 @@ from app.models import (
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.customer_normalization import (
normalize_customer_name,
normalize_domain,
normalize_email,
IDENTITY_MATCH_EQUALITY,
IDENTITY_MATCH_TIER_RANK,
canonical_identity_key,
classify_identity_containment,
normalize_identity_evidence_value,
)
RESOLUTION_VERSION = 'shadow-v2'
RESOLUTION_VERSION = 'shadow-v3'
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
@@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None:
try:
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
if source.get('option_key') == 'from_email':
return normalize_email(value)
if source.get('option_key') == 'from_domain':
return normalize_domain(value)
if field_config.get('normalizer_key') == 'name':
return normalize_customer_name(value) or None
normalized = str(value or '').strip().upper()
return normalized or None
return normalize_identity_evidence_value(
value,
option_key=source.get('option_key'),
normalizer_key=field_config.get('normalizer_key'),
)
except Exception:
return None
@@ -154,6 +155,8 @@ def _source_evidence(
normalized = _normalize(definition, value)
if not normalized:
continue
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
evidence.append({
'definition_id': definition_id,
'definition_code': code,
@@ -161,6 +164,8 @@ def _source_evidence(
'target_type': definition.get('target_type'),
'raw_value': value,
'normalized_value': normalized,
# 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。
'option_key': str(context_source.get('option_key') or ''),
'weight': int(definition.get('default_weight') or 0),
'source': source,
})
@@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons
}
def _classify_evidence_match(
*, runtime_value: str, evidence_value: str, option_key: str,
) -> str | None:
"""
对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。
核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值;
文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。
"""
if option_key in {'from_email', 'from_domain'}:
return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None
if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value):
return IDENTITY_MATCH_EQUALITY
return classify_identity_containment(runtime_value, evidence_value, option_key=option_key)
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
"""
按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。
核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级,
排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。
顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。
"""
scores: dict[int, float] = defaultdict(float)
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
tiers: dict[int, str] = {}
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
for item in evidence:
if item['target_type'] != 'customer':
continue
records = ShippingIdentityEvidence.query.filter_by(
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
definition_id=item['definition_id'], status='approved',
).all()
for record in records:
customer = customers.get(record.customer_id) if record.customer_id is not None else None
if customer is None:
continue
match_kind = _classify_evidence_match(
runtime_value=str(item['normalized_value'] or ''),
evidence_value=str(record.normalized_value or ''),
option_key=str(item.get('option_key') or ''),
)
if match_kind is None:
continue
scores[customer.id] += item['weight']
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
return sorted(
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
key=lambda item: (-float(item['score']), int(item['customer_id'])),
)
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind})
if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]:
tiers[customer.id] = match_kind
ranked = [
_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id])
for customer_id, score in scores.items()
]
# 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。
for item in ranked:
item['match_kind'] = tiers[int(item['customer_id'])]
ranked.sort(key=lambda item: (
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])],
-float(item['score']),
int(item['customer_id']),
))
return ranked
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
customer_matches = _rank_customer_matches(evidence)
site_matches = _rank_site_matches(evidence)
top_score = float(customer_matches[0]['score']) if customer_matches else None
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
# [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate,
# 强层级唯一时弱层级候选仅作展示,不参与歧义计算。
top_tier_candidates: list[dict[str, Any]] = []
if customer_matches:
top_tier_rank = min(
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches
)
top_tier_candidates = [
item for item in customer_matches
if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank
]
return {
'resolution_version': RESOLUTION_VERSION,
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous',
'evidence': evidence,
'customer_matches': customer_matches,
'site_matches': site_matches,