"""
backend/tests/test_shipping_document_layout_job.py
用途:验证独立布局 Job 从对象存储读取附件、按 lease 收口并在失败时同步版本状态。
依赖:shipping_document_layout handler、lifecycle、layout_diagnostics、通用 Job queue。
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease;
PR-0 断言 Job result 含全量 timings/counts,且诊断字段不进入 layout snapshot。
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_document_layout import LAYOUT_JOB_ERROR, run_shipping_document_layout
from app.models import Job
from app.services.shipping_notice.document_layout.layout_diagnostics import (
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
)
from app.services.shipping_notice.document_layout.lifecycle import (
COORDINATE_EVIDENCE_REF_KEY,
schedule_layout_version,
)
from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot
def _assert_layout_job_diagnostics_contract(result: dict) -> None:
"""
断言 Job result 含 PR-0 全量 timings/counts,且诊断字段不进 snapshot。
核心断言:契约键齐全;未执行阶段为 0;ocr_engine_warm 为 bool。
"""
timings = result.get('timings')
counts = result.get('counts')
assert isinstance(timings, dict)
assert isinstance(counts, dict)
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
assert key in timings
assert isinstance(timings[key], int)
assert timings[key] >= 0
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
assert key in counts
if key == 'ocr_engine_warm':
assert isinstance(counts[key], bool)
else:
assert isinstance(counts[key], int)
assert counts[key] >= 0
def _running_layout_job(app):
"""创建布局版本并模拟通用队列已领取该 Job。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
document = _document()
version = schedule_layout_version(document, force=True)
job = db.session.get(Job, version.job_id)
job.status = 'running'
job.attempts = 1
job.max_attempts = 3
db.session.commit()
return document, version, job
def test_layout_job_completes_version_and_updates_document_current(app):
"""成功 Provider 结果必须冻结 checksum 并成为 Document 当前布局。"""
with app.app_context():
document, version, job = _running_layout_job(app)
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
return_value={
**_snapshot(marker='worker'),
'coordinate_evidence': _externalizable_evidence(),
},
):
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(document)
db.session.refresh(job)
assert version.status == 'ready'
assert version.payload_checksum
assert version.lease_token is None
assert document.current_layout_version_id == version.id
assert job.status == 'success'
assert job.result_json['status'] == 'ready'
assert job.result_json['provider_status'] == 'ready'
assert job.message == '文档版面解析完成'
# 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。
assert 'coordinate_evidence' not in version.payload_json
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
_assert_layout_job_diagnostics_contract(job.result_json)
assert 'timings' not in version.payload_json
assert 'counts' not in version.payload_json
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
"""表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document, version, job = _running_layout_job(app)
snapshot = {
**_snapshot(marker='compacted-worker'),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '
',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'X' * 3000}]},
'tables': {'table-1': [{'text': 'Y' * 5000}]},
},
'layout_candidate': {'table_count': 1, 'tables': [{'table_id': 'table-1'}]},
}
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
return_value=snapshot,
):
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(document)
db.session.refresh(job)
assert version.status == 'ready'
assert document.current_layout_version_id == version.id
assert job.status == 'success'
assert job.result_json['status'] == 'ready'
assert job.message == '文档版面解析完成'
assert version.payload_json['tables'] == snapshot['tables']
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。
assert 'coordinate_evidence' not in version.payload_json
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
def test_layout_job_failure_fails_version_and_clears_lease(app):
"""不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。"""
with app.app_context():
_document_row, version, job = _running_layout_job(app)
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
side_effect=RuntimeError('temporary storage failure'),
):
with pytest.raises(RuntimeError, match='temporary storage failure'):
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(job)
# 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。
assert job.status == 'failed'
assert version.status == 'failed'
assert version.lease_token is None
assert job.error_message == LAYOUT_JOB_ERROR
def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app):
"""最后一次失败必须同步终结布局版本,Job 只保留稳定错误码而非内部异常。"""
with app.app_context():
_document_row, version, job = _running_layout_job(app)
job.max_attempts = 1
db.session.commit()
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
side_effect=RuntimeError('secret storage endpoint failed'),
):
with pytest.raises(RuntimeError, match='secret storage endpoint failed'):
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(job)
assert job.status == 'failed'
assert job.error_message == LAYOUT_JOB_ERROR
assert 'secret storage endpoint' not in str(job.error_message)
assert version.status == 'failed'
assert version.lease_token is None
assert 'shipping_document_layout_job_exhausted' in version.issues_json
def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
"""XFA hybrid 必须保留 datasets 身份,同时进入统一视觉表格/Layout 管线。"""
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
with app.app_context():
document, version, job = _running_layout_job(app)
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
return_value=pdf_bytes,
), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
) as visual_layout_mock:
visual_layout_mock.return_value = {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'provider': 'mineru',
'status': 'ready',
'tables': [{'table_id': 'visual-main', 'page_no': 1}],
'capability': {},
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [{'text': 'x'}]},
},
'issues': [],
}
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(document)
db.session.refresh(job)
visual_layout_mock.assert_called_once()
assert version.status == 'ready'
assert version.payload_json.get('provider') == 'mineru'
assert version.payload_json.get('tables') == [{'table_id': 'visual-main', 'page_no': 1}]
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
assert document.current_layout_version_id == version.id
assert job.status == 'success'
_assert_layout_job_diagnostics_contract(job.result_json)
# XFA 早退未走 OCR/OpenCV;细分字段仍存在且为 0。
assert job.result_json['counts']['ocr_call_count'] == 0
assert job.result_json['timings']['ocr_inference_ms'] == 0
assert 'timings' not in version.payload_json
assert 'counts' not in version.payload_json
def test_runtime_xfa_visual_layout_does_not_create_unfrozen_value_source_capability(app):
"""runtime 只提供共享视觉 Layout;正式 Job 才能冻结并附加 datasets capability。"""
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
from tests.test_shipping_document_layout_runtime import _candidate
with app.app_context():
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
with patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
) as mineru_client, patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=_candidate(),
):
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
snapshot = build_mineru_table_snapshot(
filename='sample.pdf',
content=pdf_bytes,
document_id=1,
content_hash='a' * 64,
)
mineru_client.return_value.parse_file_async.assert_called_once()
assert snapshot is not None
assert 'xfa_capability' not in snapshot
assert snapshot['provider'] != 'xfa'