fix(shipping-notice): 表头身份原子按 Schema 别名归一防近亲模板误杀

- 命中 Schema 别名的表头词归一为字段语义原子,header_to_field 为 None 时零行为变化
- 主路由匹配、冻结复验与下游解析验证统一传入 header_to_field,共用同一别名口径
- 冻结 definition 非法(别名碰撞)时容忍降级为词级原子,不阻断匹配与验证
- 新增表头身份归一单测并同步实施计划文档
This commit is contained in:
hugo committed 2026-09-17 15:54:53 +08:00
1 parent 241d8d48ab
commit d1adbe5ec5
6 files changed
+807 -27

No files matched your search

@@ -11,6 +11,11 @@ services/shipping_notice/document_layout/order_profile_matcher.py
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
表头可经 Schema 别名表(header_to_field)把命中短语归一为 field:: 字段语义原子
(schema_canonical_header_atoms),实现跨措辞的身份对齐,未配置时退化为词级原子;
canonical 序列(schema_canonical_header_tokens)供 signature_conflict 硬门禁的
二次机会评估复用同一表头打分逻辑(effective = max(原始, canonical),仅无必选
锚点且契约可用时生效,七维上报分数维持原始值);
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
"""
@@ -126,6 +131,7 @@ def match_frozen_coordinate_profiles(
profiles: list[dict[str, Any]],
layout: dict[str, Any],
customer_hint_id: int | None = None,
header_to_field: dict[str, str] | None = None,
) -> ProfileMatchResult:
"""
对同一文档的冻结 Profile 做签名硬门禁、分项评分与唯一匹配。
@@ -134,6 +140,10 @@ def match_frozen_coordinate_profiles(
profiles: 已发布模板快照列表;须含 matching_signature 与 definition。
layout: 冻结 layout 快照,含 tables 与 coordinate_evidence。
customer_hint_id: 可选运行期客户 ID,仅用于 trusted_business_context 维度。
header_to_field: 可选 Schema 表头别名契约(TableHeaderContract.header_to_field,
key 为归一化表头文案、value 为 field_code);传入时无必选锚点路径的表头
原子互斥先经 schema_canonical_header_atoms 归一为字段语义原子再比对,
实现跨别名身份对齐;None/空时退化为词级原子(既有行为)。
Returns:
ProfileMatchResult:含 Top1/Top2/Margin、evidence_coverage 与候选分项得分。
@@ -233,6 +243,7 @@ def match_frozen_coordinate_profiles(
optional_hits=optional_hits,
customer_ids=raw.get('customer_ids') if isinstance(raw.get('customer_ids'), list) else None,
customer_hint_id=customer_hint_id,
header_to_field=header_to_field,
)
reason_codes.extend(hard_conflict_codes)
if _profile_requires_unavailable_structure_evidence(
@@ -894,8 +905,17 @@ def _compute_dimension_results(
optional_hits: list[bool],
customer_ids: list[int] | None,
customer_hint_id: int | None,
header_to_field: dict[str, str] | None = None,
) -> tuple[dict[str, MatchDimensionResult], list[str]]:
"""基于签名与冻结证据计算统一七维三态结果。"""
"""
基于签名与冻结证据计算统一七维三态结果。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时表头原子互斥
(仅无必选锚点路径)先按别名归一为字段语义原子,None 时走词级原子;
同时启用 signature_conflict 门禁的二次机会评估(见 [STEP 1.1]),
七维上报分数不受其影响,维持原始值。
"""
hard_conflicts: list[str] = []
results: dict[str, MatchDimensionResult] = {}
@@ -906,20 +926,36 @@ def _compute_dimension_results(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=enforce_header_atoms,
)
# 七维上报维持原始得分;canonical 二次评估得分只参与下方 signature_conflict 门禁。
results['header_semantic_position'] = header_result
if (
enforce_header_atoms
and header_result.state == 'mismatched'
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
and _header_discriminator_atoms_conflict(
signature=signature, observed=observed, header_to_field=header_to_field,
)
):
hard_conflicts.append('profile_header_discriminator_conflict')
elif (
header_result.state == 'mismatched'
and signature
and signature.get('table_patterns')
and header_result.score < 0.35
):
hard_conflicts.append('profile_header_signature_conflict')
elif header_result.state == 'mismatched' and signature and signature.get('table_patterns'):
# [STEP 1.1] 二次机会门禁:原始软分被词级原子互斥压到 0.35 以下的候选,
# 在「无必选锚点 + 别名契约可用」前提下用 canonical token 复用同一打分
# 逻辑重估一次(effective = max(原始, canonical)),使跨别名措辞不再被
# 第二道表头硬门禁误杀;不满足前提时 effective 即原始分,行为零变化。
effective_score = header_result.score
if header_result.score < 0.35 and enforce_header_atoms and header_to_field:
canonical_result = _score_header_semantic_position(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=False,
expected_tokens_override=schema_canonical_header_tokens(
_signature_identity_header_tokens(signature), header_to_field,
),
observed_tokens_override=schema_canonical_header_tokens(
[str(item) for item in observed.get('header_tokens') or []], header_to_field,
),
)
effective_score = max(effective_score, canonical_result.score)
if effective_score < 0.35:
hard_conflicts.append('profile_header_signature_conflict')
# [STEP 2] column_topology
column_result = _score_column_topology(signature=signature, observed=observed, profile=profile)
@@ -969,16 +1005,32 @@ def _score_header_semantic_position(
observed: dict[str, Any],
required_hits: list[bool],
enforce_atom_discriminator: bool = True,
expected_tokens_override: list[str] | None = None,
observed_tokens_override: list[str] | None = None,
) -> MatchDimensionResult:
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
期望侧先截断单逻辑表头的折行副标签污染。
Args:
expected_tokens_override: 期望侧 token 覆盖(如 Schema 别名归一后的
canonical 序列);None 时按 `_signature_identity_header_tokens`
既有口径取值,行为不变。提供时软评分(含词命中率与顺序比)整体
切换到该序列上进行,供二次机会门禁复用同一套打分逻辑。
observed_tokens_override: 观测侧 token 覆盖(口径同上);None 时按
`observed['header_tokens']` 既有口径取值,行为不变。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
if expected_tokens_override is None:
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
else:
expected_tokens = [str(item).casefold() for item in expected_tokens_override]
if observed_tokens_override is None:
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
else:
observed_tokens = [str(item).casefold() for item in observed_tokens_override]
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
if not expected_tokens:
if not required_hits:
@@ -997,8 +1049,16 @@ def _score_header_semantic_position(
return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
observed_order = observed.get('header_tokens') or []
expected_order = (
expected_tokens
if expected_tokens_override is not None
else [str(item).casefold() for item in _signature_identity_header_order(signature)]
)
observed_order = (
observed_tokens
if observed_tokens_override is not None
else observed.get('header_tokens') or []
)
shared = [item for item in expected_order if item in observed_order]
order_ratio = 1.0
if len(shared) > 1:
@@ -1018,6 +1078,21 @@ def _score_header_semantic_position(
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
# 字段语义原子前缀:词级原子只含 [a-z0-9],不可能出现冒号,与前缀无碰撞空间。
_HEADER_FIELD_MARKER = 'field::'
def _header_normalized_words(text: str) -> list[str]:
"""
表头统一词管线:剥括号注记 → casefold → 去撇号 → 按非字母数字切分。
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
return [part for part in re.split(r'[^a-z0-9]+', normalized) if part]
def _sanitize_signature_table_identity(
@@ -1081,32 +1156,209 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
核心逻辑:先拼接 token(让跨 token 空格切开的括号注记仍可整体剥除),再走
_header_normalized_words 统一词管线切词;过滤过短词与虚词。签名侧与运行时共用。
"""
joined = ' '.join(str(token) for token in tokens)
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
normalized = re.sub(r"['’]", '', normalized)
atoms: set[str] = set()
for part in re.split(r'[^a-z0-9]+', normalized):
for part in _header_normalized_words(joined):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
def schema_canonical_header_atoms(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> frozenset[str]:
"""
将表头 token 按 Schema 别名归一为字段语义原子,供订单模板身份匹配跨别名对齐。
用途:同一业务字段在不同供应商模板中的表头措辞不同(如 Ship Date / Requested
Ship Date / 出货日期),词级原子只能字面碰撞;本函数借助 Schema 别名表把命中
别名的表头文本升级为 field::<field_code> 标记原子,使身份比较基于字段语义而非
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
- 中文别名经词管线切词后为空词元组 → 自然跳过(有意行为):词级原子本就只
保留 [a-z0-9],中文措辞无法构成词级身份,语义升级依赖别名表配置英文别名。
Args:
tokens: 表头 token 列表(可为合并格长文案,如 "Requested Ship Date Unit
Price");空串/空白 token 会被跳过(吸收 MinerU 空格占位)。
header_to_field: TableHeaderContract.header_to_field(普通 dict[str, str],
key 为 Schema 别名的归一化表头文案,value 为 field_code);鸭子类型
消费,不引入 order_schema → matcher 反向依赖;None/空表示未配置。
Returns:
frozenset[str]:field::<field_code> 标记原子与词级原子的并集。
"""
if not header_to_field:
return _header_token_atoms(tokens)
# [STEP 1] 构建短语字典:别名 key → 词元组 → field_code;casefold 跨字段
# 碰撞的短语整体弃用(身份归属不允许歧义,宁缺勿错)。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
atoms.add(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
atoms.add(word)
index += 1
return frozenset(atoms)
def schema_canonical_header_tokens(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> list[str]:
"""
将表头 token 按 Schema 别名归一为序列语义的 canonical token 列表。
用途:供 `profile_header_signature_conflict` 二次机会门禁复用
`_score_header_semantic_position` 的既有软评分——词级互斥把跨别名措辞的
原始分压成 0 后,用本函数归一出的 canonical 序列重估一次,命中别名的片段
以统一的 field::<field_code> 标记项参与序列比较,实现跨措辞的软分 rescue。
与 `schema_canonical_header_atoms` 的关系:二者共用同一词管线
(`_header_normalized_words`)与同一贪心最长短语匹配口径、同一未命中词过滤,
但语义不同——atoms 是集合语义(去重、无序,供硬互斥集合全等比较),本函数
是序列语义(保序、允许重复,供软评分按序列比较)。二者各自独立实现,
不得互相调用/推导;同一输入下本函数结果去重即 atoms 结果(同源语义)。
核心逻辑:
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
- 空串/纯空白 token(MinerU 空格占位)跳过,与 atoms 口径一致。
Args:
tokens: 表头 token 列表(期望侧传 `_signature_identity_header_tokens`
的结果、观测侧传 `observed['header_tokens']`);可为合并格长文案。
header_to_field: TableHeaderContract.header_to_field(dict[str, str],
key 为 Schema 别名归一化表头文案、value 为 field_code);
None/空表示未配置。
Returns:
list[str]:canonical token 序列(保序、允许重复)。
"""
if not header_to_field:
return tokens
# [STEP 1] 短语字典:与 schema_canonical_header_atoms 完全同源的构建口径。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
canonical.append(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
canonical.append(word)
index += 1
return canonical
def _header_discriminator_atoms_conflict(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
header_to_field: dict[str, str] | None = None,
) -> bool:
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
"""
签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时签名侧与观测侧
token 均先经 schema_canonical_header_atoms 归一为字段语义原子再比较
全等,使跨别名措辞(同字段不同表头文案)不再误判互斥;None/空时
两侧均走词级原子(既有行为,零变化)。
"""
if signature is None or not signature.get('table_patterns'):
return False
expected_tokens = _signature_identity_header_tokens(signature)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms != observed_atoms
def _score_column_topology(