Files
syops/backend/tests/test_shipping_document_layout_lifecycle.py
T

840 lines
38 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/tests/test_shipping_document_layout_lifecycle.py
用途:验证 L1 版面快照 checksum、版本幂等、XFA 证据本地化、容量门禁和当前成功版本保护。
依赖:ShippingOrderDocument/LayoutVersion/XfaStructureAnalysis、document_layout.lifecycle、Flask 测试库。
逻辑:相同快照复用;XFA 复用同步克隆 document-scoped 分析;失败版本不覆盖旧成功引用。
"""
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import (
FileAsset,
Job,
ShippingDocumentLayoutVersion,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingXfaStructureAnalysis,
User,
)
from app.services.shipping_notice.document_layout.lifecycle import (
COORDINATE_EVIDENCE_REF_KEY,
canonical_layout_payload,
claim_layout_version,
complete_layout_version,
current_layout_snapshot,
record_inline_layout_snapshot,
schedule_layout_version,
schedule_document_layouts,
sync_layout_after_job_recovery,
)
from app.services.shipping_notice.document_layout import lifecycle as layout_lifecycle
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
ensure_on_demand_coordinate_evidence,
)
def _document() -> ShippingOrderDocument:
"""创建带稳定内容哈希的最小附件 Document。"""
user = User(username='layout-owner', email='layout-owner@example.com', role='user', status='active')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-LAYOUT-L1', owner_user_id=user.id, original_filename='sample.pdf',
storage_provider='minio', storage_bucket='test', storage_key='sample.pdf',
content_hash='a' * 64, file_size=10, mime_type='application/pdf',
upload_status='ready', lifecycle_status='referenced',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-L1', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='sample.pdf', filename='sample.pdf', content_hash='a' * 64,
classification='order_notice', parse_status='parsed',
)
db.session.add(document)
db.session.flush()
return document
def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
"""构造不含正文的紧凑布局快照。"""
return {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline',
'status': status, 'tables': [], 'layout_candidate': {},
'coordinate_evidence': {'pages': {}, 'page_glyphs': {}},
'issues': [], 'marker': marker,
}
def _externalizable_evidence() -> dict:
"""构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。
生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被
``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除,
改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。
"""
return {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'x'}]},
}
def test_layout_snapshot_checksum_and_idempotent_current_version(app):
"""相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。"""
with app.app_context():
document = _document()
checksum, size = canonical_layout_payload(_snapshot())
first = record_inline_layout_snapshot(document, _snapshot())
replay = record_inline_layout_snapshot(document, _snapshot())
db.session.commit()
assert first.id == replay.id
assert first.payload_checksum == checksum
assert first.payload_size_bytes == size
assert ShippingDocumentLayoutVersion.query.count() == 1
assert document.current_layout_version_id == first.id
assert current_layout_snapshot(document)['marker'] == 'v1'
def test_ready_pdf_layout_requires_coordinate_evidence_asset(app, monkeypatch):
"""关键断言:PDF 坐标证据资产保存失败时,布局不得伪装为 ready。"""
with app.app_context():
document = _document()
monkeypatch.setattr(layout_lifecycle, '_persist_coordinate_evidence_asset', lambda **_: None)
snapshot = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><td>x</td></tr></table>'}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [{'text': 'x'}]},
'tables': {'table-1': [{'text': 'x'}]},
},
}
version = record_inline_layout_snapshot(document, snapshot)
assert version.status == 'failed'
assert 'shipping_document_layout_coordinate_evidence_persist_failed' in version.issues_json
def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app):
"""坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。"""
with app.app_context():
document = _document()
analysis = ShippingXfaStructureAnalysis(
document_id=document.id,
layout_version_id=None,
source_content_hash=document.content_hash,
document_kind='xfa_hybrid',
analysis_status='ready',
template_packet_checksum='sha256:template',
datasets_packet_checksum='sha256:datasets',
dataset_structure_fingerprint='sha256:structure',
packet_checksums_json={'datasets': 'sha256:datasets'},
stats_json={}, security_summary_json={}, tree_summary_json={},
parser_identity='xfa-parser.v1', contract_version='xfa-contract.v1',
)
db.session.add(analysis)
db.session.flush()
first = record_inline_layout_snapshot(document, {
**_snapshot(marker='xfa-base'),
'xfa_capability': {'structure_analysis_id': analysis.id},
'capability': {'structure_analysis_id': analysis.id},
})
assert analysis.layout_version_id == first.id
derived = record_inline_layout_snapshot(document, {
**dict(first.payload_json),
'marker': 'xfa-coordinate-evidence',
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
db.session.commit()
derived_analysis_id = derived.payload_json['xfa_capability']['structure_analysis_id']
derived_analysis = db.session.get(ShippingXfaStructureAnalysis, derived_analysis_id)
# 关键断言:新 Layout 与新 Analysis 一一绑定,旧分析仍保留原 Layout 审计身份。
assert derived.id != first.id
assert derived_analysis_id != analysis.id
assert derived_analysis.layout_version_id == derived.id
assert analysis.layout_version_id == first.id
assert derived.payload_json['capability']['structure_analysis_id'] == derived_analysis.id
# 修复部署前已落库的派生快照按原 checksum 重放时,同样必须补齐新 identity。
stale = record_inline_layout_snapshot(document, {
**_snapshot(marker='xfa-pre-fix-stale'),
'xfa_capability': {'structure_analysis_id': analysis.id},
'capability': {'structure_analysis_id': analysis.id},
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
stale_payload = {
**_snapshot(marker='xfa-pre-fix-stale'),
'xfa_capability': {'structure_analysis_id': analysis.id},
'capability': {'structure_analysis_id': analysis.id},
}
stale.payload_json = stale_payload
stale.payload_checksum, stale.payload_size_bytes = canonical_layout_payload(stale_payload)
db.session.flush()
repaired = record_inline_layout_snapshot(document, {
**_snapshot(marker='xfa-pre-fix-stale'),
'xfa_capability': {'structure_analysis_id': analysis.id},
'capability': {'structure_analysis_id': analysis.id},
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
repaired_analysis = db.session.get(
ShippingXfaStructureAnalysis,
repaired.payload_json['xfa_capability']['structure_analysis_id'],
)
assert repaired.id == stale.id
assert repaired_analysis.id != analysis.id
assert repaired_analysis.layout_version_id == repaired.id
def test_failed_or_oversized_layout_does_not_replace_last_good_version(app):
"""失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 500
with app.app_context():
document = _document()
good = record_inline_layout_snapshot(document, _snapshot())
failed = record_inline_layout_snapshot(document, _snapshot(status='failed', marker='failed'))
oversized = record_inline_layout_snapshot(document, {
**_snapshot(marker='large'), 'tables': [{'html': 'X' * 5000}],
})
db.session.commit()
assert failed.status == 'failed'
assert oversized.status == 'failed'
assert oversized.payload_json is None
assert 'shipping_document_layout_snapshot_size_exceeded' in oversized.issues_json
assert document.current_layout_version_id == good.id
assert current_layout_snapshot(document)['marker'] == 'v1'
assert ShippingDocumentLayoutVersion.query.count() == 3
def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
"""同 parser 成功版本默认复用;显式重解析创建下一 queued 版本及独立 Job。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
document = _document()
# PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。
ready = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
})
assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json
reused = schedule_layout_version(document)
forced = schedule_layout_version(document, force=True)
db.session.commit()
assert reused.id == ready.id
assert forced.id != ready.id
assert forced.version == 2
assert forced.status == 'queued'
assert forced.job_id is not None
job = db.session.get(Job, forced.job_id)
assert job.job_type == 'shipping_document_layout'
assert job.payload_json == {'layout_version_id': forced.id}
def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_document(app):
"""相同管理员重复上传相同文件时,新 Document 必须拥有自己的可用布局版本。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
original = _document()
ready = record_inline_layout_snapshot(original, {
**_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
})
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate.pdf', filename='duplicate.pdf', content_hash=original.content_hash,
classification='order_notice', parse_status='parsed',
)
db.session.add(duplicate)
db.session.flush()
reused = schedule_layout_version(duplicate)
db.session.commit()
# Layout 版本归属当前 Document;只复用冻结 payload,禁止跨 Document 外键引用。
assert reused.id != ready.id
assert reused.document_id == duplicate.id
assert duplicate.current_layout_version_id == reused.id
assert reused.status == 'ready'
assert reused.payload_json == ready.payload_json
assert ShippingDocumentLayoutVersion.query.count() == 2
def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
"""ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
original = _document()
# 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref),
# 缺页坐标由正式识别按需从原 PDF 恢复。
incomplete = record_inline_layout_snapshot(original, {
**_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
})
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate-incomplete.pdf', filename='duplicate-incomplete.pdf',
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
)
db.session.add(duplicate)
db.session.flush()
scheduled = schedule_layout_version(duplicate)
db.session.commit()
assert incomplete.status == 'ready'
assert scheduled.status == 'ready'
assert scheduled.id != incomplete.id
def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkeypatch):
"""共享视觉 Layout 带 datasets capability 时,复用必须本地化其结构分析身份。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
audit_events: list[str] = []
def _capture_audit(**kwargs):
audit_events.append(str(kwargs.get('event_type')))
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
_capture_audit,
)
with app.app_context():
original = _document()
source_analysis = ShippingXfaStructureAnalysis(
document_id=original.id,
layout_version_id=None,
source_content_hash=original.content_hash,
document_kind='xfa_hybrid',
analysis_status='ready',
template_packet_checksum='sha256:template',
datasets_packet_checksum='sha256:datasets',
dataset_structure_fingerprint='sha256:structure',
packet_checksums_json={'datasets': 'sha256:datasets'},
stats_json={'leaf_count': 8},
security_summary_json={'scripts_executed': False},
tree_summary_json={'known_path_ids': ['path-1']},
parser_identity='xfa-parser.v1',
contract_version='xfa-contract.v1',
)
db.session.add(source_analysis)
db.session.flush()
source_layout = record_inline_layout_snapshot(original, {
'status': 'ready',
'provider': 'mineru',
'provider_version': 'mineru-v1',
'backend': 'pipeline',
'snapshot_version': 'shipping_document_layout.v1',
'tables': [],
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset);
# datasets 仅为末端值源。
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}},
'xfa_capability': {
'structure_analysis_ready': True,
'structure_analysis_id': source_analysis.id,
'template_packet_checksum': source_analysis.template_packet_checksum,
'dataset_structure_fingerprint': source_analysis.dataset_structure_fingerprint,
},
'capability': {
'structure_analysis_ready': True,
'structure_analysis_id': source_analysis.id,
},
})
source_analysis.layout_version_id = source_layout.id
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-XFA-DUPLICATE', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate-xfa.pdf', filename='duplicate-xfa.pdf',
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
)
db.session.add(duplicate)
db.session.flush()
localized = schedule_layout_version(duplicate)
db.session.commit()
target_analysis = ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).one()
target_capability = localized.payload_json['xfa_capability']
assert localized.document_id == duplicate.id
assert localized.id != source_layout.id
assert target_analysis.id != source_analysis.id
assert target_analysis.layout_version_id == localized.id
assert target_analysis.source_content_hash == duplicate.content_hash
assert target_analysis.dataset_structure_fingerprint == source_analysis.dataset_structure_fingerprint
assert target_capability['structure_analysis_id'] == target_analysis.id
assert localized.payload_json['capability']['structure_analysis_id'] == target_analysis.id
assert 'xfa_structure_analysis_reused' in audit_events
def test_legacy_xfa_only_layout_without_shared_visual_evidence_is_reparsed(app, monkeypatch):
"""旧 XFA-only 快照缺共同视觉证据时一律重解析,不能保留格式专用复用分支。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
audit_events: list[str] = []
def _capture_audit(**kwargs):
audit_events.append(str(kwargs.get('event_type')))
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
_capture_audit,
)
with app.app_context():
original = _document()
source_layout = record_inline_layout_snapshot(original, {
'status': 'ready',
'provider': 'xfa',
'provider_version': 'xfa-parser.v1',
'backend': 'pypdf',
'snapshot_version': 'shipping_document_layout.v1',
'tables': [],
'xfa_capability': {
'structure_analysis_ready': True,
'structure_analysis_id': 999999,
'template_packet_checksum': 'sha256:template',
'dataset_structure_fingerprint': 'sha256:structure',
},
})
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-XFA-MISSING-ANALYSIS', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate-xfa-missing.pdf', filename='duplicate-xfa-missing.pdf',
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
)
db.session.add(duplicate)
db.session.flush()
scheduled = schedule_layout_version(duplicate)
db.session.commit()
assert source_layout.status == 'ready'
assert scheduled.document_id == duplicate.id
assert scheduled.status == 'queued'
assert duplicate.current_layout_version_id is None
assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0
assert not audit_events
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:sha256-old',
)
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(':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):
"""Job 回收后版本回 queued 并清 lease,旧 Worker 结果不得覆盖当前成功版本。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
document = _document()
ready = record_inline_layout_snapshot(document, _snapshot())
pending = schedule_layout_version(document, force=True)
job = db.session.get(Job, pending.job_id)
job.status = 'running'
job.attempts = 1
db.session.commit()
claimed = claim_layout_version(pending.id, job_id=job.id, owned_attempt=1)
assert claimed is not None
_version, old_lease = claimed
job.status = 'queued'
sync_layout_after_job_recovery(job)
db.session.commit()
assert pending.status == 'queued'
assert pending.lease_token is None
assert complete_layout_version(
pending.id, lease_token=old_lease, snapshot=_snapshot(marker='stale'),
) is False
db.session.refresh(document)
assert document.current_layout_version_id == ready.id
def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app):
"""PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document = _document()
pending = schedule_layout_version(document, force=True)
job = db.session.get(Job, pending.job_id)
job.status = 'running'
job.attempts = 1
db.session.commit()
claimed = claim_layout_version(pending.id, job_id=job.id, owned_attempt=1)
assert claimed is not None
_version, lease = claimed
snapshot = {
**_snapshot(),
'tables': [{
'table_id': 'table-1',
'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'X' * 3000}]},
'tables': {'table-1': [{'text': 'Y' * 5000}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
'layout_candidate': {'table_count': 1, 'tables': [{'table_id': 'table-1'}]},
}
assert complete_layout_version(pending.id, lease_token=lease, snapshot=snapshot) is True
db.session.refresh(pending)
db.session.refresh(document)
assert pending.status == 'ready'
assert document.current_layout_version_id == pending.id
assert pending.payload_json['tables'] == snapshot['tables']
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。
assert 'coordinate_evidence' not in pending.payload_json
ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY]
assert ref['asset_no']
assert ref['checksum']
assert ref['size'] > 0
assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1'
# 模板结构保留,无需把外置证据当作容量压缩问题。
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json
assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json
assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json
def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app):
"""普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document = _document()
snapshot = {
**_snapshot(marker='inline-externalized'),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
}],
'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'}]},
}
version = record_inline_layout_snapshot(document, snapshot)
assert version.status == 'ready'
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_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app):
"""压缩后顶层业务 tables 列表不得进入坐标映射并触发 dict 转换异常。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
'cells': [], 'rows': [], 'columns': [], 'source': 'native', 'status': 'ready',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
record_inline_layout_snapshot(document, layout)
restored = ensure_on_demand_coordinate_evidence(
document=document,
layout=layout,
page_nos=set(),
)
assert restored['tables'] == layout['tables']
assert 'tables' not in restored['coordinate_evidence']
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch):
"""外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。"""
with app.app_context():
document = _document()
# 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。
current = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.flush()
document.current_layout_version = current
frozen_layout = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
lambda *, characters, table_bbox: [glyph],
)
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=frozen_layout, page_nos={1},
)
# 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch):
"""外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。"""
with app.app_context():
document = _document()
current = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
document.current_layout_version = current
# 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。
stale_run_layout = {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'sources': {'pages': {'1': 'ocr_coordinate'}},
},
}
glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=stale_run_layout, page_nos={1},
)
# 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT'
assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch):
"""同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [
{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 10, 'x1': 100, 'y1': 40}},
{'table_id': 'table-2', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 100, 'y1': 90}},
],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': {'text': 'X'})],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
lambda *, characters, table_bbox: [{'text': str(table_bbox['y0'])}],
)
restored = ensure_on_demand_coordinate_evidence(
document=document,
layout=layout,
page_nos={1},
# 兼容旧调用方即使只传入同页最后一张表,也不能覆盖 layout 中的第一张表。
table_by_page={1: layout['tables'][1]},
)
# 关键断言:同页表格不能被 page_no 字典覆盖,正式抽取可按真实 table_id 逐表重建。
assert restored['coordinate_evidence']['tables'] == {
'table-1': [{'text': '10'}],
'table-2': [{'text': '50'}],
}
def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(app, monkeypatch):
"""原 PDF 无字符且 OCR 不可用时不得伪造坐标,调用方必须转 Review。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 80}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
page = SimpleNamespace(page_no=1, width=100, height=200, image=None, characters=[])
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines',
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError('ocr unavailable')),
)
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=layout, page_nos={1},
)
assert not restored['coordinate_evidence'].get('page_glyphs')
def test_layout_document_budget_defers_unscheduled_pdfs(app):
"""超过单 Intake 配额的 PDF 本轮不排程、不写 unsupported;后续 schedule 可继续排上。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1
with app.app_context():
first = _document()
second = ShippingOrderDocument(
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
attachment_key='second.pdf', filename='second.pdf', content_hash='b' * 64,
classification='order_notice', parse_status='parsed',
)
text = ShippingOrderDocument(
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
attachment_key='notes.txt', filename='notes.txt', content_hash='c' * 64,
classification='order_notice', parse_status='parsed',
)
db.session.add_all([second, text])
db.session.flush()
versions = schedule_document_layouts([first, text, second])
db.session.commit()
assert len(versions) == 1
assert versions[0].status == 'queued'
assert versions[0].document_id == first.id
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=second.id).count() == 0
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=text.id).count() == 0
# 第一份进入可用终态后,第二次 schedule 应排上此前延后的 PDF。
versions[0].status = 'ready'
first.current_layout_version_id = versions[0].id
db.session.commit()
second_wave = schedule_document_layouts([first, text, second])
db.session.commit()
assert len(second_wave) == 1
assert second_wave[0].document_id == second.id
assert second_wave[0].status == 'queued'
def test_deleting_document_cascades_layout_versions(app):
"""Document 删除必须先解除 current 引用,并级联清理其全部布局版本。"""
with app.app_context():
document = _document()
version = record_inline_layout_snapshot(document, _snapshot())
document_id = document.id
version_id = version.id
db.session.commit()
db.session.delete(document)
db.session.commit()
assert db.session.get(ShippingOrderDocument, document_id) is None
assert db.session.get(ShippingDocumentLayoutVersion, version_id) is None