fix(shipping-notice): 版面配额延后排程并修复预算续抽与表头对齐

This commit is contained in:
hugo committed 2026-09-10 22:19:41 +08:00
1 parent 6052c46d88
commit 6e1159a08b
12 files changed
+744 -163

No files matched your search

@@ -783,8 +783,8 @@ def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(
assert not restored['coordinate_evidence'].get('page_glyphs')
def test_layout_document_budget_creates_unsupported_audit_versions(app):
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
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():
@@ -805,12 +805,23 @@ def test_layout_document_budget_creates_unsupported_audit_versions(app):
versions = schedule_document_layouts([first, text, second])
db.session.commit()
assert len(versions) == 2
assert len(versions) == 1
assert versions[0].status == 'queued'
assert versions[1].status == 'unsupported'
assert versions[1].issues_json == ['mineru_intake_document_budget_exceeded']
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 引用,并级联清理其全部布局版本。"""
@@ -53,6 +53,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
reparse_order_extraction_run,
retry_order_extraction_run,
resume_runs_waiting_for_layout,
revive_layout_prerequisite_failed_units,
order_extraction_layout_prerequisite_issues,
order_extraction_layouts_failed,
materialize_order_extraction_run_inputs,
@@ -706,6 +707,66 @@ def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction
assert ShippingOrderProcessingRun.query.count() == 1
def test_resume_revives_layout_prerequisite_failed_unit_when_layout_ready(app):
"""layout 前置失败的 Unit 在版面变 ready 后必须复活为 pending 并入队续抽。"""
with app.app_context():
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
user, agent, session, intake, document, run, _ = _seed_run_with_plan(suffix='REVIVE-LAYOUT')
unit = run.extraction_plan.units[0]
transition_order_extraction_unit(unit, target_status='routing')
transition_order_extraction_unit(
unit,
target_status='failed',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
error_message='layout prerequisite: layout_missing',
)
document.order_extraction_status = 'failed'
document.order_extraction_error_code = unit.error_code
run.status = 'processing'
run.phase = 'waiting_layout'
layout = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
ShippingDocumentLayoutVersion.version.desc(),
).first()
if layout is None:
layout = ShippingDocumentLayoutVersion(
document_id=document.id,
version=1,
status='ready',
source_content_hash=document.content_hash,
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:test',
parser_name='mineru',
contract_version='shipping_document_table_snapshot.v1',
issues_json=[],
)
db.session.add(layout)
db.session.flush()
layout.status = 'ready'
layout.payload_json = {
'status': 'ready',
'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]},
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [{'text': 'A'}]},
},
}
layout.issues_json = []
document.current_layout_version_id = layout.id
db.session.commit()
revived = revive_layout_prerequisite_failed_units(run)
assert revived == 1
db.session.refresh(unit)
db.session.refresh(document)
assert unit.status == 'pending'
assert unit.error_code is None
assert document.order_extraction_status == 'not_started'
assert resume_runs_waiting_for_layout(document_id=document.id) == 1
db.session.refresh(run)
assert run.current_job_id is not None
assert run.phase in {'queued', 'waiting_layout'}
def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
"""相同内容复用历史布局时,当前 Document 的版本绑定应视为排程成功。"""
with app.app_context():
@@ -246,6 +246,128 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
assert finished['result']['waiting_layout'] is True
def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeypatch):
"""运行时预算耗尽且仍有 pending Unit 时,必须入队续抽,不得终态 partially_completed。"""
import app.jobs.handlers.shipping_order_extraction as handler
events: list[str] = []
finished: dict = {}
run = SimpleNamespace(
id=5, user_id=9, run_no='SNER-WORKER-BUDGET', status='queued', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={
'attachment_selection': {'max_runtime_seconds': 1},
'intakes': [],
},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=5, attempts=1, business_ref=run.run_no, max_attempts=3)
done_unit = SimpleNamespace(
id=51, document_id=201, intake_id=1, status='pending', result_json=None, position=1,
cancellation_requested_at=None,
)
pending_unit = SimpleNamespace(
id=52, document_id=202, intake_id=1, status='pending', result_json=None, position=2,
cancellation_requested_at=None,
)
plan = SimpleNamespace(id=5, unit_count=2, units=[done_unit, pending_unit])
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else done_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [done_unit, pending_unit]),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('budget_progress'))
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [done_unit, pending_unit])
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
)
# 第一轮抽完后假装时间已耗尽,禁止启动第二个 Unit。
clock = {'now': 100.0}
def _perf_counter():
return clock['now']
monkeypatch.setattr(handler.time, 'perf_counter', _perf_counter)
def _process(*, unit, **_kwargs):
events.append(f'processed:{unit.id}')
unit.status = 'merging_supplement'
clock['now'] = 200.0 # 超过 max_runtime_seconds=1
return [{'po_number': 'PO-BUDGET', '_hxops_intake_id': 1}]
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
monkeypatch.setattr(
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: {})
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
monkeypatch.setattr(
handler, '_enqueue_ready_order_extraction_job',
lambda _run, *, message: events.append(f'enqueue:{message}') or 999,
)
def fake_finish(*_args, **kwargs):
events.append('finished')
finished.update(kwargs)
monkeypatch.setattr(handler, 'finish_job', fake_finish)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 5})
assert 'processed:51' in events
assert 'processed:52' not in events
assert any(item.startswith('enqueue:') for item in events)
assert 'terminalized' not in events
assert 'persist_started' not in events
assert run.status == 'processing'
assert run.phase == 'waiting_layout'
assert run.current_job_id == 999
assert finished['result']['budget_stopped'] is True
assert finished['result']['waiting_continue'] is True
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
assert pending_unit.status == 'pending'
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
import app.jobs.handlers.shipping_order_extraction as handler
@@ -1,9 +1,10 @@
"""
tests/test_shipping_order_profile_matcher_replay.py
用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。
依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。
逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。
用途:回放本地库已发布模板样本,验证表头身份观测改动不回归任一 published profile。
依赖:SQLAlchemy / Flask app、match_frozen_coordinate_profiles、profile samples、route decisions。
逻辑:① 历史 unique_match 快照仍命中原 profile;② 每个 published 标注样本在全量候选中自匹配;
③ 生产件 curated 文档重匹配。无 DB 时 skip。
"""
from __future__ import annotations
@@ -26,10 +27,11 @@ _REPLAY_DB_URL = os.environ.get(
os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'),
)
_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20'))
_EXTRA_DOC_IDS = {
int(item.strip())
for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',')
if item.strip().isdigit()
# 生产件回归:document_id → 期望 profile_code
_CURATED_DOC_EXPECTATIONS = {
194: 'ODP-20260824-2C542346805B', # FOX MX / 4210012210
199: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814494_524
197: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814838
}
@@ -52,6 +54,27 @@ def replay_engine() -> Engine:
return create_engine(_REPLAY_DB_URL)
@pytest.fixture(scope='module')
def replay_app(replay_engine: Engine):
"""
绑定回放库的 Flask app,供标注样本 hydrate / published 快照加载。
核心逻辑:强制 DATABASE_URL 指向回放库后 create_app;测试结束弹出覆盖值。
"""
previous = os.environ.get('DATABASE_URL')
os.environ['DATABASE_URL'] = _REPLAY_DB_URL
from app import create_app
app = create_app('development')
try:
yield app
finally:
if previous is None:
os.environ.pop('DATABASE_URL', None)
else:
os.environ['DATABASE_URL'] = previous
def _document_from_snapshot(
snapshot: dict[str, Any],
*,
@@ -95,12 +118,7 @@ def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> lis
def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
"""
拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。
Returns:
含 route/run/unit/document/profile 期望字段的字典列表。
"""
"""拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。"""
query = text("""
SELECT
r.id AS route_id,
@@ -148,11 +166,9 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
rows.append({
'route_id': int(row['route_id']),
'run_id': int(row['run_id']),
'unit_id': int(row['unit_id']),
'document_id': int(row['document_id']),
'expected_profile_code': code,
'expected_profile_version': int(row['selected_profile_version'] or 0),
'expected_profile_checksum': str(row['selected_profile_checksum'] or ''),
'profiles': profiles,
'layout': layout,
})
@@ -160,57 +176,133 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None:
"""历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。"""
"""历史 unique_match 样本回放后仍应命中同一 profile。"""
samples = _load_replay_samples(replay_engine)
if not samples:
pytest.skip('No replayable unique_match snapshots in database')
failures: list[str] = []
summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0})
for sample in samples:
code = sample['expected_profile_code']
result = match_frozen_coordinate_profiles(
profiles=sample['profiles'],
layout=sample['layout'],
profiles=sample['profiles'], layout=sample['layout'],
)
ok = (
result.status == 'unique_match'
and result.profile_code == sample['expected_profile_code']
and result.profile_code == code
and (
not sample['expected_profile_version']
or int(result.version or 0) == int(sample['expected_profile_version'])
)
)
if ok:
summary[code]['pass'] += 1
else:
summary[code]['fail'] += 1
summary[code]['pass' if ok else 'fail'] += 1
if not ok:
failures.append(
f"{code} route={sample['route_id']} run={sample['run_id']} "
f"doc={sample['document_id']}: expected {sample['expected_profile_code']}"
f"/v{sample['expected_profile_version']}, got {result.status}"
f"/{result.profile_code}/v{result.version}"
f"{code} route={sample['route_id']} doc={sample['document_id']}: "
f"got {result.status}/{result.profile_code}"
)
if failures:
lines = [
'Published unique_match replay failures:',
*[f' - {item}' for item in failures[:50]],
'Per-profile summary:',
]
lines = ['unique_match replay failures:', *[f' - {item}' for item in failures[:50]]]
for profile_code, counts in sorted(summary.items()):
lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}')
pytest.fail('\n'.join(lines))
@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS))
def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None:
def test_replay_all_published_annotation_samples_unique_match(replay_app) -> None:
"""
对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。
每个已发布模板的标注样本,在同 Schema 全量 published 候选中须 unique_match 自身。
历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。
覆盖无历史 unique_match 路由的模板(FOX TW / QUANTA / Inventec / WIWYNN CZ 等)。
"""
from app import db
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileSample
from app.core.errors import ValidationError
from app.services.shipping_notice.order_document_profile_service import (
published_snapshots_for_schema,
)
from app.services.shipping_notice.order_document_profile_validation_service import (
_load_sample_layout,
)
with replay_app.app_context():
published = (
ShippingOrderDocumentProfile.query
.filter_by(status='published')
.order_by(ShippingOrderDocumentProfile.profile_code.asc())
.all()
)
if not published:
pytest.skip('No published profiles in replay database')
failures: list[str] = []
missing: list[str] = []
for profile in published:
sample = (
ShippingOrderDocumentProfileSample.query
.filter_by(profile_id=int(profile.id), sample_role='annotation')
.order_by(ShippingOrderDocumentProfileSample.id.asc())
.first()
)
if sample is None:
missing.append(f'{profile.display_name} ({profile.profile_code}): no annotation sample')
continue
try:
layout = _load_sample_layout(sample)
except ValidationError as exc:
missing.append(
f'{profile.display_name} ({profile.profile_code}): layout unavailable ({exc.code})'
)
continue
if not _layout_ready(layout):
from app.models import ShippingOrderDocument
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
ensure_on_demand_coordinate_evidence,
)
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
if document is not None:
layout = ensure_on_demand_coordinate_evidence(
document=document, layout=dict(layout), page_nos=None,
)
if not _layout_ready(layout):
missing.append(
f'{profile.display_name} ({profile.profile_code}): layout evidence incomplete'
)
continue
candidates = published_snapshots_for_schema(int(profile.schema_version_id))
if not candidates:
missing.append(
f'{profile.display_name} ({profile.profile_code}): no published snapshots'
)
continue
result = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
if not (
result.status == 'unique_match'
and result.profile_code == profile.profile_code
and int(result.version or 0) == int(profile.version)
):
failures.append(
f'{profile.display_name} ({profile.profile_code}): '
f'got {result.status}/{result.profile_code}/v{result.version}'
)
if missing or failures:
lines = []
if missing:
lines.append('Missing fixtures / evidence:')
lines.extend(f' - {item}' for item in missing)
if failures:
lines.append('Annotation self-match failures:')
lines.extend(f' - {item}' for item in failures)
pytest.fail('\n'.join(lines))
@pytest.mark.parametrize('document_id,expected_profile_code', sorted(_CURATED_DOC_EXPECTATIONS.items()))
def test_replay_curated_production_documents(
replay_engine: Engine, document_id: int, expected_profile_code: str,
) -> None:
"""生产回归件(FOX MX / INVENTECH TW 等)用最新 Run 快照重匹配须 unique_match。"""
query = text("""
SELECT
run.id AS run_id,
@@ -245,7 +337,4 @@ def test_replay_specific_document_rematch_after_header_band(replay_engine: Engin
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
assert result.status == 'unique_match'
if document_id == 194:
assert result.profile_code == 'ODP-20260824-2C542346805B'
else:
assert result.profile_code
assert result.profile_code == expected_profile_code