feat(shipping-notice): 增强发货通知与订单抽取功能,支持多进程处理与紧急停止

- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置
- 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS
- 实现发货通知 worker 进程,支持并发处理订单抽取任务
- 引入紧急停止功能,允许管理员在运行中控制订单解析状态
- 更新相关 API,支持读取与设置紧急停止状态
- 增强文档与代码注释,反映新的业务逻辑与功能要求
This commit is contained in:
hugo committed 2026-07-31 18:00:49 +08:00
1 parent d0fe084999
commit b352c281d5
149 files changed
+12550 -1874

No files matched your search

+20 -1
View File
@@ -7,9 +7,11 @@ tests/conftest.py
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError。
"""
import pytest
import shutil
from pathlib import Path
import pytest
@pytest.fixture(autouse=True)
def _capture_legacy_order_rows_for_tests(monkeypatch):
@@ -401,6 +403,23 @@ def pytest_configure(config):
config.option.basetemp = str(basetemp)
def pytest_unconfigure(config):
"""
测试结束后删除仓库内显式指定的旧式 pytest 临时目录。
核心逻辑:仅清理 backend 直属且名称以 .pytest- 开头的 basetemp;默认
backend/.pytest_tmp/run 保留复用,仓库外路径与其他目录不处理。
"""
basetemp_value = getattr(config.option, 'basetemp', None)
if not basetemp_value:
return
backend_dir = Path(__file__).resolve().parents[1]
basetemp = Path(basetemp_value).resolve()
if basetemp.parent == backend_dir and basetemp.name.startswith('.pytest-'):
shutil.rmtree(basetemp, ignore_errors=True)
@pytest.fixture
def app():
from app import create_app, db
@@ -220,3 +220,64 @@ def test_frozen_sample_preview_token_isolated_by_actor_and_sample(app, monkeypat
headers=owner_headers,
)
assert wrong_sample.status_code == 404
def test_frozen_sample_region_diagnostics_reads_only_configured_regions_in_visual_order(app, monkeypatch):
"""
冻结诊断只可读取模板已登记区域,并按视觉行内横坐标返回实际识别值。
关键断言:字符 y0 顺序故意为 C、A、B,接口仍返回 ABC;配置值匹配状态为真,
且响应不包含页面全文、字符坐标或客户端提交的任意区域。
"""
profile = SimpleNamespace(id=9, definition_json={
'document_match': {'required_anchors': [{
'anchor_id': 'plant', 'label': 'PLANT', 'value': 'ABC', 'page_no': 1,
'label_region': {'x0': .05, 'y0': .05, 'x1': .35, 'y1': .25},
'value_region': {'x0': .45, 'y0': .05, 'x1': .8, 'y1': .25},
}]},
'table_regions': [{
'page_scope': 'first_page', 'header_layouts': [], 'line_layouts': [],
'draft_unbound_field_regions': [{
'region_id': 'pending-column', 'parent_layout_id': 'main', 'label': '待绑定列',
'region': {'x0': .45, 'y0': .3, 'x1': .8, 'y1': .5},
}],
}],
'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
})
sample = SimpleNamespace(id=8)
document = SimpleNamespace(id=7)
layout = SimpleNamespace(payload_json={
'tables': [],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [
*[
{'text': char, 'bbox': {'x0': 10 + index * 5, 'y0': 10, 'x1': 14 + index * 5, 'y1': 20}}
for index, char in enumerate('PLANT')
],
{'text': 'A', 'bbox': {'x0': 100, 'y0': 12, 'x1': 108, 'y1': 22}},
{'text': 'B', 'bbox': {'x0': 115, 'y0': 14, 'x1': 123, 'y1': 24}},
{'text': 'C', 'bbox': {'x0': 130, 'y0': 10, 'x1': 138, 'y1': 20}},
{'text': 'VALUE', 'bbox': {'x0': 100, 'y0': 35, 'x1': 140, 'y1': 45}},
]},
},
})
monkeypatch.setattr(
preview_service, '_frozen_sample_context',
lambda **_kwargs: (profile, sample, document, layout, SimpleNamespace()),
)
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
with app.app_context():
result = preview_service.frozen_sample_region_diagnostics(
9, sample_binding_id=8, page_no=1, actor_id=1,
)
by_id = {item['region_id']: item for item in result['items']}
assert by_id['plant_label']['recognized_value'] == 'PLANT'
assert by_id['plant_value']['recognized_value'] == 'ABC'
assert by_id['plant_value']['matches_configured'] is True
assert by_id['pending-column']['recognized_value'] == 'VALUE'
assert set(by_id['plant_value']) == {
'region_id', 'kind', 'label', 'recognized_value', 'configured_value', 'matches_configured',
}
@@ -95,3 +95,13 @@ def test_current_sample_summary_rejects_empty_fields_or_values():
assert validation_service._current_sample_summary(
line_field_count=2, line_value_count=1, header_field_count=1, header_value_count=0, sample_role='annotation',
)[0] == 'passed'
def test_current_sample_summary_rejects_missing_required_header_value():
"""关键断言:即使明细已有值,任一必填订单头未确认也不能通过当前样本验证。"""
status, summary, _snapshot = validation_service._current_sample_summary(
line_field_count=2, line_value_count=2, header_field_count=3, header_value_count=2,
header_required_missing_count=1, sample_role='annotation',
)
assert status == 'failed'
assert summary['failure_code'] == 'order_profile_current_sample_required_header_missing'
@@ -5,8 +5,9 @@ backend/tests/test_shipping_audit_db_immutability.py
依赖:ShippingAuditEvent ORM 守卫、audit_service.append_shipping_audit_event、SQLAlchemy dialect。
逻辑:pytest TestingConfig 强制 SQLite create_all,无 DB 触发器 —— 仅断言 ORM append-only;
触发器断言在非 PostgreSQL 时 pytest.skip(迁移 a0e1f2b3c4d5 仅对 PG 生效)。
目标 PostgreSQL 环境请另跑:
``python scripts/verify_shipping_audit_pg_immutability.py``(日志不输出连接凭据)。
目标 PostgreSQL 环境发布前须另跑:
``python scripts/verify_shipping_audit_pg_immutability.py``(日志不输出连接凭据);
本地 dev DATABASE_URL=postgresql 时该脚本应输出 UPDATE/DELETE blocked。
"""
from __future__ import annotations
@@ -50,6 +50,58 @@ def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]:
return result
def _adaptive_layouts() -> list[dict]:
"""构造可变视觉子行的通用列配置,供自适应重建回归测试复用。"""
return [
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .1, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .5, 'y1': 1}},
]},
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'field_regions': [
{'field_code': 'qty', 'region': {'x0': .5, 'y0': 0, 'x1': .65, 'y1': 1}},
{'field_code': 'uom', 'region': {'x0': .65, 'y0': 0, 'x1': .77, 'y1': 1}},
{'field_code': 'requested_receipt_date', 'region': {'x0': .77, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'price', 'row_offset': 2, 'role': 'continuation', 'field_regions': [
{'field_code': 'unit_price', 'region': {'x0': .3, 'y0': 0, 'x1': .65, 'y1': 1}},
{'field_code': 'line_amount_with_tax', 'region': {'x0': .72, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'reference', 'row_offset': 3, 'role': 'continuation', 'field_regions': [
{'field_code': 'reservation_id', 'region': {'x0': .45, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
]
def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows():
"""显式策略应同时读取同一行或拆行的数量、单位、日期与金额,旧默认策略不受影响。"""
compact = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('6', 5), ('Street Address', 60), ('Building Road', 120)],
[('10', 5), ('PART-A', 60)], [('9.000', 115), ('PCS', 145), ('2026/07/10', 170)],
[('898.72', 80), ('8,088.48', 165)], [('R2 @2000485617', 115)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, line_layouts=_adaptive_layouts(),
row_reconstruction_mode='adaptive_record_columns',
)
expanded = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 5), ('PART-A', 60)], [('30.000', 120)], [('PCS', 150)], [('2026/07/21', 175)],
[('941.76', 120), ('28,252.80', 175)], [('R2 @1000130205', 115)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(),
row_reconstruction_mode='adaptive_record_columns',
)
# Both layouts must yield a complete logical record despite their different visual-band counts.
assert compact[0].fields == {
'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS',
'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48',
'reservation_id': '2000485617',
}
assert expanded[0].fields == {
'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '30.000', 'uom': 'PCS',
'requested_receipt_date': '2026/07/21', 'unit_price': '941.76', 'line_amount_with_tax': '28,252.80',
'reservation_id': '1000130205',
}
def _reconstruct(characters: list[dict]):
"""使用三列已确认表头区间,模拟 MinerU 网格失真后的 PDF 原生证据。"""
return reconstruct_table_from_positioned_text(
@@ -351,7 +403,7 @@ def test_coordinate_profile_rows_restore_pdf_visual_spaces():
def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them_for_preview():
"""正式解析排除删除行,标注预览可显式返回同一行的删除证据。"""
"""排除区显式授权删除标记后,正式解析排除该行,预览则保留删除证据。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-DELETED', 65)],
@@ -362,7 +414,7 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
]}], exclusion_regions=[{'x0': .25, 'y0': .3, 'x1': .8, 'y1': .5}],
)
assert [row.fields for row in rows] == [{'customer_po_line_no': '00020', 'part_number': 'PART-KEEP'}]
@@ -375,12 +427,28 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}], include_deleted=True,
]}], exclusion_regions=[{'x0': .25, 'y0': .3, 'x1': .8, 'y1': .6}], include_deleted=True,
)
# 关键断言:预览保留被删除的原始明细,但角色明确标识为不可纳入结果。
assert [(row.fields['customer_po_line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
def test_coordinate_profile_rows_ignore_unconfigured_deleted_marker():
"""关键断言:没有排除区授权时,删除文字不能擅自删除前一条有效订单明细。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-KEEP', 65)],
[('** Item deleted **', 65)],
[('00020', 10), ('PART-NEXT', 65)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}], include_deleted=True,
)
assert [(row.fields['customer_po_line_no'], row.role) for row in rows] == [('00010', 'data'), ('00020', 'data')]
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
"""脱敏回放 F9A1:四条物理行只合并为一条,并只读取已绑定的标准字段。"""
rows = reconstruct_coordinate_profile_rows(
@@ -419,10 +487,26 @@ def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schem
assert rows[0].fields == {
'customer_po_line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
'qty': '3.000', 'uom': 'PCS', 'required_date': '2026/05/05', 'incoterm': 'EXW SGSIN DBS',
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '@ 3000092530',
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '3000092530',
}
def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign():
"""预约号框只覆盖十位数字时仍须识别,不能把 ``@`` 当作业务值的一部分。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)],
[('898.72', 80), ('898.72', 165)], [('3000097059', 115)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
line_layouts=_adaptive_layouts(),
row_reconstruction_mode='adaptive_record_columns',
)
# 合法纯数字与带 @ 后缀使用同一业务校验,并统一输出纯号码。
assert rows[0].fields['reservation_id'] == '3000097059'
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
rows = reconstruct_coordinate_profile_rows(
@@ -480,7 +564,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .2, 'x1': 1, 'y1': .35}},
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .36, 'x1': .52, 'y1': .5}},
],
}],
}], exclusion_regions=[{'x0': 0, 'y0': .55, 'x1': .5, 'y1': .85}],
)
assert deleted == []
@@ -595,7 +679,7 @@ def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary():
"""脱敏回放 4518838152:删除标记废弃 00010,合计后的记录不允许泄漏。"""
"""脱敏回放 4518838152:配置区内删除标记废弃 00010,合计后的记录不允许泄漏。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('6Y70B2501901', 62), ('0', 210), ('EA', 225)],
@@ -623,7 +707,7 @@ def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary
{'layout_id': 'terms', 'row_offset': 2, 'field_regions': [
{'field_code': 'incoterm', 'region': {'x0': .18, 'y0': 0, 'x1': .62, 'y1': 1}},
]},
],
], exclusion_regions=[{'x0': .2, 'y0': .35, 'x1': .65, 'y1': .48}],
)
assert len(rows) == 1
@@ -20,6 +20,7 @@ from app.services.shipping_notice.document_layout.lifecycle import (
schedule_document_layouts,
sync_layout_after_job_recovery,
)
from app.services.shipping_notice.document_layout import lifecycle as layout_lifecycle
def _document() -> ShippingNoticeDocument:
@@ -151,22 +152,33 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
assert ShippingDocumentLayoutVersion.query.count() == 2
def test_layout_parser_revision_change_creates_new_version_without_force(app):
"""运维提升 parser revision 后不得复用旧 Provider/模型结果。"""
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
"""布局实现指纹变化后自动创建新版本,不依赖人工修改环境变量。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
document = _document()
old = record_inline_layout_snapshot(
document, _snapshot(),
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:v1',
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:sha256-old',
)
app.config['SHIPPING_NOTICE_LAYOUT_PARSER_REVISION'] = 'v2'
monkeypatch.setattr(layout_lifecycle, 'layout_parser_implementation_fingerprint', lambda: 'newfingerprint')
new = schedule_layout_version(document)
db.session.commit()
assert new.id != old.id
assert new.version == 2
assert new.parser_key.endswith(':v2')
assert new.parser_key.endswith(':sha256-newfingerprint')
def test_layout_parser_fingerprint_ignores_unrelated_app_config(app):
"""无关业务配置变化不能让所有 PDF 布局缓存失效。"""
with app.app_context():
before = layout_lifecycle.current_layout_parser_key()
app.config['UNRELATED_CHAT_SETTING'] = 'changed'
after = layout_lifecycle.current_layout_parser_key()
assert before == after
assert ':sha256-' in before
def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
@@ -149,6 +149,22 @@ def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence():
assert candidate.capability.issues == ['mineru_cell_coordinates_missing']
def test_mineru_candidate_accepts_async_table_html_and_page_no_fields():
"""异步结果使用 table_html/content_type/page_no 时仍须恢复同一表格候选。"""
payload = _mineru_payload()
content = json.loads(payload['results']['fixture']['content_list'])
table = content[0]
table['content_type'] = table.pop('type')
table['table_html'] = table.pop('table_body')
table['page_no'] = table.pop('page_idx') + 1
payload['results']['fixture']['content_list'] = json.dumps(content)
candidate = parse_mineru_candidate(payload)
assert len(candidate.pages[0].tables) == 1
assert candidate.pages[0].tables[0].row_count == 2
def test_mineru_capability_accepts_explicit_cell_coordinate_objects():
"""服务未来直接返回带行列身份的 cell bbox 时能力报告才能标记证据就绪。"""
candidate = parse_mineru_candidate(_mineru_payload(with_cell_coordinates=True))
@@ -24,6 +24,7 @@ from app.services.shipping_notice.document_layout.mineru import (
from app.services.shipping_notice.document_layout.native_pdf import (
NativePdfPage,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
)
from app.services.shipping_notice.document_layout.ocr_pdf import (
@@ -75,6 +76,71 @@ def _page(text: str) -> NativePdfPage:
)
def _fallback_page() -> NativePdfPage:
"""构造无框多行明细表;MinerU 未给 table 时只允许稳定表头触发原生 PDF 兜底。"""
characters = []
for y, entries in [
(10, [('Item', 10), ('Material', 45), ('Manufacturer', 95), ('VendorPartNumber', 160)]),
(22, [('Description', 10), ('Quantity', 135), ('Delivery', 175)]),
(42, [('00010', 10), ('PART-A', 45), ('ACME', 95), ('VENDOR-A', 160)]),
(54, [('1.000', 135), ('PCS', 158), ('2026/08/01', 175)]),
(72, [('Total:', 120), ('100.00', 175)]),
]:
for text, x0 in entries:
for index, char in enumerate(text):
characters.append(PositionedCharacter(
text=char, source_index=len(characters),
bbox=LayoutBBox(x0=x0 + index * 5, y0=y, x1=x0 + index * 5 + 4, y1=y + 8),
))
return NativePdfPage(
page_no=1, width=220, height=100, rotation=0,
characters=characters, image=np.full((200, 440), 255, dtype=np.uint8),
)
def test_native_pdf_text_fallback_recovers_unbordered_table_only_with_multi_column_header():
"""无框表必须由多列通用表头和合计终止双门禁恢复,付款说明等文本不可误入候选。"""
with patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[_fallback_page()],
):
tables = build_native_pdf_text_table_fallbacks(b'%PDF')
assert len(tables) == 1
assert tables[0]['source'] == 'native_pdf_text_header_fallback'
assert '<th>Item</th>' in tables[0]['html']
assert '00010' in tables[0]['html']
assert 'Total:' not in tables[0]['html']
def test_native_pdf_text_fallback_accepts_po_header_synonyms_without_false_page_header():
"""PO 常见 ITEM/MATERIAL/ORDER QUANTITY 表头应恢复,PURCHASE ORDER 页眉不得抢先命中。"""
characters = []
for y, entries in [
(10, [('PURCHASE', 10), ('ORDER', 80), ('PAGE', 150)]),
(30, [('ITEM NO', 10), ('MATERIAL NO', 55), ('MATERIAL DESCRIPTION', 110), ('ORDER QUANTITY', 185)]),
(42, [('00010', 10), ('PART-A', 55), ('SET RACK', 110), ('30 EA', 185)]),
(54, [('Ship by sea', 110), ('2026/08/01', 185)]),
(66, [('______________________________', 10)]),
]:
for text, x0 in entries:
for index, char in enumerate(text):
characters.append(PositionedCharacter(
text=char, source_index=len(characters),
bbox=LayoutBBox(x0=x0 + index * 4, y0=y, x1=x0 + index * 4 + 3, y1=y + 8),
))
page = NativePdfPage(
page_no=1, width=260, height=100, rotation=0, characters=characters,
image=np.full((200, 520), 255, dtype=np.uint8),
)
tables = build_native_pdf_text_table_fallbacks(b'%PDF', native_pages=[page])
assert len(tables) == 1
assert '<th>ITEM NO</th>' in tables[0]['html']
assert 'PURCHASE' not in tables[0]['html']
def test_native_pdf_unique_text_builds_traceable_needs_review_layout():
"""唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。"""
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
@@ -1,14 +1,14 @@
"""
backend/tests/test_shipping_document_layout_runtime.py
用途:验证 Intake 阶段 MinerU 紧凑文本/表格快照、降级行为和容量门禁。
用途:验证 Intake 阶段 MinerU 紧凑快照、PDFium 页面复用、降级行为和容量门禁。
依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。
逻辑:Mock 客户端避免真实网络;只允许受预算文本块、表格 HTML 和能力摘要进入快照,原响应不得持久化。
"""
from __future__ import annotations
from unittest.mock import patch
from unittest.mock import call, patch
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
@@ -102,6 +102,133 @@ def test_runtime_limits_persisted_mineru_text(app):
assert 'mineru_text_budget_exceeded' in snapshot['issues']
def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app):
"""单次 PDF 快照只允许提取/渲染一次页面,后续三个本地阶段必须复用同一对象。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
native_pages = [object()]
timings: dict[str, int] = {}
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
return_value={'status': 'completed'},
), patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=_candidate().model_copy(update={'pages': [
_candidate().pages[0].model_copy(update={'tables': []}),
]}),
), patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=native_pages,
) as extract_pages, patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
return_value=[],
) as fallback, patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'test'},
) as build_evidence:
build_layout.return_value.model_dump.return_value = {'version': 'layout.v1'}
snapshot = build_mineru_table_snapshot(
filename='order.pdf',
content=b'%PDF',
document_id=1,
content_hash='hash',
timings=timings,
)
assert snapshot['status'] == 'ready'
assert extract_pages.call_args_list == [
call(b'%PDF', render_images=False),
call(b'%PDF'),
]
assert fallback.call_args.kwargs['native_pages'] is native_pages
assert build_layout.call_args.kwargs['native_pages'] is native_pages
assert build_evidence.call_args.kwargs['pages'] is native_pages
assert 'mineru_wait_ms' in timings
assert 'native_pdf_extract_ms' in timings
assert 'shipping_document_business_table_not_detected' in snapshot['issues']
def test_runtime_native_pdf_fast_path_skips_mineru_when_strict_table_evidence_exists(app):
"""文字型 PDF 可证明订单表格时应立即完成,不得继续等待 MinerU。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})()
table = {
'table_id': 'native-1', 'page_no': 1,
'bbox': {'x0': 0, 'y0': 20, 'x1': 100, 'y1': 100},
'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .5},
'html': '<table><tr><th>Item</th><th>Material</th><th>Qty</th></tr><tr><td>10</td><td>A</td><td>1</td></tr></table>',
'row_count': 2, 'cell_count': 6, 'has_rowspan': False, 'has_colspan': False,
}
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[page],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
return_value=[table],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'shipping_order_coordinate_evidence.v1'},
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
) as mineru:
build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'}
timings: dict[str, int] = {}
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF', document_id=1,
content_hash='a' * 64, timings=timings,
)
assert snapshot['status'] == 'ready'
assert snapshot['provider'] == 'pdfium'
assert snapshot['tables'][0]['table_id'] == 'native-1'
assert timings['layout_fast_path'] == 1
mineru.assert_not_called()
def test_runtime_native_fast_path_defers_page_rendering(app):
"""本地文字证据命中时只提取字符,不能预先渲染高分辨率页面图。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})()
table = {
'table_id': 'native-1', 'page_no': 1,
'bbox': {'x0': 0, 'y0': 20, 'x1': 100, 'y1': 100},
'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .5},
'html': '<table><tr><th>Item</th><th>Qty</th></tr><tr><td>10</td><td>1</td></tr></table>',
'row_count': 2, 'cell_count': 4, 'has_rowspan': False, 'has_colspan': False,
}
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[page],
) as extract_pages, patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
return_value=[table],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'test'},
):
build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'}
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF', document_id=1, content_hash='b' * 64,
)
assert snapshot['provider'] == 'pdfium'
extract_pages.assert_called_once_with(b'%PDF', render_images=False)
def test_runtime_provider_failure_is_safe_fallback(app):
"""MinerU 失败只记录错误码并返回空表,不能抛出导致 Intake 文本解析失败。"""
app.config.update(
@@ -9,6 +9,7 @@ backend/tests/test_shipping_document_profile_quality.py
from __future__ import annotations
from datetime import datetime
from types import SimpleNamespace
import pytest
@@ -32,6 +33,23 @@ from app.services.shipping_notice.document_layout.lifecycle import record_inline
from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint
def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source():
"""盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。"""
evidence = {
'tables': {'table-1': [{'text': 'TABLE'}]},
'page_glyphs': {'1': [{'text': 'PAGE'}]},
}
raw_table = {'page_no': 1}
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'TABLE'}]
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'PAGE'}]
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingNoticeDocument]]:
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
@@ -0,0 +1,159 @@
"""
tests/test_shipping_generic_order_completeness.py
用途:锁定通用解析完整性报告的列/行计数与可忽略列表头契约。
依赖:generic_order_completeness、generic_order_gate。
逻辑:未映射非空列计入缺口;Schema ignorable_column_headers 命中后不得阻断。
"""
from __future__ import annotations
from decimal import Decimal
from types import SimpleNamespace
from app.services.shipping_notice.generic_order_completeness import (
build_generic_completeness_report,
completeness_report_to_metadata,
)
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
def _mapped_columns() -> list[dict]:
return [
{
'column_index': 0, 'header_path': ['Part'], 'field_code': 'part_number',
'field_id': 'id-part_number', 'status': 'mapped', 'candidates': ['part_number'],
},
{
'column_index': 1, 'header_path': ['Qty'], 'field_code': 'qty',
'field_id': 'id-qty', 'status': 'mapped', 'candidates': ['qty'],
},
]
def _data_row(*, cells: list[dict] | None = None) -> dict:
return {
'row_index': 1,
'role': 'data',
'fields': [
{
'field_id': 'id-part_number', 'field_code': 'part_number', 'value': 'ABC-01',
'page_no': 1, 'table_id': 'table-1', 'row_index': 1, 'column_index': 0,
'cell_id': 'c1', 'evidence_ref': 'ref-1', 'token_ids': ['t1'],
},
{
'field_id': 'id-qty', 'field_code': 'qty', 'value': Decimal('10'),
'page_no': 1, 'table_id': 'table-1', 'row_index': 1, 'column_index': 1,
'cell_id': 'c2', 'evidence_ref': 'ref-2', 'token_ids': ['t2'],
},
],
'cells': list(cells or []),
'complete_build_fields': True,
'complete_required_fields': True,
'missing_required_field_codes': [],
}
def _candidate(**overrides) -> dict:
base = {
'page_no': 1,
'table_id': 'table-1',
'mapping_status': 'candidate',
'header_row_index': 0,
'issues': [],
'columns': _mapped_columns(),
'rows': [_data_row()],
'row_role_summary': {'data': 1},
'unmapped_nonempty_column_indices': [],
'ignorable_column_headers': [],
}
base.update(overrides)
return base
def _definition() -> dict:
return {
'fields': [
{
'field_id': 'id-part_number', 'field_code': 'part_number', 'scope': 'line',
'enabled': True, 'required': True, 'aliases': ['Part'],
'collection_mode': 'llm_extraction',
},
{
'field_id': 'id-qty', 'field_code': 'qty', 'scope': 'line',
'enabled': True, 'required': True, 'aliases': ['Qty'],
'collection_mode': 'llm_extraction', 'value_type': 'decimal',
},
],
}
def test_completeness_report_counts_unmapped_nonempty_column():
"""非空未映射列必须计入 unmapped_nonempty_column_count。"""
candidate = _candidate(
columns=_mapped_columns() + [{
'column_index': 2, 'header_path': ['Notes'], 'status': 'unmapped', 'candidates': [],
}],
unmapped_nonempty_column_indices=[2],
rows=[_data_row(cells=[{'column_index': 2, 'cell_id': 'c3', 'text': 'urgent'}])],
)
report = build_generic_completeness_report([candidate])
assert report.unmapped_nonempty_column_count == 1
assert report.data_row_count == 1
assert report.tables[0].unmapped_nonempty_columns[0].column_index == 2
meta = completeness_report_to_metadata(report)
# 断言:元数据脱敏,仅保留计数与表 ID。
assert meta['unmapped_nonempty_column_count'] == 1
assert 'Notes' not in str(meta)
def test_ignorable_column_headers_exclude_unmapped_gap_from_gate():
"""Schema 配置的可忽略列表头不得因非空未映射列阻断门禁。"""
candidate = _candidate(
columns=_mapped_columns() + [{
'column_index': 2, 'header_path': ['Notes'], 'status': 'unmapped', 'candidates': [],
}],
# schema_mapping 仍上报索引;completeness/gate 须按 ignorable headers 排除。
unmapped_nonempty_column_indices=[2],
ignorable_column_headers=['Notes'],
rows=[_data_row(cells=[{'column_index': 2, 'cell_id': 'c3', 'text': 'ignore-me'}])],
)
report = build_generic_completeness_report([candidate])
assert report.unmapped_nonempty_column_count == 0
gate = evaluate_generic_extraction_gate(
candidates=[candidate],
definition=_definition(),
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is True
assert 'unmapped_nonempty_column' not in gate.gate_reason_codes
def test_completeness_report_counts_unexplained_nonempty_row():
"""未知 role 的非空行必须计入 unexplained_nonempty_row_count。"""
candidate = _candidate(
rows=[
_data_row(),
{
'row_index': 2,
'role': 'unknown_footer',
'fields': [],
'cells': [{'column_index': 0, 'cell_id': 'c9', 'text': 'TOTAL'}],
'complete_build_fields': False,
'complete_required_fields': False,
'missing_required_field_codes': [],
},
],
row_role_summary={'data': 1, 'unknown_footer': 1},
)
report = build_generic_completeness_report([candidate])
assert report.unexplained_nonempty_row_count == 1
assert report.row_role_totals.get('unknown_footer') == 1
@@ -0,0 +1,273 @@
"""
tests/test_shipping_generic_order_gate.py
用途:锁定通用确定性解析完整性门禁的 fail-closed 行为与 workflow 路由接线。
依赖:generic_order_gate、generic_order_parser、order_extraction_workflow。
逻辑:未映射列、多客户、续行与 LLM 必填字段必须阻断;layout_drift 禁止降级。
"""
from __future__ import annotations
from decimal import Decimal
from types import SimpleNamespace
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
from app.services.shipping_notice.order_extraction_workflow import (
_apply_stp_route_adjudication,
_should_attempt_generic_extraction,
route_deterministic_unit,
)
def _field(code: str, *, scope: str = 'line', required: bool = False, collection_mode: str = 'llm_extraction') -> dict:
return {
'field_id': f'id-{code}',
'field_code': code,
'scope': scope,
'value_type': 'string' if code != 'qty' else 'decimal',
'enabled': True,
'required': required,
'aliases': [code.replace('_', ' ').title()],
'normalizer_key': 'trim' if code != 'qty' else 'decimal',
'validator_keys': [] if code != 'qty' else ['positive_decimal'],
'collection_mode': collection_mode,
}
def _good_candidate() -> dict:
return {
'page_no': 1,
'table_id': 'table-1',
'mapping_status': 'candidate',
'header_row_index': 0,
'issues': [],
'columns': [
{'column_index': 0, 'header_path': ['Part'], 'field_code': 'part_number', 'field_id': 'id-part_number', 'status': 'mapped', 'candidates': ['part_number']},
{'column_index': 1, 'header_path': ['Qty'], 'field_code': 'qty', 'field_id': 'id-qty', 'status': 'mapped', 'candidates': ['qty']},
],
'rows': [{
'row_index': 1,
'role': 'data',
'fields': [
{'field_id': 'id-part_number', 'field_code': 'part_number', 'value': 'ABC-01', 'page_no': 1, 'table_id': 'table-1', 'row_index': 1, 'column_index': 0, 'cell_id': 'c1', 'evidence_ref': 'ref-1', 'token_ids': ['t1']},
{'field_id': 'id-qty', 'field_code': 'qty', 'value': Decimal('10'), 'page_no': 1, 'table_id': 'table-1', 'row_index': 1, 'column_index': 1, 'cell_id': 'c2', 'evidence_ref': 'ref-2', 'token_ids': ['t2']},
],
'cells': [],
'complete_build_fields': True,
'complete_required_fields': True,
'missing_required_field_codes': [],
}],
'row_role_summary': {'data': 1},
'unmapped_nonempty_column_indices': [],
'ignorable_column_headers': [],
}
def test_gate_passes_clean_candidate():
"""完整映射且无未解释行时 gate 通过。"""
definition = {'fields': [_field('part_number', required=True), _field('qty', required=True)]}
gate = evaluate_generic_extraction_gate(
candidates=[_good_candidate()],
definition=definition,
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is True
assert gate.reason_codes == []
assert gate.parse_result is not None
assert len(gate.parse_result.orders) == 1
def test_stp_needs_review_strips_acceptance_marker():
"""STP=needs_review 时必须剥离验收标记,防止 Candidate 误自动接受。"""
orders = [{'_hxops_acceptance': 'approved_generic_deterministic_v1', 'lines': []}]
result = _apply_stp_route_adjudication(
{
'route_type': 'generic_deterministic',
'fallback_reason_codes': ['generic_gate_blocked'],
'auto_create_approved': False,
},
execution_mode='deterministic',
orders=orders,
)
assert result.decision['route_decision'] == 'needs_review'
assert '_hxops_acceptance' not in result.orders[0]
def test_gate_blocks_unmapped_nonempty_column():
"""非空未映射列必须 fail-closed。"""
candidate = _good_candidate()
candidate['columns'].append({
'column_index': 2, 'header_path': ['Notes'], 'status': 'unmapped', 'candidates': [],
})
candidate['unmapped_nonempty_column_indices'] = [2]
candidate['rows'][0]['cells'] = [{'column_index': 2, 'cell_id': 'c3', 'text': 'urgent'}]
gate = evaluate_generic_extraction_gate(
candidates=[candidate],
definition={'fields': [_field('part_number', required=True), _field('qty', required=True)]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is False
assert 'unmapped_nonempty_column' in gate.gate_reason_codes
assert 'generic_gate_blocked' in gate.reason_codes
def test_gate_blocks_legacy_unmapped_nonempty_columns_payload():
"""兼容 unmapped_nonempty_columns 遗留字段格式。"""
candidate = _good_candidate()
candidate['unmapped_nonempty_columns'] = [{'column_index': 3, 'header': 'Note', 'sample': 'X'}]
gate = evaluate_generic_extraction_gate(
candidates=[candidate],
definition={'fields': [_field('part_number', required=True), _field('qty', required=True)]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is False
assert 'generic_gate_blocked' in gate.reason_codes
def test_gate_blocks_repeated_header_as_continuation_row():
"""重复表头行视为续行信号并阻断。"""
candidate = _good_candidate()
candidate['rows'].append({'row_index': 2, 'role': 'repeated_header', 'fields': [], 'cells': []})
candidate['row_role_summary'] = {'data': 1, 'repeated_header': 1}
gate = evaluate_generic_extraction_gate(
candidates=[candidate],
definition={'fields': [_field('part_number', required=True), _field('qty', required=True)]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is False
assert 'continuation_row' in gate.gate_reason_codes
def test_gate_blocks_llm_only_required_field():
"""必填但不在表格字段集的字段意味着 LLM 参与,必须阻断。"""
gate = evaluate_generic_extraction_gate(
candidates=[_good_candidate()],
definition={'fields': [
_field('part_number', required=True),
_field('qty', required=True),
{'field_id': 'id-custom-note', 'field_code': 'custom_note', 'scope': 'header', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is False
assert 'llm_involvement' in gate.gate_reason_codes
def test_should_attempt_generic_extraction_rejects_layout_drift():
"""layout_drift 永不允许进入通用解析。"""
assert _should_attempt_generic_extraction(
match_status='layout_drift',
profile_result={'issues': ['order_profile_layout_drift'], 'match': {'status': 'layout_drift'}},
) is False
def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
"""无异型特征时允许尝试通用解析。"""
assert _should_attempt_generic_extraction(
match_status='no_special_profile_feature',
profile_result={'issues': [], 'match': {'status': 'no_special_profile_feature'}},
) is True
def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
"""无模板且开关开启时 route_type 应为 generic_deterministic。"""
candidate = _good_candidate()
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
'schema': {
'extraction_contract': {'schema_version_id': 1, 'checksum': 'a' * 64},
'definition': {'fields': [_field('part_number', required=True), _field('qty', required=True)]},
},
'order_document_profiles': [],
'intakes': [{
'intake_no': 'SNI-001',
'documents': [{
'document_id': 55,
'layout_snapshot': {'status': 'ready', 'tables': []},
'layout_schema_candidates': [candidate],
}],
}],
},
)
unit = SimpleNamespace(document_id=55, intake_id=1)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled',
lambda: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
lambda *_args, **_kwargs: {
'matched': False, 'blocking': False, 'tables': [], 'issues': [],
'match': {'status': 'no_special_profile_feature', 'candidates': []},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: (
{'intake_no': 'SNI-001'},
run.input_snapshot_json['intakes'][0]['documents'][0],
),
)
route = route_deterministic_unit(run, unit=unit)
assert route.execution_mode == 'deterministic'
assert route.decision['route_type'] == 'generic_deterministic'
assert route.decision['generic_completeness']['data_row_count'] == 1
assert route.orders[0]['_hxops_acceptance'] == 'approved_generic_deterministic_v1'
def test_route_deterministic_unit_never_generic_on_layout_drift(monkeypatch):
"""layout_drift 时即使开关开启也不得进入 generic。"""
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
'schema': {'extraction_contract': {}, 'definition': {'fields': []}},
'order_document_profiles': [{'schema_version_id': 1, 'definition': {'contract_version': 'order_coordinate_profile.v2'}}],
'intakes': [{'intake_no': 'SNI-001', 'documents': [{'document_id': 1, 'layout_snapshot': {'status': 'ready'}}]}],
},
)
unit = SimpleNamespace(document_id=1, intake_id=1)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled',
lambda: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
lambda *_args, **_kwargs: {
'matched': False, 'blocking': True, 'tables': [], 'issues': ['order_profile_layout_drift'],
'match': {'status': 'layout_drift', 'candidates': []},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: ({'intake_no': 'SNI-001'}, {'document_id': 1, 'layout_schema_candidates': []}),
)
route = route_deterministic_unit(run, unit=unit)
assert route.execution_mode == 'review_required'
assert route.decision.get('route_type') != 'generic_deterministic'
assert 'profile_drift_detected' in route.decision['fallback_reason_codes']
@@ -0,0 +1,158 @@
"""
backend/tests/test_shipping_generic_order_parser.py
用途:验证 layout_schema_candidates 通用解析器能组装 Header/Line/PO 订单并保留证据链接。
依赖:generic_order_parser、generic_order_evidence。
逻辑:构造最小候选表与冻结 Schema,覆盖单 PO、多 PO 阻断与必填字段缺失。
"""
from __future__ import annotations
from decimal import Decimal
from types import SimpleNamespace
from app.services.shipping_notice.generic_order_parser import parse_generic_orders
def _field(
code: str,
*,
field_id: str | None = None,
scope: str = 'line',
required: bool = False,
) -> dict:
return {
'field_id': field_id or f'id-{code}',
'field_code': code,
'scope': scope,
'value_type': 'string' if code != 'qty' else 'decimal',
'enabled': True,
'required': required,
'aliases': [code.replace('_', ' ').title()],
'normalizer_key': 'trim' if code != 'qty' else 'decimal',
'validator_keys': [] if code != 'qty' else ['positive_decimal'],
'collection_mode': 'llm_extraction',
}
def _candidate(*rows: dict, po_header: bool = False) -> dict:
fields = []
columns = []
if po_header:
columns.extend([
{'column_index': 0, 'header_path': ['PO'], 'field_code': 'customer_po_number', 'field_id': 'id-customer_po_number', 'status': 'mapped', 'candidates': ['customer_po_number']},
{'column_index': 1, 'header_path': ['Part'], 'field_code': 'part_number', 'field_id': 'id-part_number', 'status': 'mapped', 'candidates': ['part_number']},
{'column_index': 2, 'header_path': ['Qty'], 'field_code': 'qty', 'field_id': 'id-qty', 'status': 'mapped', 'candidates': ['qty']},
])
else:
columns.extend([
{'column_index': 0, 'header_path': ['Part'], 'field_code': 'part_number', 'field_id': 'id-part_number', 'status': 'mapped', 'candidates': ['part_number']},
{'column_index': 1, 'header_path': ['Qty'], 'field_code': 'qty', 'field_id': 'id-qty', 'status': 'mapped', 'candidates': ['qty']},
])
mapped_rows = []
for index, row in enumerate(rows):
row_fields = []
for code, value in row.items():
field_id = f'id-{code}'
row_fields.append({
'field_id': field_id,
'field_code': code,
'value': value,
'page_no': 1,
'table_id': 'table-1',
'row_index': index + 1,
'column_index': 0,
'cell_id': f'cell-{index}-{code}',
'evidence_ref': f'doc:p1:table-1:r{index + 1}:c0',
'token_ids': [f'token-{index}-{code}'],
})
mapped_rows.append({
'row_index': index + 1,
'role': 'data',
'fields': row_fields,
'cells': [],
'complete_build_fields': True,
'complete_required_fields': True,
'missing_required_field_codes': [],
})
return {
'page_no': 1,
'table_id': 'table-1',
'mapping_status': 'candidate',
'header_row_index': 0,
'issues': [],
'columns': columns,
'rows': mapped_rows,
'row_role_summary': {'data': len(rows)},
'unmapped_nonempty_column_indices': [],
'ignorable_column_headers': [],
}
def _unit(document_id: int = 101) -> SimpleNamespace:
return SimpleNamespace(document_id=document_id)
def test_parse_generic_orders_builds_single_order_with_evidence():
"""单表两行应产出 1 个订单,且 observation 含 layout_evidence。"""
definition = {'fields': [
_field('part_number', required=True),
_field('qty', required=True),
]}
result = parse_generic_orders(
candidates=[_candidate({'part_number': 'ABC-01', 'qty': Decimal('10')}, {'part_number': 'ABC-02', 'qty': Decimal('20')})],
definition=definition,
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=_unit(),
)
assert result.reason_code is None
assert len(result.orders) == 1
order = result.orders[0]
assert len(order['lines']) == 2
assert order['_hxops_acceptance'] == 'approved_generic_deterministic_v1'
observation = order['lines'][0]['fields'][0]['observations'][0]
assert observation['layout_evidence']['cell_id'] == 'cell-0-part_number'
assert observation['layout_evidence']['token_ids'] == ['token-0-part_number']
def test_parse_generic_orders_blocks_multiple_po_values():
"""同一表出现两个 PO 值时必须返回 multiple_po_detected。"""
definition = {'fields': [
_field('customer_po_number', scope='header'),
_field('part_number', required=True),
_field('qty', required=True),
]}
result = parse_generic_orders(
candidates=[_candidate(
{'customer_po_number': 'PO-1', 'part_number': 'A', 'qty': Decimal('1')},
{'customer_po_number': 'PO-2', 'part_number': 'B', 'qty': Decimal('2')},
po_header=True,
)],
definition=definition,
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=_unit(),
)
assert result.orders == []
assert result.reason_code == 'multiple_po_detected'
def test_parse_generic_orders_blocks_missing_required_field():
"""缺少必填 qty 时不产出订单。"""
definition = {'fields': [
_field('part_number', required=True),
_field('qty', required=True),
]}
result = parse_generic_orders(
candidates=[_candidate({'part_number': 'ABC-01', 'qty': Decimal('10')})],
definition={'fields': [_field('part_number', required=True), _field('qty', required=True), _field('reservation_id', required=True)]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=_unit(),
)
assert result.orders == []
assert result.reason_code == 'required_field_missing'
@@ -381,8 +381,8 @@ def test_create_batch_defers_parse_without_structured(app, client):
assert not (task.lines_json or [])
def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"""聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,首轮解析延后到 Dify。"""
def test_workspace_create_batch_from_notices_awaits_order_extraction(app, client):
"""聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,等待订单抽取主链。"""
headers = _workspace_headers(app)
res = client.post(
@@ -476,7 +476,6 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"] = True
started: list[str] = []
def fake_start(batch_no: str | None) -> bool:
@@ -39,7 +39,6 @@ from app.services.chat.log_service import merge_chat_log_payload
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import persist_order_extraction_result
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_execution_result
from app.services.shipping_notice.open_existing_reservation_backfill import (
backfill_exact_file_open_existing_reservations,
)
@@ -686,11 +685,49 @@ def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(a
assert candidate.selected is True
def test_workflow_result_accepts_only_documented_data_orders_wrapper():
"""Dify End 允许 data.orders 包装,但不把内部接受字段当作可信输入。"""
assert parse_order_extraction_execution_result({
'status': 'succeeded', 'outputs': {'orders': {'data': {'orders': [{'id': 'one'}]}}},
}) == [{'id': 'one'}]
def test_approved_generic_deterministic_marker_auto_accepts_candidate(app):
"""通用确定性验收标记可自动接受 Candidate,供 Phase 3 自动冻结消费。"""
with app.app_context():
_user, _session, intake, document, runtime_context = _seed_extraction_input()
context = _build_test_extraction_context({'agent_runtime_context': runtime_context})
# 与模板自动接受用例共用同一订单形状,仅替换验收标记,隔离标记语义。
order = _order(
intake_no=intake.intake_no, document_id=int(document.id), po_number='4510000001',
part_number='SKU-A', qty=10, include_process_fields=True,
)
order['_hxops_acceptance'] = 'approved_generic_deterministic_v1'
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
# 断言:通用标记自动接受且来源/策略版本与模板路径区分。
assert candidate.candidate_status == 'accepted'
assert candidate.acceptance_mode == 'automatic'
assert candidate.extraction_source == 'approved_generic_deterministic'
assert candidate.acceptance_reason == 'approved_generic_deterministic'
assert candidate.acceptance_policy_version == 'generic-deterministic-v1'
assert candidate.selected is True
def test_unknown_acceptance_marker_stays_provisional(app):
"""非白名单验收标记不得自动接受;订单本身可建时仍保持 provisional。"""
with app.app_context():
_user, _session, intake, document, runtime_context = _seed_extraction_input()
context = _build_test_extraction_context({'agent_runtime_context': runtime_context})
order = _order(
intake_no=intake.intake_no, document_id=int(document.id), po_number='4510000001',
part_number='SKU-A', qty=10, include_process_fields=True,
)
order['_hxops_acceptance'] = 'approved_deterministic_generic_v1'
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
assert candidate.candidate_status == 'provisional'
assert candidate.selected is False
assert candidate.acceptance_mode is None
# 断言:非法标记不自动接受,但订单字段本身应通过校验(与模板用例同形)。
assert candidate.validation_status == 'ready'
def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app):
@@ -0,0 +1,55 @@
"""
tests/test_shipping_order_auto_freeze_execution.py
用途:锁定自动冻结候选范围不得扩大到 Run 内其它已消费任务。
依赖:order_auto_freeze_execution._freeze_created_tasks。
逻辑:未传入本轮 eligible candidate_nos 时不得扫描全 Run consumed 集合。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from app.services.shipping_notice.order_auto_freeze_execution import _freeze_created_tasks
def test_freeze_created_tasks_requires_eligible_candidate_nos():
"""空 eligible 集合必须直接返回,禁止扩大冻结范围。"""
run = SimpleNamespace(id=1)
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingNoticeCandidate'
) as candidate_model:
frozen, blocked = _freeze_created_tasks(run=run, policy={'enabled': True}, candidate_nos=[])
assert frozen == []
assert blocked == []
candidate_model.query.filter_by.assert_not_called()
def test_freeze_created_tasks_filters_accepted_selected_and_eligible_nos():
"""冻结查询必须约束 accepted + selected 且限定本轮 candidate_nos。"""
run = SimpleNamespace(id=42)
query = MagicMock()
query.filter_by.return_value = query
query.filter.return_value = query
query.order_by.return_value = query
query.all.return_value = []
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingNoticeCandidate'
) as candidate_model:
candidate_model.query = query
frozen, blocked = _freeze_created_tasks(
run=run,
policy={'enabled': True},
candidate_nos=['CAND-A', 'CAND-B'],
)
assert frozen == []
assert blocked == []
query.filter_by.assert_called_once_with(
order_extraction_run_id=42,
is_current_version=True,
candidate_status='accepted',
selected=True,
)
assert query.filter.call_count == 2
@@ -379,3 +379,103 @@ def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app)
assert policy['enabled'] is True
assert 'pending_orders_present' not in policy['blocking_reason_codes']
def test_generic_straight_through_can_enable_auto_freeze_when_flag_on(app, monkeypatch):
"""通用路径仅 STP=straight_through 且开关开启时可自动冻结。"""
with app.app_context():
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED', True)
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-GENERIC-OK')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
unit = run.extraction_plan.units[0]
job = db.session.get(Job, run.current_job_id)
run.status = 'completed'
db.session.add(
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='no_special_profile_feature',
selected_profile_id=None,
auto_create_approved=False,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=0,
parsed_table_count=1,
approved_table_count=1,
candidate_summary_json=[{
'_contract': 'order-extraction-route.v1',
'route_type': 'generic_deterministic',
'route_decision': 'straight_through',
}],
fallback_reason_codes_json=[],
),
)
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
# 断言:直通 + 开关 → freeze_source=generic_deterministic 且 enabled。
assert policy['freeze_source'] == 'generic_deterministic'
assert policy['enabled'] is True
assert 'generic_auto_freeze_disabled' not in policy['blocking_reason_codes']
def test_generic_deterministic_needs_review_cannot_auto_freeze(app, monkeypatch):
"""execution_mode=deterministic 但 STP=needs_review 的通用路径不得进入自动冻结。"""
with app.app_context():
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED', True)
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-FREEZE-GENERIC-NR')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
_materialize_run_plan(run)
unit = run.extraction_plan.units[0]
job = db.session.get(Job, run.current_job_id)
run.status = 'completed'
db.session.add(
ShippingOrderExtractionRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
attempt_no=1,
decision='deterministic',
match_status='no_match',
selected_profile_id=None,
auto_create_approved=False,
candidate_count=1,
table_count=1,
document_table_count=1,
business_table_count=1,
matched_table_count=0,
parsed_table_count=1,
approved_table_count=0,
candidate_summary_json=[{
'_contract': 'order-extraction-route.v1',
'route_type': 'generic_deterministic',
'route_decision': 'needs_review',
}],
fallback_reason_codes_json=['generic_gate_blocked'],
),
)
db.session.commit()
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
# 断言:不得因 decision=deterministic 误判为可冻结。
assert policy['enabled'] is False
assert policy.get('freeze_source') != 'generic_deterministic'
assert 'profile_not_auto_freeze_approved' in policy['blocking_reason_codes']
@@ -242,6 +242,42 @@ def test_template_sample_status_requires_ready_coordinate_layout(app):
}
def test_template_sample_status_rejects_ready_layout_without_modeling_table(app):
"""文本布局完成但没有表格时不得误报样本已就绪,避免向导无限等待列表同步。"""
with app.app_context():
user = User(username='empty-table-status-admin', email='empty-table-status@example.com', role='admin')
asset = FileAsset(
asset_no='FA-EMPTY-TABLE-STATUS', owner_user_id=1, original_filename='layout.pdf',
storage_provider='test', storage_bucket='test', storage_key='empty-layout.pdf',
content_hash='e' * 64, file_size=1, mime_type='application/pdf',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add_all([user, asset]); db.session.flush()
asset.owner_user_id = user.id
intake = ShippingNoticeIntake(
intake_no='SNI-EMPTY-TABLE-STATUS', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake); db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='empty-layout.pdf',
filename='layout.pdf', content_hash='e' * 64, classification='supporting', parse_status='parsed',
)
db.session.add(document); db.session.flush()
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'issues': ['mineru_table_structure_missing'], 'tables': [],
})
db.session.commit()
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
assert status == {
'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'failed', 'document_count': 1,
'error_code': 'mineru_table_structure_missing',
}
def test_draft_unbound_order_field_layout_does_not_require_schema_scope(app):
"""自动标记的未绑定订单字段只保留布局,保存时不应被 scope 契约误伤。"""
with app.app_context():
@@ -1,120 +1,370 @@
"""
backend/tests/test_shipping_order_extraction_dify_guide.py
用途:验证订单抽取 Dify 配置指南中的校验 Code 节点可执行且保持业务错误契约。
依赖:订单抽取 Workflow 指南、标准 json/pathlib。
逻辑:直接加载指南中的 Python 节点脚本,确保单文档字段错位被丢弃而非阻断跨文档聚合。
用途:验证唯一货代 Chatflow 配置手册中的 Code 节点可执行并保持分支隔离契约。
依赖:货代 Chatflow 配置手册、标准 json/pathlib。
逻辑:按节点标题提取手册内 Python 脚本,覆盖确定性路由、最小证据和受控输出。
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Callable
def _validation_main():
GUIDE_PATH = (
Path(__file__).parents[2]
/ 'docs'
/ 'features'
/ 'shipping-notice'
/ 'order-extraction-workflow-dify-guide.md'
)
def _guide_source() -> str:
"""读取当前唯一 Chatflow 配置手册。"""
return GUIDE_PATH.read_text(encoding='utf-8')
def _node_main(node_heading: str) -> Callable[..., dict]:
"""
从 Dify 配置指南提取并编译订单校验节点的 main 函数。
按 Markdown 节点标题提取紧随其后的首个 Python Code 节点。
Args:
node_heading: 完整二级标题,例如 `## 5. ROUTE_DETECT_MODE`。
Returns:
callable: 与 Dify `VALIDATE_AND_NORMALIZE_ORDERS` 节点一致的入口函数。
手册中该 Code 节点的 main 函数。
"""
guide = Path(__file__).parents[2] / 'docs' / 'features' / 'shipping-notice' / 'order-extraction-workflow-dify-guide.md'
source = guide.read_text(encoding='utf-8')
marker = 'def _field_map(schema):'
marker_index = source.index(marker)
block_start = source.rfind('```python', 0, marker_index) + len('```python\n')
block_end = source.index('\n```', marker_index)
source = _guide_source()
heading_index = source.index(node_heading)
block_start = source.index('```python', heading_index) + len('```python')
block_start += 2 if source[block_start:block_start + 2] == '\r\n' else 1
block_end = source.index('\n```', block_start)
namespace: dict[str, object] = {}
exec(source[block_start:block_end], namespace)
return namespace['main']
exec(compile(source[block_start:block_end], str(GUIDE_PATH), 'exec'), namespace)
return namespace['main'] # type: ignore[return-value]
def _contract() -> dict:
"""构造包含可选单价和必填需求数量的最小冻结 Schema 契约。"""
def _table_first_column_after(marker: str, *, table_label: str | None = None) -> list[str]:
"""提取指定标记及可选表格标签后的首个 Markdown 表格第一列。"""
source = _guide_source()
marker_index = source.index(marker)
search_index = source.index(table_label, marker_index) if table_label else marker_index
table_start = source.index('|', search_index)
table_end = source.find('\n\n', table_start)
table_text = source[table_start:table_end if table_end >= 0 else len(source)]
rows = [line for line in table_text.splitlines() if line.startswith('|')]
return [
row.split('|')[1].strip().strip('`')
for row in rows[2:]
]
def _review_request(*, scope: str = 'header', line_key: str | None = None) -> dict:
"""构造单字段最小证据请求信封。"""
return {
'schema_version_id': 1,
'checksum': 'checksum',
'fields': [
{
'field_id': 'po-id', 'field_code': 'po_number', 'display_name': '采购订单号',
'scope': 'header', 'value_type': 'string', 'collection_mode': 'llm_extraction',
'required': True, 'validator_keys': ['non_empty'],
},
{
'field_id': 'unit-price-id', 'field_code': 'unit_price', 'display_name': '单价',
'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction',
'required': False, 'validator_keys': [],
},
{
'field_id': 'qty-id', 'field_code': 'qty', 'display_name': '需求数量',
'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction',
'required': True, 'validator_keys': ['positive_decimal'],
},
],
'contract_version': 'order-review-llm.v1',
'review_case_id': 123,
'document_id': 456,
'evidence_level': 'L1_field',
'target_fields': [{
'field_id': 'field-1',
'field_code': 'po_number',
'scope': scope,
'line_key': line_key,
'line_number': None,
}],
'evidence_pack': {
'document_id': 456,
'evidence_level': 'L1_field',
'fields': [{
'field_id': 'field-1',
'snippets': [{'quote': 'PO-123'}],
}],
'tables': [],
'pages': [],
},
'constraints': {
'values_must_be_verbatim_in_evidence': True,
'full_pdf_forbidden': True,
'cannot_auto_freeze': True,
},
}
def _order(fields: list[dict]) -> dict:
"""构造只含一条订单行的最小模型输出。"""
return {
'orders': [{
'schema_version_id': 1, 'schema_checksum': 'checksum',
'classification': 'shipping_request', 'classification_confidence': 0.98,
'source_intake_no': 'SNI-TEST', 'primary_document_id': 1,
'header_fields': [], 'lines': [{'fields': fields}], 'conflicts': [],
def test_route_uses_only_server_contract_for_review_mode():
"""仅服务端契约精确匹配可进入复核分支,用户 query 不参与路由。"""
main = _node_main('## 5. ROUTE_DETECT_MODE')
assert main('order-review-llm.v1')['mode'] == 'review'
assert main('')['mode'] == 'chat'
assert main(' order-review-llm.v1 ')['mode'] == 'review'
assert main('ORDER-REVIEW-LLM.V1')['mode'] == 'chat'
def test_review_request_accepts_one_header_field():
"""合法单字段请求应生成可传给后续节点的规范 JSON。"""
main = _node_main('## 7. REVIEW_PARSE_REQUEST')
result = main(
json.dumps(_review_request()),
'order-review-llm.v1',
)
assert result['request_valid'] is True
parsed = json.loads(result['review_request_json'])
assert parsed['document_id'] == 456
assert parsed['target_fields'][0]['field_id'] == 'field-1'
def test_review_request_rejects_multiple_fields_and_line_without_key():
"""复核分支必须一次只处理一个字段,明细字段必须绑定 line_key。"""
main = _node_main('## 7. REVIEW_PARSE_REQUEST')
multiple = _review_request()
multiple['target_fields'].append(dict(multiple['target_fields'][0], field_id='field-2'))
multiple_result = main(json.dumps(multiple), 'order-review-llm.v1')
line_result = main(
json.dumps(_review_request(scope='line')),
'order-review-llm.v1',
)
assert multiple_result == {
'request_valid': False,
'request_error_code': 'EXACTLY_ONE_TARGET_REQUIRED',
'review_request_json': '',
}
assert line_result['request_valid'] is False
assert line_result['request_error_code'] == 'LINE_KEY_REQUIRED'
def test_review_context_removes_secrets_and_limits_to_current_pack():
"""模型上下文应剔除秘密字段并只保留当前请求的受控证据集合。"""
main = _node_main('## 9. REVIEW_PREPARE_CONTEXT')
request = _review_request()
request['evidence_pack']['token'] = 'must-not-leak'
request['evidence_pack']['pages'] = [
{'page_no': index + 1, 'text': f'page-{index + 1}'}
for index in range(10)
]
result = main(json.dumps(request))
context = json.loads(result['model_context_json'])
assert 'token' not in result['model_context_json'].casefold()
assert context['document_id'] == 456
assert len(context['pages']) == 8
assert json.loads(result['target_field_json'])['field_id'] == 'field-1'
def test_review_output_accepts_matching_scalar_and_empty_suggestions():
"""匹配字段的标量建议和空建议均属于合法结构输出。"""
main = _node_main('## 11. REVIEW_VALIDATE_OUTPUT')
request_json = json.dumps(_review_request())
suggestion = {
'suggestions': [{
'field_id': 'field-1',
'field_code': 'po_number',
'scope': 'header',
'suggested_value': 'PO-123',
'quote': 'PO-123',
'confidence': 1.5,
'line_number': 999,
}],
}
result = main(request_json, json.dumps(suggestion))
empty_result = main(request_json, '{"suggestions":[]}')
def _observation(field_id: str, value: object) -> dict:
"""构造带当前 Document 逐字证据的字段 Observation。"""
return {
'field_id': field_id,
'observations': [{'value': value, 'document_id': 1, 'quote': str(value), 'confidence': 0.98}],
assert result['output_valid'] is True
answer = json.loads(result['answer_json'])['suggestions'][0]
assert answer['field_id'] == 'field-1'
assert answer['confidence'] == 1.0
assert answer['line_number'] is None
assert empty_result['output_valid'] is True
assert json.loads(empty_result['answer_json']) == {'suggestions': []}
def test_review_output_rejects_wrong_field_and_extra_top_level_keys():
"""模型不得改写字段身份,也不得在协议顶层夹带其他输出。"""
main = _node_main('## 11. REVIEW_VALIDATE_OUTPUT')
request_json = json.dumps(_review_request())
wrong_field = {
'suggestions': [{
'field_id': 'field-2',
'scope': 'header',
'suggested_value': 'PO-123',
'quote': 'PO-123',
}],
}
field_result = main(request_json, json.dumps(wrong_field))
extra_result = main(request_json, json.dumps({'suggestions': [], 'orders': []}))
def test_dify_validation_drops_optional_numeric_field_type_mismatch():
"""可选单价错填料号时应忽略该字段,保留必填需求数量并通过校验。"""
main = _validation_main()
result = main(
json.dumps(_order([
_observation('unit-price-id', 'D4-A08AR12000002'),
_observation('qty-id', 30),
])),
json.dumps(_contract()), 'SNI-TEST', 1,
)
assert result['validation_ok'] is True
fields = json.loads(result['orders'])[0]['lines'][0]['fields']
assert [item['field_id'] for item in fields] == ['qty-id']
assert field_result['output_valid'] is False
assert field_result['output_error_code'] == 'FIELD_ID_MISMATCH'
assert extra_result['output_valid'] is False
assert extra_result['output_error_code'] == 'INVALID_TOP_LEVEL_OUTPUT'
def test_dify_validation_drops_required_field_type_mismatch_for_partial_unit():
"""单文档的必填 Qty 类型错误只丢弃该字段,完整性由 HXOPS 跨文档判断。"""
main = _validation_main()
result = main(
json.dumps(_order([_observation('qty-id', 'thirty')])),
json.dumps(_contract()), 'SNI-TEST', 1,
)
def test_chat_context_parses_only_expected_runtime_fields():
"""普通聊天分支只投影受控运行态字段和原样能力令牌。"""
main = _node_main('## 14. CHAT_PARSE_CONTEXT')
runtime_context = {
'schema_version': '1',
'platform': {'locale': 'zh-CN'},
'refs': {'task_no': 'SN-TEST', 'batch_no': 'SB-TEST'},
'domain': {
'summary': '当前任务等待人工处理',
'state_hint': {'current_step': 'review', 'status': 'needs_human'},
},
'secret': 'must-not-be-projected',
}
assert result['validation_ok'] is True
normalized = json.loads(result['orders'])
assert normalized[0]['lines'] == []
assert result['validation_error'] == ''
result = main(json.dumps(runtime_context), 'signed-token')
assert result['context_valid'] is True
assert result['task_no'] == 'SN-TEST'
assert result['batch_no'] == 'SB-TEST'
assert result['current_step'] == 'review'
assert result['capability_token'] == 'signed-token'
assert 'secret' not in result
def test_dify_validation_accepts_email_header_fragment_without_order_lines():
"""EML 只提供 PO 等 Header 证据时必须成功,等待 PDF Unit 补充订单行。"""
main = _validation_main()
payload = _order([])
payload['orders'][0]['header_fields'] = [_observation('po-id', '4518738152')]
payload['orders'][0]['lines'] = []
def test_guide_keeps_review_and_chat_capabilities_isolated():
"""手册必须保留单 Chatflow 的硬路由、无状态复核和只读聊天红线。"""
source = _guide_source()
result = main(json.dumps(payload), json.dumps(_contract()), 'SNI-TEST', 1)
assert '`agent_code=shipping_notice` 唯一 Chatflow' in source
assert 'ROUTE_DETECT_MODE.mode == "review"' in source
assert '复核分支不使用 Conversation History、Memory、Knowledge、Tool、HTTP、Agent' in source
assert '`get_task_status` 和 `get_batch_status`' in source
assert 'Dify 不输出 `orders`' in source
assert '不自动冻结' in source
assert result['validation_ok'] is True
normalized = json.loads(result['orders'])[0]
assert normalized['lines'] == []
assert normalized['header_fields'][0]['field_id'] == 'po-id'
def test_guide_lists_every_chatflow_node_with_connections():
"""全节点关系表必须覆盖画布中的每个配置节点及终端节点。"""
source = _guide_source()
relation_section = source[
source.index('### 4.1 全节点连接关系'):
source.index('### 4.2 变量类型约定')
]
expected_nodes = {
'CHAT_ANSWER_BATCH_STATUS',
'CHAT_ANSWER_GENERAL',
'CHAT_ANSWER_MISSING_CONTEXT',
'CHAT_ANSWER_MODEL_ERROR',
'CHAT_ANSWER_TASK_STATUS',
'CHAT_ANSWER_TOOL_ERROR',
'CHAT_CLASSIFY_INTENT',
'CHAT_GENERAL_LLM',
'CHAT_GET_BATCH_STATUS',
'CHAT_GET_TASK_STATUS',
'CHAT_HAS_BATCH_CONTEXT',
'CHAT_HAS_TASK_CONTEXT',
'CHAT_PARSE_CONTEXT',
'CHAT_RENDER_BATCH_STATUS',
'CHAT_RENDER_TASK_STATUS',
'REVIEW_ANSWER_INVALID_OUTPUT',
'REVIEW_ANSWER_INVALID_REQUEST',
'REVIEW_ANSWER_SUCCESS',
'REVIEW_OUTPUT_VALID',
'REVIEW_PARSE_REQUEST',
'REVIEW_PREPARE_CONTEXT',
'REVIEW_PROVIDER_ERROR',
'REVIEW_REQUEST_VALID',
'REVIEW_SUGGEST_FIELD',
'REVIEW_VALIDATE_OUTPUT',
'ROUTE_DETECT_MODE',
'ROUTE_IS_REVIEW',
'START',
}
for node_name in expected_nodes:
assert f'`{node_name}`' in relation_section
assert relation_section.count('| 终止 |') == 10
def test_guide_keeps_key_input_and_output_fields_alphabetically_sorted():
"""关键节点输入输出字段必须按变量名 ASCII 升序排列。"""
markers = {
'START business inputs': [
'agent_runtime_context',
'review_llm_contract',
'shipping_chat_capability_token',
],
'REVIEW_PARSE_REQUEST outputs': [
'request_error_code',
'request_valid',
'review_request_json',
],
'REVIEW_SUGGEST_FIELD inputs': [
'model_context_json',
'target_field_json',
],
'REVIEW_VALIDATE_OUTPUT inputs': [
'model_answer',
'review_request_json',
],
'CHAT_PARSE_CONTEXT outputs': [
'batch_no',
'capability_token',
'context_summary',
'context_valid',
'current_step',
'locale',
'status',
'task_no',
],
'CHAT_GET_TASK_STATUS inputs': [
'conversation_id',
'shipping_chat_capability_token',
'task_id',
],
}
anchors = {
'START business inputs': ('## 3. Start 节点', '所有字段均按变量名 ASCII 升序排列'),
'REVIEW_PARSE_REQUEST outputs': ('## 7. REVIEW_PARSE_REQUEST', '输出字段按变量名排序:'),
'REVIEW_SUGGEST_FIELD inputs': ('## 10. REVIEW_SUGGEST_FIELD', '输入字段按变量名排序:'),
'REVIEW_VALIDATE_OUTPUT inputs': ('## 11. REVIEW_VALIDATE_OUTPUT', '输入字段按变量名排序:'),
'CHAT_PARSE_CONTEXT outputs': ('## 14. CHAT_PARSE_CONTEXT', '输出字段按变量名排序:'),
'CHAT_GET_TASK_STATUS inputs': ('### 16.4 CHAT_GET_TASK_STATUS', '输入参数按名称 ASCII 升序排列:'),
}
for label, expected in markers.items():
anchor, table_label = anchors[label]
actual = _table_first_column_after(anchor, table_label=table_label)
assert actual == expected, label
def test_guide_defines_independent_prompts_for_each_status_renderer():
"""批次和任务状态 LLM 必须各自具备可独立配置的提示词与失败策略。"""
source = _guide_source()
batch_section = source[
source.index('### 17.1 CHAT_RENDER_BATCH_STATUS'):
source.index('### 17.2 CHAT_RENDER_TASK_STATUS')
]
task_section = source[
source.index('### 17.2 CHAT_RENDER_TASK_STATUS'):
source.index('## 18. CHAT_GENERAL_LLM')
]
for section in (batch_section, task_section):
assert 'System Prompt:' in section
assert 'User Prompt:' in section
assert '| Memory / History | 关闭,不引用会话历史 |' in section
assert '| Response format | Text |' in section
assert '| Retry | 关闭 |' in section
assert '| Temperature | `0.1` |' in section
assert '| Tools / Knowledge | 不连接 |' in section
assert '| Vision / Files | 关闭 |' in section
assert '连接 `CHAT_ANSWER_MODEL_ERROR`' in section
assert '批次状态 Tool 返回:' in batch_section
assert 'process_summary' in batch_section
assert 'status=ok 只表示本次查询成功,不代表批次内所有任务已完成' in batch_section
assert '任务状态 Tool 返回:' in task_section
assert 'stop_agent_turn=true' in task_section
assert 'forbidden_next_tools' in task_section
@@ -0,0 +1,90 @@
"""
tests/test_shipping_order_extraction_route_contract.py
用途:锁定订单抽取路由契约枚举、策略版本与 profile 路径推导规则。
依赖:order_extraction_route_contract。
逻辑:阶段 0 验收——五类路由互斥、通用资格、原因码规范化与决策字典脱敏。
"""
from app.services.shipping_notice.order_extraction_route_contract import (
EXTRACTION_ROUTE_TYPES,
GENERIC_ELIGIBLE_MATCH_STATUSES,
ROUTE_STRATEGY_VERSION,
ExtractionRouteResult,
default_policy_versions,
execution_mode_for_route,
normalize_reason_codes,
route_type_from_profile_path,
)
def test_extraction_route_types_are_frozen_and_complete():
"""对外路由五类必须完整且互斥集合稳定。"""
assert EXTRACTION_ROUTE_TYPES == {
'profile_deterministic',
'generic_deterministic',
'llm_assisted_review',
'manual_review',
'rejected',
}
def test_only_no_special_profile_feature_is_generic_eligible():
"""漂移/歧义/证据不足禁止进入通用解析资格集合。"""
assert GENERIC_ELIGIBLE_MATCH_STATUSES == {'no_special_profile_feature'}
for status in ('layout_drift', 'ambiguous', 'evidence_insufficient', 'no_match'):
assert status not in GENERIC_ELIGIBLE_MATCH_STATUSES
def test_route_type_from_profile_path_maps_selected_profile_to_profile_deterministic():
"""已选模板且 deterministic 必须映射为 profile_deterministic。"""
assert route_type_from_profile_path(
match_status='unique_match',
execution_mode='deterministic',
stp_route_decision='straight_through',
has_selected_profile=True,
) == 'profile_deterministic'
def test_route_type_from_profile_path_keeps_generic_eligible_as_manual_until_phase2():
"""阶段 0 无异型特征仍落 manual_review,避免误报 generic_deterministic。"""
assert route_type_from_profile_path(
match_status='no_special_profile_feature',
execution_mode='review_required',
stp_route_decision='needs_review',
has_selected_profile=False,
) == 'manual_review'
def test_execution_mode_for_route_and_policy_versions():
"""策略版本与 execution_mode 映射必须稳定。"""
assert execution_mode_for_route('profile_deterministic') == 'deterministic'
assert execution_mode_for_route('generic_deterministic') == 'deterministic'
assert execution_mode_for_route('manual_review') == 'review_required'
assert execution_mode_for_route('rejected') == 'skipped'
versions = default_policy_versions()
assert versions['route_strategy_version'] == ROUTE_STRATEGY_VERSION
assert 'profile_scoring_policy_version' in versions
assert 'generic_gate_policy_version' in versions
def test_extraction_route_result_decision_dict_is_sanitized():
"""decision 字典必须含 route_type / reason_codes / policy_versions,且不含正文。"""
result = ExtractionRouteResult(
route_type='manual_review',
execution_mode='review_required',
stp_route_decision='needs_review',
match_status='layout_drift',
reason_codes=['profile_drift_detected', 'profile_drift_detected', 'unknown_custom'],
selected_profile={'profile_code': 'PO_A', 'version': 1, 'checksum': 'a' * 64},
metadata={'candidate_count': 2},
)
decision = result.to_decision_dict()
assert decision['route_type'] == 'manual_review'
assert decision['route_decision'] == 'needs_review'
assert decision['reason_codes'] == normalize_reason_codes(
['profile_drift_detected', 'profile_drift_detected', 'unknown_custom'],
)
assert decision['selected_profile_code'] == 'PO_A'
assert 'document_text' not in decision
assert decision['policy_versions']['route_strategy_version'] == ROUTE_STRATEGY_VERSION
@@ -630,11 +630,11 @@ def test_run_freezes_manual_auto_freeze_policy(app):
}
def test_run_v3_freezes_layout_schema_candidate_without_exposing_internal_evidence(app):
"""Run v3 冻结真实 layout cell 映射,确定性诊断快照必须剥离内部证据。"""
def test_run_v3_freezes_layout_schema_candidate_and_policy_versions(app):
"""Run v3 冻结 layout 候选与路由策略版本;主链不再构建 Dify execution_manifest。"""
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.order_extraction_workflow import build_order_extraction_execution_snapshot
from app.services.shipping_notice.order_extraction_route_contract import ROUTE_STRATEGY_VERSION
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='B')
@@ -667,12 +667,9 @@ def test_run_v3_freezes_layout_schema_candidate_without_exposing_internal_eviden
assert candidates[0]['mapping_status'] == 'candidate'
assert candidates[0]['rows'][0]['fields'][0]['cell_id']
assert 'layout_table_not_accepted' in candidates[0]['issues']
manifest = build_order_extraction_execution_snapshot(
run, unit=run.extraction_plan.units[0],
)['execution_manifest']
assert 'layout_schema_candidates' not in manifest
assert 'layout_candidate' not in manifest
# 关键断言:策略版本写入快照,且不再暴露 Dify Workflow 清单。
assert run.input_snapshot_json['policy_versions']['route_strategy_version'] == ROUTE_STRATEGY_VERSION
assert 'execution_manifest' not in run.input_snapshot_json
def test_create_run_freezes_published_order_document_profile_definition(app):
@@ -1133,6 +1130,143 @@ def test_active_run_blocks_different_intake_in_same_conversation(app):
assert ShippingOrderExtractionRun.query.count() == 1
def test_same_attachment_content_reuses_pending_workflow_across_upload_batches(app):
"""同会话重新上传完全相同的 PDF,必须返回原 Run/Workflow 而不是新建批次。"""
from app.models import ShippingNoticeWorkflow, ShippingNoticeWorkflowItem
with app.app_context():
user, agent, session, first_intake, first_document = _seed_run_input(suffix='CONTENT-REUSE')
first_intake.upload_batch_id = 'content-reuse-batch-1'
first, reused = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[first_intake.intake_no],
upload_batch_id=first_intake.upload_batch_id,
)
transition_order_extraction_run(first, target_status='processing', phase='extracting')
transition_order_extraction_run(first, target_status='review_required', phase='review_required')
db.session.commit()
second_asset = FileAsset(
asset_no='FA-RUN-CONTENT-REUSE-SECOND',
owner_user_id=user.id,
original_filename='renamed-orders.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/renamed-orders.pdf',
content_hash=db.session.get(FileAsset, first_intake.asset_id).content_hash,
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingNoticeIntake(
intake_no='SNI-RUN-CONTENT-REUSE-SECOND',
asset_id=second_asset.id,
user_id=user.id,
conversation_id=session.session_id,
upload_batch_id='content-reuse-batch-2',
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
extracted_text='same business attachment',
expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingNoticeDocument(
intake_id=second_intake.id,
asset_id=second_asset.id,
document_type='attachment',
attachment_key='renamed-orders.pdf',
filename='renamed-orders.pdf',
content_hash=first_document.content_hash,
classification='order_notice',
parse_status='parsed',
extracted_text=first_document.extracted_text,
))
db.session.commit()
replay, replayed = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
# 关键断言:内容指纹复用原业务事实,且重复 Intake 不再回到输入栏。
assert reused is False
assert replayed is True
assert replay.id == first.id
assert second_intake.order_extraction_status == 'partially_completed'
assert ShippingOrderExtractionRun.query.count() == 1
assert ShippingNoticeWorkflow.query.count() == 1
assert ShippingNoticeWorkflowItem.query.count() == 1
def test_closed_same_attachment_workflow_allows_new_business_batch(app):
"""同内容 Workflow Item 已关闭后,新上传代表显式新业务,应允许新建 Run。"""
from app.models import ShippingNoticeWorkflowItem
from app.services.shipping_notice.workflow_ledger_service import close_workflow_item
with app.app_context():
user, agent, session, first_intake, first_document = _seed_run_input(suffix='CONTENT-CLOSED')
first, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id,
intake_nos=[first_intake.intake_no],
)
item = ShippingNoticeWorkflowItem.query.filter_by(current_run_id=first.id).one()
close_workflow_item(
item=item,
closed_reason='non_order',
actor_type='user',
actor_id=user.id,
)
transition_order_extraction_run(first, target_status='processing', phase='extracting')
transition_order_extraction_run(first, target_status='completed', phase='completed')
db.session.commit()
second_asset = FileAsset(
asset_no='FA-RUN-CONTENT-CLOSED-SECOND', owner_user_id=user.id,
original_filename='closed-copy.pdf', storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/closed-copy.pdf',
content_hash=db.session.get(FileAsset, first_intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingNoticeIntake(
intake_no='SNI-RUN-CONTENT-CLOSED-SECOND', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='content-closed-batch-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same closed attachment', expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingNoticeDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key='closed-copy.pdf', filename='closed-copy.pdf',
content_hash=first_document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=first_document.extracted_text,
))
db.session.commit()
second, reused = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id,
intake_nos=[second_intake.intake_no], upload_batch_id=second_intake.upload_batch_id,
)
# 关键断言:关闭的业务事实不得被隐式重开。
assert reused is False
assert second.id != first.id
assert ShippingOrderExtractionRun.query.count() == 2
def test_ten_integrity_races_reuse_database_winner(app):
"""模拟 10 个请求在预查后同时落库失败;每个请求都必须回读唯一赢家而非暴露 500。"""
with app.app_context():
@@ -81,6 +81,38 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
assert result.source == 'pdf_coordinate'
def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower():
"""值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'currency', 'text': 'Currency:',
'region': {'x0': .025, 'y0': .544, 'x1': .140, 'y1': .557},
'position_locked': False,
},
'value_region': {'x0': 1.13043478, 'y0': 0, 'x1': 1.36521739, 'y1': 1},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(
profile=profile,
schema_fields=_schema(value_type='currency', normalizer_key='currency', validator_keys=['currency']),
coordinate_evidence={
'pages': {'1': {'width': 609, 'height': 791}},
'page_glyphs': {'1': [
*[
{'text': character, 'bbox': {'x0': 15 + index * 8, 'y0': 430, 'x1': 22 + index * 8, 'y1': 438}}
for index, character in enumerate('Currency:')
],
*_glyphs(('USD', 90, 430)),
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
)[0]
# 框尾轻微截断只补齐当前连续词,避免依赖 PDF 字体的精确字符宽度。
assert result.status == 'confirmed'
assert result.value == 'USD'
def test_unlocked_anchor_reads_same_field_after_horizontal_layout_shift():
"""标签右侧字段不应被画布初始横坐标限制,才能覆盖同版式的左移变体。"""
profile = _profile(layout={
@@ -113,8 +145,8 @@ def test_movable_right_of_anchor_starts_at_actual_anchor_end():
assert result.value == '3000099132'
def test_legacy_right_of_anchor_canvas_box_is_rebased_after_horizontal_shift():
"""旧画布保存绝对框时,运行期仍须按右侧语义兼容左移同版式单据。"""
def test_legacy_right_of_anchor_canvas_box_does_not_guess_beyond_saved_width():
"""历史绝对框只覆盖部分预约号时不得越界猜全值,管理员需重建完整绿色框。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'reservation', 'text': 'reservation_id',
@@ -128,7 +160,7 @@ def test_legacy_right_of_anchor_canvas_box_is_rebased_after_horizontal_shift():
))[0]
assert result.status == 'confirmed'
assert result.value == '3000099132'
assert result.value != '3000099132'
def test_legacy_cross_row_value_box_remains_absolute():
@@ -407,6 +439,64 @@ def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection
assert result.value == '66 Hou-Kang Street'
def test_tight_value_region_keeps_edge_glyphs_without_reading_adjacent_text():
"""紧贴 USD 字符盒的右侧值框应容忍渲染误差,但不能吞入相邻字段。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'currency', 'text': 'Currency'},
'value_region': {'x0': 1, 'y0': .55, 'x1': 2.18, 'y1': 1},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='currency',
), coordinate_evidence=_evidence(pages={'1': _glyphs(
('Currency', 20, 40), (':', 72, 40), ('USD', 76, 40), ('X', 92, 40),
)}))[0]
# 关键断言:字符中心略越过框上缘仍读取 USD,而正常字距外的 X 不进入币种值。
assert result.status == 'confirmed'
assert result.value == 'USD'
def test_right_value_keeps_canvas_size_when_anchor_box_is_wide():
"""右侧值框只跟随标签位置,管理员画宽的紫色框不能缩放 USD 绿色值框。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'currency', 'text': 'Currency',
'region': {'x0': .25, 'y0': .20, 'x1': .40, 'y1': .25},
},
'absolute_value_region': {'x0': .42, 'y0': .20, 'x1': .48, 'y1': .25},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='currency',
), coordinate_evidence=_evidence(pages={'1': _glyphs(
('Currency', 52, 42), (':', 80, 42), ('USD', 84, 42),
)}))[0]
# 关键断言:真实标签仍在参考紫框内时直接使用绿色绝对框,不受紫框宽高影响。
assert result.status == 'confirmed'
assert result.value == 'USD'
def test_legacy_below_anchor_relative_region_restores_original_canvas_box():
"""旧版标签下方相对框须按保存时标签反算,实际标签字宽变化不能裁掉 PO 首字符。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'number', 'text': 'Number',
'region': {'x0': .55, 'y0': .20, 'x1': .61, 'y1': .24},
},
'value_region': {'x0': -1.5, 'y0': 1, 'x1': 1, 'y1': 2},
'value_mode': 'below_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('Number', 112, 40), ('60187624', 92, 48))},
))[0]
# 关键断言:完整读取 60187624,不能因当前 Number 字符盒较窄而从 0 开始。
assert result.status == 'confirmed'
assert result.value == '60187624'
def test_anchored_order_field_rejects_ambiguous_legacy_and_absolute_value_regions():
"""新旧值框不能并存,避免后续编辑绕过唯一画布读取边界。"""
try:
@@ -3,6 +3,19 @@
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
def _field_region(*, field_id: str = 'line-id', field_code: str = 'customer_po_line_no', region: dict | None = None) -> dict:
"""构造符合 v2 scope 契约的字段区域。"""
box = region or {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}
return {
'field_id': field_id,
'field_code': field_code,
'scope': 'line',
'region': box,
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{'scope': 'line', 'field_code': field_code, 'field_id': field_id}],
}
def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
"""构造最小冻结 Profile;工厂值必须与 PLANT NAME 标签形成关系才可命中。"""
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
@@ -11,10 +24,15 @@ def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None
'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': value, 'value_position': 'right'}],
'optional_anchors': [{'anchor_id': f'optional_{index}', 'label': 'TYPE:', 'value': item, 'value_position': 'right'} for index, item in enumerate(optional or [])],
'minimum_score': score, 'minimum_margin': margin,
'scoring_thresholds': {
'auto_select_minimum_score': 0.90,
'auto_select_minimum_margin': 0.15,
'critical_structure_minimum': 0.90,
},
},
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
'field_regions': [_field_region()],
}]}],
}}
@@ -95,6 +113,35 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
assert result.status == 'unique_match'
def test_profile_matcher_restores_region_text_by_visual_line_before_matching_anchor():
"""
区域锚点须按视觉行内横坐标恢复固定值,不能因 PDF 字符基线抖动打乱阅读顺序。
关键断言:值字符的 y0 顺序故意为 C、A、B;匹配器仍应按 x0 得到 ABC,
与标注工作台保存固定值时的视觉行重建规则一致。
"""
profile = _profile('PO_A', value='ABC')
anchor = profile['definition']['document_match']['required_anchors'][0]
anchor.update({
'page_no': 1,
'label_region': {'x0': 0.05, 'y0': 0.05, 'x1': 0.4, 'y1': 0.25},
'value_region': {'x0': 0.45, 'y0': 0.05, 'x1': 0.8, 'y1': 0.25},
})
layout = _layout('')
layout['coordinate_evidence']['page_glyphs'] = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 5, 'y0': 10, 'x1': 14 + index * 5, 'y1': 20}}
for index, char in enumerate('PLANT NAME:')
] + [
{'text': 'A', 'bbox': {'x0': 100, 'y0': 12, 'x1': 108, 'y1': 22}},
{'text': 'B', 'bbox': {'x0': 115, 'y0': 14, 'x1': 123, 'y1': 24}},
{'text': 'C', 'bbox': {'x0': 130, 'y0': 10, 'x1': 138, 'y1': 20}},
]}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
@@ -117,3 +164,106 @@ def test_profile_matcher_allows_multiple_template_regions_on_one_detected_table(
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
def test_profile_matcher_rejects_invalid_scope_contract_as_no_candidate():
"""缺少 scope/target_fields 的非法 Profile 不得参与评分(静默跳过 → no_match)。"""
broken = _profile('PO_BROKEN')
broken['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
'field_id': 'line-id',
'field_code': 'customer_po_line_no',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
}]
assert match_frozen_coordinate_profiles(profiles=[broken], layout=_layout()).status == 'no_match'
def test_profile_matcher_tie_scores_remain_ambiguous_not_order_dependent():
"""同分候选必须 ambiguous,且对输入顺序不敏感。"""
left_first = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
right_first = match_frozen_coordinate_profiles(profiles=[_profile('PO_B'), _profile('PO_A')], layout=_layout())
assert left_first.status == 'ambiguous'
assert right_first.status == 'ambiguous'
assert [item.profile_code for item in left_first.candidates] == [item.profile_code for item in right_first.candidates]
def test_profile_matcher_reports_dimension_scores_and_margin_on_candidates():
"""分项得分与 Top1/Top2/Margin 必须出现在候选与结果摘要中。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'])], layout=_layout('PLANT NAME: FACTORY A TYPE: UM17'))
assert result.status == 'unique_match'
assert result.top1_score is not None
assert result.margin is not None
candidate = result.candidates[0]
assert candidate.dimension_scores is not None
assert candidate.dimension_scores.anchor_geometry == 1.0
assert 0.0 <= candidate.score <= 1.0
def test_profile_matcher_returns_no_special_profile_feature_without_template_evidence():
"""文档不含任何模板锚点/值证据时,必须明确无异型特征而非 layout_drift。"""
result = match_frozen_coordinate_profiles(
profiles=[_profile('PO_A')],
layout=_layout('GENERIC INVOICE NUMBER 12345 TOTAL DUE'),
)
assert result.status == 'no_special_profile_feature'
assert result.status != 'layout_drift'
def test_profile_matcher_auto_selects_by_score_when_margin_and_thresholds_met():
"""多候选 hard_match 且满足自动决胜阈值时返回 selected_by_score。"""
stronger = _profile('PO_A', optional=['UM17'])
weaker = _profile('PO_B', optional=['MISSING_TAG'])
weaker['definition']['table_regions'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'].append({
'region_id': 'extra_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1},
'line_layouts': [{
'layout_id': 'extra_main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1},
'field_regions': [_field_region(field_id='line-id-2', region={'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1})],
}],
})
for item in (stronger, weaker):
item['definition']['document_match']['scoring_thresholds'] = {
'auto_select_minimum_score': 0.90,
'auto_select_minimum_margin': 0.15,
'critical_structure_minimum': 0.80,
}
result = match_frozen_coordinate_profiles(
profiles=[stronger, weaker],
layout=_layout('PLANT NAME: FACTORY A TYPE: UM17'),
)
assert result.status == 'selected_by_score'
assert result.profile_code == 'PO_A'
assert result.margin is not None
assert result.margin >= 0.15
def test_profile_matcher_uses_page_geometry_when_mineru_detects_no_table():
"""v2 坐标模板有完整页证据时,MinerU 零表不得把拓扑分清零并拒绝既有模板。"""
layout = _layout('PLANT NAME: FACTORY A')
layout['coordinate_evidence']['page_glyphs'] = {
'1': list(layout['coordinate_evidence']['tables']['table-1']),
}
layout['tables'] = []
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
assert result.status == 'unique_match'
assert result.candidates[0].dimension_scores is not None
assert result.candidates[0].dimension_scores.table_topology == 1.0
def test_profile_matcher_drift_is_not_no_special_profile_feature():
"""部分锚点证据缺失但页内仍出现模板值时,必须判定 layout_drift。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('REMARK: FACTORY A'))
assert result.status == 'layout_drift'
assert result.status != 'no_special_profile_feature'
@@ -0,0 +1,101 @@
"""
backend/tests/test_shipping_order_review_evidence_selector.py
用途:验证最小证据包选取与 L4 默认禁止。
依赖:order_review_evidence_selector、order_review_llm_contract。
"""
from app.services.shipping_notice.order_review_evidence_selector import (
_strip_forbidden,
select_review_evidence_pack,
)
from app.services.shipping_notice.order_review_llm_contract import L4_FULL_PDF_ALLOWED_BY_DEFAULT
def test_strip_forbidden_removes_secret_keys():
"""证据包不得包含 token/secret 键。"""
cleaned = _strip_forbidden({'token': 'x', 'fields': [{'quote': '100'}]})
assert 'token' not in cleaned
assert cleaned['fields'][0]['quote'] == '100'
def test_select_l1_field_evidence_pack():
"""L1 应包含目标字段 snippets。"""
document = {
'document_id': 1,
'layout_schema_candidates': [{
'table_id': 't1',
'page_no': 1,
'rows': [{
'row_index': 0,
'fields': [{
'field_id': 'fld-qty',
'quote': '100',
'value': '100',
}],
}],
}],
}
pack = select_review_evidence_pack(
document=document,
target_fields=[{'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line'}],
evidence_level='L1_field',
)
assert pack['evidence_level'] == 'L1_field'
assert pack['fields'][0]['snippets']
def test_select_line_evidence_binds_target_line_key():
"""明细证据必须绑定目标 line_key,禁止用兄弟行同名字段串值。"""
document = {
'document_id': 1,
'layout_schema_candidates': [{
'table_id': 't1',
'page_no': 1,
'rows': [
{
'row_index': 1,
'line_key': 'machine-1',
'fields': [{'field_id': 'fld-qty', 'quote': '10', 'value': '10'}],
},
{
'row_index': 2,
'line_key': 'machine-2',
'fields': [{'field_id': 'fld-qty', 'quote': '20', 'value': '20'}],
},
],
}],
'layout_snapshot': {
'text_blocks': [
{'page_no': 1, 'text': 'page1'},
{'page_no': 2, 'text': 'page2-unrelated'},
],
},
}
pack = select_review_evidence_pack(
document=document,
target_fields=[{
'field_id': 'fld-qty',
'field_code': 'qty',
'scope': 'line',
'line_key': 'machine-2',
}],
evidence_level='L3_page',
)
quotes = [item.get('quote') for item in pack['fields'][0]['snippets']]
assert quotes == ['20']
assert all(item.get('table_id') == 't1' for item in pack['tables'])
assert all(int(item.get('page_no') or 0) == 1 for item in pack['pages'])
def test_l4_full_pdf_downgrades_without_admin_flag():
"""L4 整份 PDF 默认禁止,无 allow_full_pdf 时降级为 L3。"""
assert L4_FULL_PDF_ALLOWED_BY_DEFAULT is False
document = {'document_id': 1, 'layout_schema_candidates': [], 'layout_snapshot': {'text_blocks': []}}
pack = select_review_evidence_pack(
document=document,
target_fields=[{'field_id': 'fld-x', 'scope': 'header'}],
evidence_level='L4_pdf',
allow_full_pdf=False,
)
assert pack['evidence_level'] == 'L3_page'
@@ -0,0 +1,223 @@
"""
tests/test_shipping_order_review_llm_audit.py
用途:锁定 LLM 建议请求/Provider 失败/裁决写入统一不可变审计,并镜像到订单抽取进度流。
依赖:order_review_llm_service、ShippingAuditEvent、ShippingOrderExtractionProgressEvent、复核 Case 夹具。
逻辑:开关关闭时须有 requested + received(failure) 审计与同名进度事件;裁决 accept 须有 llm_suggestion_accepted。
"""
from __future__ import annotations
from datetime import datetime
from unittest.mock import patch
import pytest
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingAuditEvent,
ShippingNoticeCandidate,
ShippingOrderExtractionProgressEvent,
ShippingOrderReviewSuggestion,
)
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_review_llm_service import decide_suggestion, request_field_suggestion
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _seed_review_case(*, suffix: str):
"""物化 Run + Review Case/Draft,返回 user/case/header_field_id。"""
user, agent, session, intake, document = _seed_run_input(suffix=suffix)
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
ensure_order_extraction_plan(run)
unit = run.extraction_plan.units[0]
unit.result_json = {
'orders': [{
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}],
'lines': [{'fields': [{'field_id': 'qty-id', 'observations': [{'value': '1'}]}]}],
'conflicts': [],
}],
}
db.session.add(ShippingNoticeCandidate(
candidate_no=f'CAND-LLM-{suffix}',
intake_id=int(intake.id),
primary_document_id=int(document.id),
candidate_key=f'llm-{suffix}',
order_extraction_run_id=int(run.id),
structured_result_json={},
candidate_status='provisional',
validation_status='needs_review',
))
# 保证冻结 Schema 含 header 字段,供 _schema_field 解析。
schema_snap = dict(run.input_snapshot_json or {})
schema = dict(schema_snap.get('schema') or {})
definition = dict(schema.get('definition') or {})
fields = list(definition.get('fields') or [])
if not any(isinstance(item, dict) and item.get('field_id') == 'po-id' for item in fields):
fields.append({
'field_id': 'po-id',
'field_code': 'po_number',
'scope': 'header',
'enabled': True,
'required': False,
'aliases': ['PO'],
})
definition['fields'] = fields
schema['definition'] = definition
schema_snap['schema'] = schema
run.input_snapshot_json = schema_snap
db.session.commit()
ensure_run_review_cases(run=run)
db.session.commit()
case = run.review_cases[0]
return user, case, 'po-id'
def test_request_suggestion_writes_requested_and_failed_audit_when_disabled(app, monkeypatch):
"""LLM 开关关闭时仍须落 requested + received(failure) 审计事件。"""
with app.app_context():
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_LLM_REVIEW_ENABLED', False)
user, case, field_id = _seed_review_case(suffix='LLM-DISABLED')
# 复核发生在 Run 终态之后;进度桥须仍能写入 LLM 事件。
case.run.status = 'review_required'
db.session.commit()
result = request_field_suggestion(
user_id=int(user.id),
case_no=case.case_no,
field_id=field_id,
)
assert result['suggestion']['status'] == 'provider_unavailable'
events = (
ShippingAuditEvent.query
.filter_by(review_case_no=case.case_no)
.order_by(ShippingAuditEvent.id.asc())
.all()
)
types = [str(item.event_type) for item in events]
assert 'llm_review_requested' in types
assert 'llm_review_received' in types
failed = next(item for item in events if item.event_type == 'llm_review_received')
assert failed.result == 'failure'
assert failed.error_code == 'SHIPPING.REVIEW_LLM_DISABLED'
# 断言:审计事件须同步进入订单抽取进度流,供工作区时间线展示。
progress_codes = {
str(item.event_code)
for item in ShippingOrderExtractionProgressEvent.query.filter_by(run_id=int(case.run_id)).all()
}
assert 'llm_review_requested' in progress_codes
assert 'llm_review_received' in progress_codes
def test_decide_suggestion_writes_accepted_audit_event(app, monkeypatch):
"""人工 accept 必须写入 llm_suggestion_accepted 不可变审计。"""
with app.app_context():
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_LLM_REVIEW_ENABLED', True)
user, case, field_id = _seed_review_case(suffix='LLM-ACCEPT')
suggestion = ShippingOrderReviewSuggestion(
suggestion_no='RSG-ACCEPT01',
review_case_id=int(case.id),
document_id=int(case.document_id),
run_id=int(case.run_id),
field_id=field_id,
scope='header',
evidence_level='L1_field',
status='validated',
contract_version='order-review-llm.v1',
draft_version_at_request=1,
requested_by_id=int(user.id),
suggested_value_json={'value': 'PO-AI'},
validation_issues_json=[],
created_at=datetime.utcnow(),
)
db.session.add(suggestion)
db.session.commit()
with patch(
'app.services.shipping_notice.order_review_llm_service.adjudicate_llm_suggestion_on_draft',
return_value={'case_no': case.case_no},
):
decide_suggestion(
user_id=int(user.id),
case_no=case.case_no,
suggestion_no='RSG-ACCEPT01',
decision='accept',
expected_draft_version=1,
note='ok',
)
events = ShippingAuditEvent.query.filter_by(
review_case_no=case.case_no,
event_type='llm_suggestion_accepted',
).all()
assert len(events) == 1
assert events[0].result == 'success'
assert events[0].action == 'llm_suggestion_accept'
# after 快照经白名单脱敏,仅保留字段定位与状态;建议号在 metadata。
assert (events[0].after_snapshot_json or {}).get('field_id') == field_id
assert (events[0].after_snapshot_json or {}).get('status') == 'accepted'
assert (events[0].metadata_json or {}).get('suggestion_no') == 'RSG-ACCEPT01' or (
(events[0].metadata_json or {}).get('contract_version') == 'order-review-llm.v1'
)
def test_decide_suggestion_rejects_accept_on_validation_failed(app, monkeypatch):
"""validation_failed 建议禁止 accept,仅允许 reject。"""
with app.app_context():
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_LLM_REVIEW_ENABLED', True)
user, case, field_id = _seed_review_case(suffix='LLM-FAIL-ACCEPT')
suggestion = ShippingOrderReviewSuggestion(
suggestion_no='RSG-FAIL01',
review_case_id=int(case.id),
document_id=int(case.document_id),
run_id=int(case.run_id),
field_id=field_id,
scope='header',
evidence_level='L1_field',
status='validation_failed',
contract_version='order-review-llm.v1',
draft_version_at_request=1,
requested_by_id=int(user.id),
suggested_value_json={'value': 'PO-HALLUCINATION'},
validation_issues_json=[{'code': 'value_not_in_evidence', 'severity': 'blocking'}],
created_at=datetime.utcnow(),
)
db.session.add(suggestion)
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
decide_suggestion(
user_id=int(user.id),
case_no=case.case_no,
suggestion_no='RSG-FAIL01',
decision='accept',
expected_draft_version=1,
)
assert exc_info.value.code == 'SHIPPING.REVIEW_LLM_SUGGESTION_NOT_ACCEPTABLE'
with patch(
'app.services.shipping_notice.order_review_llm_service.adjudicate_llm_suggestion_on_draft',
return_value={'case_no': case.case_no},
):
decide_suggestion(
user_id=int(user.id),
case_no=case.case_no,
suggestion_no='RSG-FAIL01',
decision='reject',
expected_draft_version=1,
reason='not in evidence',
)
refreshed = db.session.get(ShippingOrderReviewSuggestion, suggestion.id)
assert refreshed is not None
assert refreshed.status == 'rejected'
@@ -0,0 +1,62 @@
"""
backend/tests/test_shipping_order_review_llm_validation.py
用途:验证 LLM 建议值须逐字存在于冻结证据包。
依赖:order_review_llm_validation。
"""
from app.services.shipping_notice.order_review_llm_validation import validate_suggestions_against_evidence
def test_validate_suggestions_rejects_out_of_document_value():
"""文档外幻觉值必须 validation_failed。"""
pack = {
'fields': [{'field_id': 'fld-qty', 'snippets': [{'quote': '50'}]}],
'tables': [],
'pages': [],
}
suggestions = [{
'field_id': 'fld-qty',
'suggested_value': '999',
'quote': '999',
}]
validated = validate_suggestions_against_evidence(suggestions=suggestions, evidence_pack=pack)
assert validated[0]['valid'] is False
assert validated[0]['rejection_reason'] == 'value_not_in_evidence'
def test_validate_suggestions_accepts_verbatim_match():
"""逐字匹配的证据值应通过校验。"""
pack = {
'fields': [{'field_id': 'fld-mpn', 'snippets': [{'quote': 'ABC-01'}]}],
'tables': [],
'pages': [],
}
suggestions = [{'field_id': 'fld-mpn', 'suggested_value': 'ABC-01', 'quote': 'ABC-01'}]
validated = validate_suggestions_against_evidence(suggestions=suggestions, evidence_pack=pack)
assert validated[0]['valid'] is True
def test_validate_suggestions_rejects_numeric_substring_false_positive():
"""数量 `10` 不得因证据 `100` 的子串而通过。"""
pack = {
'fields': [{'field_id': 'fld-qty', 'snippets': [{'quote': '100'}]}],
'tables': [],
'pages': [],
}
suggestions = [{'field_id': 'fld-qty', 'suggested_value': '10', 'quote': '10'}]
validated = validate_suggestions_against_evidence(suggestions=suggestions, evidence_pack=pack)
assert validated[0]['valid'] is False
assert validated[0]['rejection_reason'] == 'value_not_in_evidence'
def test_validate_suggestions_requires_target_field_snippets():
"""不得用其它字段的证据验证当前字段建议。"""
pack = {
'fields': [{'field_id': 'fld-other', 'snippets': [{'quote': '10'}]}],
'tables': [],
'pages': [],
}
suggestions = [{'field_id': 'fld-qty', 'suggested_value': '10'}]
validated = validate_suggestions_against_evidence(suggestions=suggestions, evidence_pack=pack)
assert validated[0]['valid'] is False
@@ -0,0 +1,204 @@
"""
tests/test_shipping_order_review_progress_bridge.py
用途:专项验证复核进度旁路的 Unit/Run 写入、幂等与 Savepoint 事务隔离。
依赖:order_review_progress_bridge、ShippingOrderExtractionProgressEvent、复核 Case 夹具。
逻辑:覆盖 Unit 命中、无 Unit 回退 Run、重复事件幂等、旁路异常后外层业务仍可提交。
"""
from __future__ import annotations
from unittest.mock import patch
from sqlalchemy.exc import OperationalError
from app import db
from app.models import (
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionUnit,
)
from app.services.shipping_notice.order_extraction_progress import record_run_progress
from app.services.shipping_notice.order_review_progress_bridge import record_review_progress_event
from tests.test_shipping_order_review_llm_audit import _seed_review_case
def _progress_codes(run_id: int) -> set[str]:
"""读取指定 Run 的进度事件码集合。"""
return {
str(item.event_code)
for item in ShippingOrderExtractionProgressEvent.query.filter_by(run_id=int(run_id)).all()
}
def test_bridge_writes_unit_progress_when_unit_exists(app):
"""存在 Plan Unit 时须写入带 unit_id 的进度事件。"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-UNIT')
case.run.status = 'review_required'
db.session.commit()
ok = record_review_progress_event(
case=case,
audit_event_type='llm_review_requested',
summary={'field_id': 'po-id'},
)
db.session.commit()
assert ok is True
assert 'llm_review_requested' in _progress_codes(int(case.run_id))
row = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=int(case.run_id), event_code='llm_review_requested')
.order_by(ShippingOrderExtractionProgressEvent.id.desc())
.first()
)
assert row is not None
assert row.unit_id is not None
assert int(row.document_id or 0) == int(case.document_id)
def test_bridge_falls_back_to_run_progress_without_unit(app):
"""找不到 Unit 时回退写入 Run 级进度事件。"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-RUN')
case.run.status = 'review_required'
plan_id = int(case.run.extraction_plan.id)
ShippingOrderExtractionUnit.query.filter_by(plan_id=plan_id).delete(
synchronize_session=False,
)
db.session.commit()
ok = record_review_progress_event(
case=case,
audit_event_type='review_field_changed',
summary={'field_id': 'po-id'},
)
db.session.commit()
assert ok is True
assert 'review_field_changed' in _progress_codes(int(case.run_id))
row = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=int(case.run_id), event_code='review_field_changed')
.order_by(ShippingOrderExtractionProgressEvent.id.desc())
.first()
)
assert row is not None
assert row.unit_id is None
def test_bridge_is_idempotent_for_duplicate_event(app):
"""相同进度事件重复写入须幂等(第二次返回 False,不新增行)。"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-IDEM')
case.run.status = 'review_required'
db.session.commit()
first = record_review_progress_event(
case=case,
audit_event_type='llm_suggestion_accepted',
summary={'suggestion_no': 'RSG-1', 'field_id': 'po-id'},
)
db.session.flush()
second = record_review_progress_event(
case=case,
audit_event_type='llm_suggestion_accepted',
summary={'suggestion_no': 'RSG-1', 'field_id': 'po-id'},
)
db.session.commit()
assert first is True
assert second is False
count = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=int(case.run_id), event_code='llm_suggestion_accepted')
.count()
)
assert count == 1
def test_bridge_exception_does_not_block_outer_commit(app):
"""
进度写入抛出数据库异常后,外层业务变更仍可提交。
断言:旁路返回 False;Case 状态更新可成功 commit;无脏进度事件。
"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-ISO')
case.run.status = 'review_required'
db.session.commit()
case.status = 'draft'
db.session.flush()
boom = OperationalError('flush', {}, Exception('simulated progress failure'))
with patch(
'app.services.shipping_notice.order_review_progress_bridge.record_unit_progress',
side_effect=boom,
), patch(
'app.services.shipping_notice.order_review_progress_bridge.record_run_progress',
side_effect=boom,
):
ok = record_review_progress_event(
case=case,
audit_event_type='llm_review_received',
summary={'field_id': 'po-id'},
)
assert ok is False
case.status = 'ready'
db.session.commit()
db.session.refresh(case)
assert case.status == 'ready'
assert 'llm_review_received' not in _progress_codes(int(case.run_id))
def test_progress_flush_failure_inside_nested_keeps_outer_committable(app):
"""
commit=False 进度 flush 失败时,调用方 Savepoint 回滚后外层业务仍可提交。
"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-NEST')
case.run.status = 'review_required'
db.session.commit()
case.status = 'draft'
db.session.flush()
nested = db.session.begin_nested()
boom = OperationalError('flush', {}, Exception('simulated nested flush failure'))
ok = False
raised = False
with patch.object(db.session, 'flush', side_effect=boom):
try:
ok = record_run_progress(
run=case.run,
event_code='llm_review_requested',
summary={'case_no': case.case_no},
commit=False,
)
except OperationalError:
# 部分 Session 代理无法探测嵌套事务时,进度服务会向上抛出。
raised = True
ok = False
assert ok is False or raised
if nested.is_active:
nested.rollback()
case.status = 'ready'
db.session.commit()
db.session.refresh(case)
assert case.status == 'ready'
def test_bridge_ignores_unknown_audit_event(app):
"""未映射的审计事件码不得写入进度流。"""
with app.app_context():
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-SKIP')
before = len(_progress_codes(int(case.run_id)))
ok = record_review_progress_event(
case=case,
audit_event_type='not_a_progress_event',
)
assert ok is False
assert len(_progress_codes(int(case.run_id))) == before
@@ -62,6 +62,9 @@ def test_serialize_workflow_counts_and_items(app):
assert payload['items'][0]['root_document_id'] == int(document.id)
assert payload['items'][0]['current_document_filename'] == document.filename
assert payload['items'][0]['root_document_filename'] == document.filename
assert 'cancel' in payload['items'][0]['available_actions']
assert 'reparse' not in payload['items'][0]['available_actions']
assert payload['items'][0]['reparse_kind'] is None
def test_manual_upload_pending_is_not_completed_count(app):
@@ -199,3 +202,35 @@ def test_serialize_workflow_event_includes_actor_id(app):
# 关键断言:actor_type 与 actor_id 同时出现在用户态投影中。
assert payload['actor_type'] == 'user'
assert payload['actor_id'] == '42'
def test_pending_review_without_case_cannot_reparse(app):
"""pending_review 且无 current_case_no 时不得开放 reparse(对齐 ledger CASE_REQUIRED)。"""
with app.app_context():
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-NOCASE')
workflow = create_workflow(
conversation_id=session.session_id,
owner_user_id=int(user.id),
owner_agent_id=int(agent.id),
)
item = ensure_workflow_item_for_document(
workflow=workflow,
conversation_id=session.session_id,
owner_user_id=int(user.id),
document_id=int(document.id),
)
transition_item_status(
item=item,
lifecycle_status='pending_review',
actor_type='system',
actor_id='test',
)
item.current_case_no = None
item.current_run_no = 'SNER-STILL-RUNNING'
db.session.commit()
payload = serialize_workflow_item(item)
assert payload['lifecycle_status'] == 'pending_review'
assert 'reparse' not in payload['available_actions']
assert payload['reparse_kind'] is None
assert 'cancel' in payload['available_actions']