fix(shipping-notice): 表头身份原子按 Schema 别名归一防近亲模板误杀
- 命中 Schema 别名的表头词归一为字段语义原子,header_to_field 为 None 时零行为变化 - 主路由匹配、冻结复验与下游解析验证统一传入 header_to_field,共用同一别名口径 - 冻结 definition 非法(别名碰撞)时容忍降级为词级原子,不阻断匹配与验证 - 新增表头身份归一单测并同步实施计划文档
This commit is contained in:
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(
|
||||
|
||||
@@ -30,6 +30,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
LAYOUT_SIGNATURE_ID,
|
||||
MATCHER_POLICY_ID,
|
||||
@@ -1235,6 +1236,15 @@ def _build_coordinate_overlap_evidence(
|
||||
definition = dict(profile.definition_json or {})
|
||||
thresholds = _match_thresholds(definition)
|
||||
schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {}
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(
|
||||
schema_definition if isinstance(schema_definition, dict) else {},
|
||||
).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 Schema definition 非法(别名碰撞等)时容忍降级:None 使 overlap
|
||||
# 证据的表头原子互斥退化为词级原子,不阻断模板验证;空 definition 编译
|
||||
# 出空映射,matcher 侧与 None 同口径。
|
||||
header_to_field = None
|
||||
published = published_rival_snapshots_for_overlap(profile)
|
||||
candidates = [draft_snapshot, *published]
|
||||
sample_role_pollution = _detect_sample_role_pollution(profile)
|
||||
@@ -1243,7 +1253,9 @@ def _build_coordinate_overlap_evidence(
|
||||
outcomes: list[dict[str, Any]] = []
|
||||
for sample in samples:
|
||||
layout = _load_sample_layout(sample)
|
||||
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=candidates, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
parse_result = None
|
||||
if match.profile_code == profile.profile_code and int(match.version or 0) == int(profile.version):
|
||||
if parse_result_resolver is not None:
|
||||
@@ -1296,7 +1308,9 @@ def _build_coordinate_overlap_evidence(
|
||||
'reason_code': 'representative_layout_unavailable',
|
||||
})
|
||||
continue
|
||||
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=candidates, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
source_unique = (
|
||||
match.status in {'unique_match', 'selected_by_score'}
|
||||
and match.profile_code == published_snapshot.get('profile_code')
|
||||
|
||||
@@ -1072,7 +1072,12 @@ def _profile_table_candidates(
|
||||
'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match,
|
||||
}
|
||||
else:
|
||||
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
|
||||
# 主路由匹配与下游表格解析共用同一冻结 Schema 表头契约:matcher 侧
|
||||
# 表头原子互斥按别名归一为字段语义原子,跨措辞近亲模板不误杀。
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=coordinate_profiles, layout=layout,
|
||||
header_to_field=contract.header_to_field,
|
||||
)
|
||||
affinity_applied = False
|
||||
if not match_only:
|
||||
match = _apply_parse_validation_gate(
|
||||
@@ -1543,9 +1548,8 @@ def _apply_reparse_profile_affinity(
|
||||
), None)
|
||||
if candidate is None:
|
||||
return match, False
|
||||
verified = match_frozen_coordinate_profiles(profiles=[frozen], layout=layout)
|
||||
if verified.status != 'unique_match':
|
||||
return match, False
|
||||
# 契约编译须先于复验:复验与解析验证消费同一份冻结 Schema definition,
|
||||
# 表头原子互斥才能与正式取值走同一别名口径。
|
||||
schema_snapshot = (
|
||||
run.input_snapshot_json.get('schema')
|
||||
if isinstance(getattr(run, 'input_snapshot_json', None), dict)
|
||||
@@ -1556,6 +1560,18 @@ def _apply_reparse_profile_affinity(
|
||||
if isinstance(schema_snapshot, dict) and isinstance(schema_snapshot.get('definition'), dict)
|
||||
else {}
|
||||
)
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(schema_definition).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
|
||||
# 词级原子,不阻断重识别亲和性;definition 为空时编译结果为空映射,
|
||||
# matcher 侧与 None 同口径。
|
||||
header_to_field = None
|
||||
verified = match_frozen_coordinate_profiles(
|
||||
profiles=[frozen], layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
if verified.status != 'unique_match':
|
||||
return match, False
|
||||
parse_result = validate_profile_parse_candidate(
|
||||
profile_snapshot=frozen,
|
||||
layout=layout,
|
||||
@@ -2567,7 +2583,15 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document_model, layout=layout, page_nos=required_pages,
|
||||
)
|
||||
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
|
||||
try:
|
||||
header_to_field = compile_table_header_contract(definition).header_to_field
|
||||
except ValidationError:
|
||||
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
|
||||
# 词级原子,confirmed 字段锁集返回空,不抛错。
|
||||
header_to_field = None
|
||||
match = match_frozen_coordinate_profiles(
|
||||
profiles=profiles, layout=layout, header_to_field=header_to_field,
|
||||
)
|
||||
match, _affinity_applied = _apply_reparse_profile_affinity(
|
||||
run=run, unit=unit, profiles=profiles, match=match, layout=layout,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
tests/test_order_profile_header_identity.py
|
||||
|
||||
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
|
||||
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
|
||||
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
|
||||
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
|
||||
依赖:order_profile_matcher.schema_canonical_header_atoms /
|
||||
schema_canonical_header_tokens / _header_token_atoms /
|
||||
_header_discriminator_atoms_conflict。
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
schema_canonical_header_atoms,
|
||||
schema_canonical_header_tokens,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_none_or_empty_mapping_degrades_to_word_atoms():
|
||||
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
|
||||
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
|
||||
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
|
||||
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记原子
|
||||
assert not any(
|
||||
atom.startswith('field::')
|
||||
for atom in schema_canonical_header_atoms(tokens, None)
|
||||
)
|
||||
|
||||
|
||||
def test_exact_phrase_hit_emits_field_marker():
|
||||
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{'requested ship date': 'requested_receipt_date'},
|
||||
)
|
||||
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_merged_cell_greedy_decomposition():
|
||||
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
|
||||
|
||||
|
||||
def test_greedy_prefers_longest_phrase():
|
||||
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{
|
||||
'ship date': 'ship_date',
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_case_insensitive_matching():
|
||||
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['UNIT PRICE'],
|
||||
{'Unit Price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_unmatched_words_kept_and_short_words_filtered():
|
||||
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Total Amount ok the ab'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
|
||||
assert atoms == frozenset({'total', 'amount'})
|
||||
|
||||
mixed = schema_canonical_header_atoms(
|
||||
['Unit Price Remarks ok'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
|
||||
assert mixed == frozenset({'field::unit_price', 'remarks'})
|
||||
|
||||
|
||||
def test_empty_tokens_skipped():
|
||||
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['', ' ', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_chinese_alias_yields_no_field_atom():
|
||||
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['数量', 'Qty'],
|
||||
{'数量': 'quantity'},
|
||||
)
|
||||
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
|
||||
assert atoms == frozenset({'qty'})
|
||||
|
||||
|
||||
def test_casefold_collision_phrase_discarded():
|
||||
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{
|
||||
'Ship Date': 'ship_date',
|
||||
'ship date': 'requested_ship_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
|
||||
assert atoms == frozenset({'ship', 'date'})
|
||||
|
||||
|
||||
def test_casefold_equal_duplicate_alias_kept():
|
||||
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
|
||||
)
|
||||
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
|
||||
assert atoms == frozenset({'field::ship_date'})
|
||||
|
||||
|
||||
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
|
||||
|
||||
_SIGNATURE_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
_PO6075316_OBSERVED_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
_SCHEMA_V4_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _po6075316_signature() -> dict:
|
||||
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
|
||||
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
|
||||
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is False
|
||||
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
|
||||
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
|
||||
assert schema_canonical_header_atoms(
|
||||
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) == schema_canonical_header_atoms(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
|
||||
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(), observed=observed,
|
||||
) is True
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
) is True
|
||||
|
||||
|
||||
def test_po6075316_foreign_date_word_not_merged_by_alias():
|
||||
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
|
||||
observed = {'header_tokens': [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Customer PO Date Unit Price', '', 'Extension',
|
||||
]}
|
||||
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is True
|
||||
|
||||
|
||||
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
|
||||
|
||||
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
|
||||
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
|
||||
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
|
||||
assert schema_canonical_header_tokens(tokens, None) == tokens
|
||||
assert schema_canonical_header_tokens(tokens, {}) == tokens
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记项
|
||||
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
|
||||
|
||||
|
||||
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
|
||||
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Requested Ship Date', 'Remarks', 'Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
|
||||
assert canonical == [
|
||||
'field::requested_receipt_date', 'remarks', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
|
||||
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
|
||||
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
|
||||
assert canonical == [
|
||||
'field::unit_price', 'total', 'amount', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_dedup_equals_atoms_same_source_semantics():
|
||||
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
|
||||
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
|
||||
mapping = {
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
'vendor item': 'part_number',
|
||||
}
|
||||
canonical = schema_canonical_header_tokens(tokens, mapping)
|
||||
atoms = schema_canonical_header_atoms(tokens, mapping)
|
||||
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
|
||||
assert set(canonical) == set(atoms)
|
||||
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
|
||||
assert len(canonical) == len([item for item in canonical if item])
|
||||
|
||||
|
||||
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
|
||||
canonical_expected = schema_canonical_header_tokens(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
canonical_observed = schema_canonical_header_tokens(
|
||||
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
|
||||
# 供二次机会门禁按序列比较得出满配额软分
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
@@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_observe_layout_features,
|
||||
_resolve_coordinate_transform,
|
||||
_signature_identity_header_tokens,
|
||||
match_frozen_coordinate_profiles,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
@@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip():
|
||||
assert bbox is not None
|
||||
assert bbox[3] < 0.62
|
||||
assert bbox[3] > 0.50
|
||||
|
||||
|
||||
# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 ---
|
||||
|
||||
# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。
|
||||
_PO6075316_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。
|
||||
_PO6075316_FAULT_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。
|
||||
_PO6075316_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]:
|
||||
"""按列生成表头字符证据。
|
||||
|
||||
列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复);
|
||||
列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。
|
||||
"""
|
||||
glyphs: list[dict] = []
|
||||
cursor = x_start
|
||||
for token in tokens:
|
||||
first_of_column = True
|
||||
for index, char in enumerate(token):
|
||||
if char == ' ':
|
||||
continue
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1},
|
||||
'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'),
|
||||
})
|
||||
first_of_column = False
|
||||
cursor += 4.0
|
||||
cursor += column_gap
|
||||
return glyphs
|
||||
|
||||
|
||||
def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict:
|
||||
"""以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。"""
|
||||
layout = _layout()
|
||||
layout['coordinate_evidence']['pages']['1']['width'] = page_width
|
||||
header = _column_header_glyphs(tokens)
|
||||
layout['coordinate_evidence']['tables']['table-1'] = header
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*header,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_header_alias_contract_clears_all_po6075316_header_hard_gates():
|
||||
"""路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与
|
||||
signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
|
||||
# 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS
|
||||
|
||||
with_contract = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=_PO6075316_HEADER_TO_FIELD,
|
||||
)
|
||||
without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault)
|
||||
|
||||
contract_candidate = with_contract.candidates[0]
|
||||
plain_candidate = without_contract.candidates[0]
|
||||
# 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。
|
||||
assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥
|
||||
# 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。
|
||||
assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。
|
||||
assert contract_candidate.hard_match is True
|
||||
# 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。
|
||||
assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes
|
||||
|
||||
|
||||
def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection():
|
||||
"""反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。
|
||||
|
||||
证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical
|
||||
原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict
|
||||
分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator;
|
||||
断言落点是「仍被硬拒」:hard_match False 且综合分归零。
|
||||
"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _PO6075316_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
|
||||
partial = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
)
|
||||
candidate = partial.candidates[0]
|
||||
# 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。
|
||||
assert 'profile_header_discriminator_conflict' in candidate.reason_codes
|
||||
# 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。
|
||||
assert candidate.hard_match is False
|
||||
assert candidate.score == 0.0
|
||||
@@ -0,0 +1,69 @@
|
||||
# 计划:订单模板表头身份原子按 Schema 别名归一(契约层)
|
||||
|
||||
> 状态:已确认(2026-09-16,会话内评审)。执行方式:subagent-driven-development。
|
||||
> 背景:PO_6075316.pdf 因日期列名 `Requested Ship Date`(训练样本为 `Requested Arrival Date`)
|
||||
> 触发 `profile_header_discriminator_conflict`,11 模板全 0 分,layout_drift 转人工空单。
|
||||
> 契约层方案:表头身份原子比较前按冻结 Schema 的字段别名归一为字段语义类;
|
||||
> 原子集全等硬门禁与近亲模板互斥语义**不变**;复用现有别名机制,不新造轮子。
|
||||
|
||||
## Global Constraints(全局约束,评审时的注意力透镜)
|
||||
|
||||
1. 硬门禁不弱化:归一后仍要求原子集**全等**;不同字段类、Schema 外新词照样冲突。
|
||||
2. `header_to_field=None` 的所有路径行为与现状完全一致(向后兼容,已发布签名不重冻结)。
|
||||
3. 同义词唯一治理来源 = Schema `fields[].aliases`;matcher 不新增同义词表/配置面。
|
||||
4. 纯后端改动;不引入新第三方依赖;新函数/文件须满足 AGENTS §5 三层注释。
|
||||
5. 全程不 commit(用户规则);测试环境 Schema v4 **原位**补别名、不升版(用户确认)。
|
||||
6. 已确认:`Requested Ship Date` 归 `requested_receipt_date`。
|
||||
|
||||
## Task 1:核心纯函数 + 单测(文件 `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py`)
|
||||
|
||||
- 新增模块级常量 `_HEADER_FIELD_MARKER = 'field::'`(标记原子前缀;词级原子不可能含冒号,无碰撞)。
|
||||
- 新增 `schema_canonical_header_atoms(tokens: list[str], header_to_field: dict[str, str] | None) -> frozenset[str]`:
|
||||
- `header_to_field` 为 `TableHeaderContract.header_to_field`(普通 dict,鸭子类型,不引入 order_schema→matcher 反向依赖);
|
||||
- **None 时直接返回 `_header_token_atoms(tokens)`**(零行为变化);
|
||||
- 短语字典:对每个 alias key 先 `_HEADER_PAREN_GLOSS` 剥注记 → casefold → 按 `[^a-z0-9]+` 切词元组;**casefold 后跨字段碰撞的短语弃用**(身份归属不允许歧义);
|
||||
- 每个 token:空串跳过(吸收 MinerU 空格);同一词管线(剥注记/casefold/切词)后,**贪心最长短语匹配**(命中 → `_HEADER_FIELD_MARKER + field_code` 原子);未命中的剩余词沿用既有规则(≥`_HEADER_ATOM_MIN_LEN`、非 `_HEADER_ATOM_STOPWORDS`);
|
||||
- 中文别名经 `[^a-z0-9]+` 切词后为空 → 自然跳过(与词级原子只保留 `[a-z0-9]` 的现状一致),docstring 注明。
|
||||
- 单测(新文件 `backend/tests/test_order_profile_header_identity.py`,pure_unit):
|
||||
精确命中 / 合并格贪心分解(`requested ship date unit price` → 两个 field 标记)/ 大小写不敏感 /
|
||||
未命中词保留原词(含过短词过滤)/ 空串跳过 / casefold 碰撞短语弃用 / None 兼容。
|
||||
- Verify:`pytest tests/test_order_profile_header_identity.py -q` 全绿。
|
||||
|
||||
## Task 2:matcher 接线(同文件三层透传)
|
||||
|
||||
- `_header_discriminator_atoms_conflict(..., header_to_field: dict[str, str] | None = None)`:非 None 时两侧均用 Task 1 函数归一后比较;None 走现行为。
|
||||
- `_compute_dimension_results(..., header_to_field=None)` 透传(唯一调用点在 `match_frozen_coordinate_profiles` 主循环)。
|
||||
- `match_frozen_coordinate_profiles(..., header_to_field=None)` 透传 + docstring 同步。
|
||||
- Verify:matcher 既有测试套件全绿(执行时 `grep -rl match_frozen_coordinate_profiles tests/` 定位)。
|
||||
|
||||
## Task 3:调用点传入契约(5 处,与 Task 2 同一派发批次)
|
||||
|
||||
- `order_extraction_workflow.py` 主路由匹配处(约 :1075):传 `contract.header_to_field`(contract 已在作用域)。
|
||||
- `order_extraction_workflow.py` `_apply_reparse_profile_affinity` 内复验调用(约 :1546):先由 `run.input_snapshot_json` 冻结 definition 编译 `compile_table_header_contract` 再传入。
|
||||
- `order_extraction_workflow.py` `_confirmed_profile_order_fields`(约 :2570):同上,definition 已在作用域。
|
||||
- `order_document_profile_validation_service.py` 两处(约 :1246、:1299):从 `profile.schema_version.definition_json`(已在作用域)编译传入——满足"正式/验证/盲测同契约"。
|
||||
- Verify:`test_shipping_xfa_formal_extraction_route / test_shipping_order_extraction_worker / test_shipping_order_extraction_runs / test_shipping_document_profile_quality / test_order_document_profile_preview_service / test_order_extraction_pdf_po_split / test_shipping_notice_reservation_id` 全绿。
|
||||
|
||||
## Task 4:回归测试(新)
|
||||
|
||||
- matcher 级(放入 Task 1 测试文件):PO_6075316 形状观测 `['LN','Quantity','Part Number Vendor Item#','Description','Requested Ship Date Unit Price','','Extension']` vs 签名 token(`Requested Arrival Date` 版)——传契约不冲突;不传冲突;换真正异义词(如 `Customer PO Date` 未配别名)仍冲突。
|
||||
- 路由级合成用例:最小 frozen profile + layout 重放 `match_frozen_coordinate_profiles`,断言不再因 discriminator 拒绝(参考 tests/ 内既有 matcher 测试的构造方式)。
|
||||
- Verify:新旧用例全绿。
|
||||
|
||||
## Task 5:真实数据回归矩阵(离线重放,测试库 192.168.100.192/hxops_testing)
|
||||
|
||||
- T5.1 run 317(`SNER-20260916-C2AF1BF3`)冻结快照 + doc 879(PO_6075316)layout:向冻结 definition 注入 `Requested Ship Date` 别名(模拟治理后)→ 期望 HYVE 不再 `profile_header_discriminator_conflict`、score>0(理想 unique_match)。
|
||||
- T5.2 对照:不注入别名(=当前线上态)→ 仍 conflict(证明效果来自别名契约而非代码放水)。
|
||||
- T5.3 **全文档×全模板无翻转**:对 run 317 快照内全部文档,三种配置重放 `(i) 旧行为(header_to_field=None)`、`(ii) 新逻辑+现网 v4 别名`、`(iii) 新逻辑+注入别名`;断言 (ii)≡(i) 全部一致、(iii) 仅 879 变化其余全部一致。
|
||||
- T5.4 **模板自样本回归**:对每个已发布模板的 training/annotation 样本(layout_version_id 从 `shipping_order_document_profile_samples` 取,含坐标证据资产回填),新逻辑下各模板仍唯一自匹配。
|
||||
- Verify:输出留档 `.zcode/header_alias_replay/`。
|
||||
|
||||
## Task 6:Schema v4 原位补别名(测试库,用户已授权)+ 文档
|
||||
|
||||
- 控制器亲自执行:UPDATE `shipping_order_schema_versions`(version id=4)`definition_json` 中 `requested_receipt_date`(field_id `dfa4544a-b789-478e-ba1a-d19725817ac2`)的 aliases 追加 `'Requested Ship Date'`;改前备份原 JSON 到工作区,改后回读验证;同事务检查有无 checksum 列需同步(执行时核实)。
|
||||
- `docs/features/shipping-notice/technical.md`:补 2026-09-16 契约注记(身份原子按冻结 Schema 别名归一;别名是同义词唯一治理入口;硬互斥不变;v4 原位修订记录)。
|
||||
- `docs/funclist.md`:若存在模板匹配相关条目则补一句(执行时检查)。
|
||||
|
||||
## Task 7:收尾
|
||||
|
||||
全量相关测试套件;汇总验证输出;不 commit。
|
||||
Reference in new issue
Block a user