diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py index 4479dbae..de9e6ea3 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py @@ -17,6 +17,7 @@ backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py from __future__ import annotations +import logging import unicodedata from typing import Any, Callable @@ -38,6 +39,8 @@ from app.services.shipping_notice.document_layout.order_profile import ( OrderCoordinateProfile, ) +logger = logging.getLogger(__name__) + # 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。 OCR_RESCUE_CONFIDENCE_FLOOR = 0.8 # 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。 @@ -194,6 +197,18 @@ def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, An return out +def _default_read_asset_bytes(asset_id: int) -> bytes: + """按 id 加载 FileAsset 后读取字节;read_asset_bytes 接收 ORM 对象而非 id。""" + from app.extensions import db + from app.models import FileAsset + from app.services.file_assets.service import read_asset_bytes + + asset = db.session.get(FileAsset, int(asset_id)) + if asset is None: + raise LookupError(f'file asset not found: {asset_id}') + return read_asset_bytes(asset) + + def _collect_rescue_glyphs( *, document: Any, @@ -213,6 +228,8 @@ def _collect_rescue_glyphs( page_width = float(page.get('width') or 0) page_height = float(page.get('height') or 0) asset_id = int(getattr(document, 'asset_id', 0) or 0) + if read_asset_fn is None: + read_asset_fn = _default_read_asset_bytes # [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。 if asset_id > 0: try: @@ -247,9 +264,6 @@ def _collect_rescue_glyphs( if asset_id <= 0: return None try: - if read_asset_fn is None: - from app.services.file_assets.service import read_asset_bytes - read_asset_fn = read_asset_bytes if page_images_fn is None: from app.services.shipping_notice.document_layout.native_pdf import ( extract_native_pdf_pages, @@ -296,7 +310,15 @@ def _collect_rescue_glyphs( if band: return band, 'ocr_coordinate' return None - except (ValueError, TypeError, KeyError, OSError): + except Exception as exc: # noqa: BLE001 - 兜底来源失败时交回上层维持原判 + # [PARAM_TUNING] 2026-10-14 test 事故(SNER-20261014-8EBAB7A1):AttributeError + # 炸穿本层令整个 Unit 技术失败。收口语义保持「静默回退」,但必须留观测痕 + # 迹,否则只能靠 Unit error_message 反推。 + logger.warning( + 'order profile rescue glyphs failed document_id=%s error_type=%s', + int(getattr(document, 'id', 0) or 0), + type(exc).__name__, + ) return None @@ -341,9 +363,6 @@ def rescue_match_with_header_ocr( page = pages.get('1') or pages.get(1) if not isinstance(page, dict): return match - if read_asset_fn is None: - from app.services.file_assets.service import read_asset_bytes - read_asset_fn = read_asset_bytes _, _, probe_observed = _candidate_header_atoms( raw_profile=next(iter(eligible.values()))[1], layout=layout, @@ -390,6 +409,10 @@ def rescue_match_with_header_ocr( 'identity_rescue_source': rescue_source, 'candidates': marked_candidates, }) - except (ValueError, TypeError, KeyError, OSError): - # 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。 + except Exception as exc: # noqa: BLE001 - 补救属锦上添花:任何异常(含 AttributeError 等未预期类型错误)都回退原判,不得阻断抽取主链。 + logger.warning( + 'order profile rescue aborted document_id=%s error_type=%s', + int(getattr(document, 'id', 0) or 0), + type(exc).__name__, + ) return match diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 045ec50b..50f56a64 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -311,6 +311,51 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] | return dict(_AUTOMATIC_ACCEPTANCE_BY_MARKER[marker]) if marker in _AUTOMATIC_ACCEPTANCE_BY_MARKER else None +def _failed_unit_errors_by_document(run_id: int | None) -> dict[int, dict[str, str | None]]: + """ + 读取 Run 内 Unit 级失败事实(document_id → 错误码/消息),供收口裁决纠正文档级状态。 + + 核心逻辑:persist 的候选裁决只知道「有没有 pending」,不知道 Unit 是否技术失败; + Unit 全失败的附件没有任何产出裁决,禁止按零 pending 误写 completed + (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,批次中心误报通知完成)。 + + Args: + run_id: ShippingOrderProcessingRun 主键;为空时返回空表(领域单测路径)。 + + Returns: + document_id → {'error_code', 'error_message'} 映射。 + """ + if run_id is None: + return {} + from app.models import ShippingOrderProcessingPlan, ShippingOrderProcessingUnit + + rows = ( + db.session.query( + ShippingOrderProcessingUnit.document_id, + ShippingOrderProcessingUnit.error_code, + ShippingOrderProcessingUnit.error_message, + ) + .join( + ShippingOrderProcessingPlan, + ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id, + ) + .filter( + ShippingOrderProcessingPlan.run_id == int(run_id), + ShippingOrderProcessingUnit.status == 'failed', + ShippingOrderProcessingUnit.document_id.isnot(None), + ) + .all() + ) + return { + int(document_id): { + 'error_code': str(error_code or '').strip() or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED', + 'error_message': str(error_message or '').strip() or 'Order extraction unit failed', + } + for document_id, error_code, error_message in rows + if document_id is not None + } + + def persist_order_extraction_result( *, session: ChatSession, @@ -794,21 +839,31 @@ def persist_order_extraction_result( # [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。 has_unassigned_pending = any(not item.get('source_intake_no') for item in pending) + # Unit 失败事实优先:Unit 失败且无候选/待处理裁决的附件,识别并未完成, + # 必须落 failed(携带 Unit 错误码),禁止按「零 pending」误写 completed—— + # 否则随后的 Run 失败收口会因「已是终态」跳过回填,批次中心误报已完成。 + failed_unit_error_by_document = _failed_unit_errors_by_document(run_id) for document in documents: keys = document_candidate_keys[int(document.id)] - document.order_extraction_status = ( - 'partially_completed' - if document_has_pending[int(document.id)] or has_unassigned_pending - else 'completed' - ) + unit_failure = failed_unit_error_by_document.get(int(document.id)) + if unit_failure and not keys and not document_has_pending[int(document.id)]: + document.order_extraction_status = 'failed' + document.order_extraction_error_code = unit_failure['error_code'] + document.order_extraction_error_message = unit_failure['error_message'] + else: + document.order_extraction_status = ( + 'partially_completed' + if document_has_pending[int(document.id)] or has_unassigned_pending + else 'completed' + ) + document.order_extraction_error_code = None + document.order_extraction_error_message = None document.order_extraction_source = extraction_source document.order_extraction_result_json = { 'request_id': request_id, 'candidate_keys': keys, 'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)], } - document.order_extraction_error_code = None - document.order_extraction_error_message = None # [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。 # Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate @@ -836,13 +891,32 @@ def persist_order_extraction_result( duplicate_results_by_intake.get(int(intake.id), []), ) apply_duplicate_result_to_intake(intake, aggregate) - intake.order_extraction_status = ( - 'partially_completed' - if pending_by_intake[int(intake.id)] or has_unassigned_pending - else 'completed' + # Intake 聚合文档级终态:全部业务附件 failed → failed;部分失败 → partially_completed; + # 二者都不得被后续「零 pending 即 completed」的收口覆盖。 + intake_documents = documents_by_intake.get(int(intake.id)) or [] + failed_intake_documents = [ + document + for document in intake_documents + if str(document.order_extraction_status or '').strip().lower() == 'failed' + ] + business_document_count = sum( + 1 + for document in intake_documents + if str(document.document_type or '').strip().lower() != 'email_body' ) - intake.order_extraction_error_code = None - intake.order_extraction_error_message = None + if failed_intake_documents and business_document_count > 0 \ + and len(failed_intake_documents) >= business_document_count: + intake.order_extraction_status = 'failed' + intake.order_extraction_error_code = failed_intake_documents[0].order_extraction_error_code + intake.order_extraction_error_message = failed_intake_documents[0].order_extraction_error_message + elif failed_intake_documents or pending_by_intake[int(intake.id)] or has_unassigned_pending: + intake.order_extraction_status = 'partially_completed' + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None + else: + intake.order_extraction_status = 'completed' + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None intake.updated_at = datetime.utcnow() db.session.flush() @@ -1001,7 +1075,13 @@ def persist_order_extraction_result( for intake in intakes: intake.parse_status = 'consumed' intake.consumed_at = now - intake.order_extraction_status = 'completed' + # consumed 仅代表「邮件解析结果已被抽取收口消费」;文档/Intake 级 + # order_extraction_status 若已按 Unit 失败裁决为 failed/partially_completed, + # 不得在此覆盖回 completed——否则 Run 失败收口会因「已是终态」跳过回填。 + if str(intake.order_extraction_status or '').strip().lower() not in { + 'failed', 'partially_completed', + }: + intake.order_extraction_status = 'completed' intake.updated_at = now db.session.commit() diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 6a6b6b50..c2b100e3 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -498,7 +498,21 @@ def _email_parent_rows( if document_id <= 0 or document_id in existing_document_ids: continue parse_status = parse_statuses.get(intake_id, '') - parent_status = 'failed' if parse_status == 'parse_failed' else 'processing' + run_status = str(run.status or '').strip().lower() + if run_status in {'queued', 'processing'}: + # 运行中的 Run:EML 父项只区分解析失败与处理中。 + parent_status = 'failed' if parse_status == 'parse_failed' else 'processing' + else: + # [STEP] 终态 Run 的 EML 父项必须跟随 Run 结果收敛,禁止停留在「处理中」 + # (历史缺陷:全部 Unit 失败后父项仍显示处理中,误导用户批次仍在进行)。 + # partially_completed 的用户语义与 review_required 一致(需人工处理)。 + parent_status = { + 'failed': 'failed', + 'cancelled': 'cancelled', + 'completed': 'completed', + 'review_required': 'review_required', + 'partially_completed': 'review_required', + }.get(run_status, 'failed') rows.append({ 'unit_id': -document_id, 'document_id': document_id, diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index bf5cf5c8..ca0b597f 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -4263,14 +4263,17 @@ def project_conversation_processing_summary( if case.run_id is not None ) # 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析; - # 仅 load id/run_no,不触碰 Plan/Unit。 + # 仅 load id/run_no/status/error_code,不触碰 Plan/Unit。status/error_code + # 供摘要把「抽取收口 completed 但最新 Run 失败」的文档纠正为失败裁决。 latest_run_by_intake_id: dict[int, Any] = {} if intake_ids: - for intake_id, run_id, run_no in ( + for intake_id, run_id, run_no, run_status, run_error_code in ( db.session.query( ShippingOrderProcessingRunIntake.intake_id, ShippingOrderProcessingRun.id, ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.status, + ShippingOrderProcessingRun.error_code, ) .join( ShippingOrderProcessingRun, @@ -4287,7 +4290,12 @@ def project_conversation_processing_summary( key = int(intake_id) if key in latest_run_by_intake_id: continue - latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()} + latest_run_by_intake_id[key] = { + 'id': int(run_id), + 'run_no': str(run_no or '').strip(), + 'status': str(run_status or '').strip().lower(), + 'error_code': str(run_error_code or '').strip() or None, + } run_ids.add(int(run_id)) runs_by_id = { int(run.id): run @@ -4455,7 +4463,25 @@ def project_conversation_processing_summary( if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}: return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review' if raw in {'completed', 'uploaded'}: - return 'completed', 'completed', None + # 文档级 completed 只代表「抽取收口完成」,不是业务终态:通知完成必须 + # 以正式 OT/Notice/上传核验为前提,禁止把收口语义译成通知完成 + # (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed, + # 批次中心据此误报 9/9 已完成 + 通知完成)。 + if task is not None: + return 'completed', 'completed', None + if case is not None and case_status == 'non_order': + # 非订单处置是唯一无 OT 的合法业务完成出口。 + return 'completed', 'completed', None + latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {} + if str(latest_intake_run.get('status') or '').strip().lower() == 'failed': + # 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。 + return ( + 'failed', + stage, + str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', + ) + # 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。 + return 'running', stage, None if raw in {'cancelled', 'archived'}: return raw, raw, None return 'running', stage, None @@ -4499,9 +4525,22 @@ def project_conversation_processing_summary( stage = 'candidate_creating' case_status = str(getattr(case, 'status', None) or '').strip().lower() terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} - extraction_failed = str(document.order_extraction_status or '').strip().lower() in { - 'failed', 'parse_failed', 'technical_retrying', - } + # 抽取失败事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败」: + # 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义), + # 此时仍必须下发重解析入口,与 _status 的失败裁决同源。 + latest_intake_run_status = str( + (latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or '' + ).strip().lower() + extraction_failed = ( + str(document.order_extraction_status or '').strip().lower() in { + 'failed', 'parse_failed', 'technical_retrying', + } + or ( + task is None + and case is None + and latest_intake_run_status == 'failed' + ) + ) task_no = str(task.task_no).strip() if task is not None else None available_actions: list[str] = [] primary_action: dict[str, Any] | None = None diff --git a/backend/tests/test_order_extraction_workspace_projection.py b/backend/tests/test_order_extraction_workspace_projection.py new file mode 100644 index 00000000..d4ef55cd --- /dev/null +++ b/backend/tests/test_order_extraction_workspace_projection.py @@ -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' diff --git a/backend/tests/test_order_profile_ocr_rescue.py b/backend/tests/test_order_profile_ocr_rescue.py index e00377cd..7615ae85 100644 --- a/backend/tests/test_order_profile_ocr_rescue.py +++ b/backend/tests/test_order_profile_ocr_rescue.py @@ -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) diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 116fb61e..9859d728 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -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' diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 2f9c362d..e7cca132 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -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'