fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取

- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
This commit is contained in:
hugo committed 2026-10-14 22:40:37 +08:00
1 parent 92ed140739
commit 9f132564d6
8 files changed
+480 -39

No files matched your search

@@ -0,0 +1,85 @@
"""
tests/test_order_extraction_workspace_projection.py
用途:锁定工作台投影中 EML 父项状态的收敛契约。
依赖:order_extraction_workspace_projection._email_parent_rows。
逻辑:pure_unit;运行中的 Run(queued/processing)EML 父项维持既有口径
(parse_failed → failed,否则 processing);终态 Run 的 EML 父项必须跟随
Run 结果收敛(failed/cancelled/completed/review_required),禁止停留在
「处理中」——历史缺陷:全部 Unit 失败后父项仍显示处理中。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.shipping_notice.order_extraction_workspace_projection import (
_email_parent_rows,
)
pytestmark = pytest.mark.pure_unit
def _run_stub(status: str, parse_status: str | None = 'parsed') -> SimpleNamespace:
return SimpleNamespace(
status=status,
finished_at=None,
input_snapshot_json={'intakes': [{'intake_id': 1, 'parse_status': parse_status}]},
)
def _documents() -> dict[int, dict]:
return {
906: {'document_id': 906, 'intake_id': 1, 'document_type': 'email_body', 'file_name': 'batch.eml'},
}
def test_queued_run_email_parent_stays_processing():
"""运行中(queued)且未解析失败:EML 父项维持「处理中」(既有口径零变化)。"""
rows = _email_parent_rows(
run=_run_stub('queued'),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:queued 运行下父项 processing,阶段为邮件解析
assert rows[0]['status'] == 'processing'
assert rows[0]['user_visible_stage'] == 'email_parsing'
def test_failed_run_email_parent_converges_to_failed():
"""终态 failed 的 Run:EML 父项必须收敛为 failed,不得停留「处理中」。"""
rows = _email_parent_rows(
run=_run_stub('failed', parse_status=None),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:冻结 parse_status 为 None(消费型 Intake)时,failed Run 的父项
# 曾无条件渲染 processing;现在必须跟随 Run 结果收敛
assert rows[0]['status'] == 'failed'
assert rows[0]['user_visible_stage'] == 'failed'
def test_review_required_run_email_parent_converges_to_review():
"""终态 review_required / partially_completed:父项收敛为需人工复核语义。"""
for status in ('review_required', 'partially_completed'):
rows = _email_parent_rows(
run=_run_stub(status),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:两种终态都投影为 review_required(partially_completed 同义)
assert rows[0]['status'] == 'review_required', status
def test_parse_failed_intake_parent_stays_failed_under_active_run():
"""运行中但冻结 parse_status=parse_failed:父项仍为 failed(既有口径零变化)。"""
rows = _email_parent_rows(
run=_run_stub('processing', parse_status='parse_failed'),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:解析失败优先于处理中,技术失败原因码保留
assert rows[0]['status'] == 'failed'
assert rows[0]['technical_failure_reason_code'] == 'intake_parse_failed'
@@ -316,6 +316,33 @@ def test_rescue_prefers_acroform_widgets_over_ocr(monkeypatch):
assert result.status == 'unique_match'
def test_rescue_never_leaks_asset_read_errors(monkeypatch):
"""资产读取抛 AttributeError(test 环境真实故障:int 传入 read_asset_bytes 访问
.deleted_at)必须被收口为维持原判,不得炸穿抽取 Unit。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
def broken_read_asset(asset_id):
raise AttributeError("'int' object has no attribute 'deleted_at'")
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
read_asset_fn=broken_read_asset,
)
# 关键断言:补洞证据读取的任意异常都收口为原判返回
assert result is match
def test_rescue_skipped_for_non_failed_status():
"""常规匹配已成功(如 unique_match)时绝不触发证据补洞。"""
match = ProfileMatchResult(
@@ -331,3 +358,49 @@ def test_rescue_skipped_for_non_failed_status():
read_asset_fn=lambda asset_id: (_ for _ in ()).throw(AssertionError('asset must not run')),
)
assert result is match
def test_default_read_asset_loads_orm_before_read_asset_bytes(monkeypatch):
"""默认资产读取必须先加载 FileAsset ORM 再交给 read_asset_bytes。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——默认接线曾把
document.asset_id(int)直接传给 read_asset_bytes,第一行访问
``asset.deleted_at`` 即抛 AttributeError,炸穿补救层令整个抽取 Unit
技术失败。本测试锁定默认接线契约:read_asset_bytes 只接收 ORM 对象。
"""
from types import SimpleNamespace as NS
import app.extensions as extensions
import app.services.file_assets.service as asset_service
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
_default_read_asset_bytes,
)
received_objects: list[object] = []
def fake_read_asset_bytes(asset):
received_objects.append(asset)
return b'%PDF-default-wired'
fake_asset = NS(id=7, deleted_at=None)
class FakeSession:
def get(self, model, asset_id):
assert model is not int and asset_id == 7
return fake_asset
monkeypatch.setattr(asset_service, 'read_asset_bytes', fake_read_asset_bytes)
monkeypatch.setattr(extensions, 'db', NS(session=FakeSession()))
# 关键断言 1:默认接线按 id 取 ORM,read_asset_bytes 收到对象而非 int。
assert _default_read_asset_bytes(7) == b'%PDF-default-wired'
assert received_objects == [fake_asset]
# 关键断言 2:资产不存在时抛 LookupError(可被补救层收口为原判)。
class MissingSession:
def get(self, model, asset_id):
return None
monkeypatch.setattr(extensions, 'db', NS(session=MissingSession()))
with pytest.raises(LookupError):
_default_read_asset_bytes(404)
@@ -1697,3 +1697,70 @@ def test_merge_chat_log_payload_requires_exact_turn_ownership(app):
'existing_key': 'kept',
'shipping_order_extraction_state': {'status': 'completed'},
}
def test_persist_close_out_marks_failed_units_failed_not_completed(app):
"""Unit 全失败的空结果收口必须写 failed,禁止把附件误标为识别完成。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——persist 在 orders=[]
时按「零 pending」把附件 order_extraction_status 写成 completed;随后的
Run 失败收口因「已是 completed 终态」跳过回填,批次进度中心据此把整批
误报为已完成/通知完成。
"""
with app.app_context():
user, session, intake, document, _runtime_context = _seed_extraction_input()
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
run = ShippingOrderProcessingRun(
run_no='SNER-FAILED-UNITS-CLOSE-OUT',
user_id=int(user.id),
owner_agent_id=int(agent.id),
conversation_id=session.session_id,
schema_version_id=int(schema.id),
input_snapshot_hash='failed-units-close-out-snapshot',
input_snapshot_json={},
idempotency_key='failed-units-close-out-run',
status='processing',
)
plan = ShippingOrderProcessingPlan(
run=run,
plan_version='test.v1',
input_snapshot_hash=run.input_snapshot_hash,
unit_count=1,
)
unit = ShippingOrderProcessingUnit(
plan=plan,
intake_id=int(intake.id),
document_id=int(document.id),
position=0,
unit_type='document_extraction',
document_type='attachment',
status='failed',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
error_message="'int' object has no attribute 'deleted_at'",
)
db.session.add_all([run, plan, unit])
db.session.commit()
persist_order_extraction_result(
session=session,
intakes=[intake],
documents=[document],
current_snapshot='failed-units-close-out-snapshot',
request_id='SNER-FAILED-UNITS-CLOSE-OUT',
orders=[],
run_id=int(run.id),
schema_version_id=int(schema.id),
extraction_source='deterministic_order_parser',
auto_create_enabled=False,
)
db.session.commit()
db.session.refresh(document)
db.session.refresh(intake)
# 关键断言 1:Unit 失败且零候选裁决 → 文档必须落 failed 并携带 Unit 错误码。
assert document.order_extraction_status == 'failed'
assert document.order_extraction_error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
# 关键断言 2:全部附件失败 → Intake 同步 failed;consumed 保留(孤儿重解析依赖)。
assert intake.order_extraction_status == 'failed'
assert intake.parse_status == 'consumed'
@@ -1504,15 +1504,20 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None:
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。"""
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。
回归语义(SNER-20261014-8EBAB7A1):无 OT 的文档级 completed 只是抽取收口,
摘要不再译成业务已完成;混合场景改用 failed + processing 两类真实用户分组。
"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, intake, completed_document = _seed_run_input(
user, _agent, session, intake, failed_document = _seed_run_input(
suffix='SUMMARY-MIXED-EML-LEAF-STATUS',
)
intake.source_type = 'eml'
completed_document.order_extraction_status = 'completed'
failed_document.order_extraction_status = 'failed'
failed_document.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
processing_document = ShippingOrderDocument(
intake_id=intake.id,
document_type='attachment',
@@ -1531,17 +1536,17 @@ def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> Non
conversation_id=session.session_id,
)['conversation_processing']
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在失败容器。
failed_rows = projection['status_groups']['failed']
processing_rows = projection['status_groups']['processing']
completed_rows = projection['status_groups']['completed']
assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [
processing_document.id,
]
assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [
completed_document.id,
assert [child['source_summary']['document_id'] for child in failed_rows[0]['aggregate_children']] == [
failed_document.id,
]
assert projection['summary']['processing_files'] == 1
assert projection['summary']['completed_files'] == 1
assert projection['summary']['failed_files'] == 1
assert projection['summary']['total_files'] == 2
@@ -3423,3 +3428,58 @@ def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized
assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf'
# 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。
assert _batch_file_counts(merged)['total_files'] == 1
def test_summary_failed_run_does_not_project_document_completed_as_upload_complete(app) -> None:
"""Run 失败时文档级 completed(抽取收口语义)不得译成业务终态「通知完成」。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——9 个 Unit 全部
ORDER_EXTRACTION_UNIT_FAILED,persist 收口零 pending 仍把附件写成
order_extraction_status='completed';首屏摘要 _status() 据此映射
('completed','completed'),批次进度中心误报 9/9 已完成 + 通知完成。
"""
with app.app_context():
from datetime import datetime
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-CLOSEOUT-NOT-COMPLETE',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
for unit in run.extraction_plan.units:
unit.status = 'failed'
unit.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
run.status = 'failed'
run.phase = 'failed'
run.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
# 脏数据形态:persist 收口已把文档/Intake 写成 completed(抽取收口 ≠ 业务完成)。
document.order_extraction_status = 'completed'
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.order_extraction_status = 'completed'
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
projection = payload['conversation_processing']
leaf = next(
child
for rows in projection['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
if child['source_summary']['document_id'] == document.id
)
# 关键断言 1:无 OT/Notice 的文件不可能投影为「通知完成」。
assert leaf['ui_state']['lifecycle_stage'] != 'upload_complete'
# 关键断言 2:失败文件不得计入批次已完成统计。
assert projection['summary']['completed'] == 0
# 关键断言 3:与全量视图同判词 —— 失败停接收解析,主动作是重解析。
assert leaf['user_group'] == 'failed'
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['code'] == 'reparse'