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

@@ -7,6 +7,7 @@ backend/app/jobs/handlers/shipping_order_extraction.py
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
@@ -41,6 +42,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
from app.services.shipping_notice.order_extraction_run_service import (
_enqueue_ready_order_extraction_job,
begin_input_freeze,
complete_input_freeze,
mark_order_extraction_persistence_started,
@@ -50,6 +52,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
materialize_order_extraction_run_inputs,
ensure_workflow_items_for_run,
progress_ready_extraction_unit,
revive_layout_prerequisite_failed_units,
schedule_order_extraction_layouts,
synchronize_order_extraction_expansion_snapshot,
transition_order_extraction_run,
@@ -774,6 +777,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
if code == 'layout_pending'
}
ready_document_ids = order_extraction_ready_document_ids(run)
# 版面已就绪时复活此前因 layout 前置失败的 Unit,避免永久 failed。
revive_layout_prerequisite_failed_units(run)
if run.status == 'queued':
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
@@ -1170,6 +1175,50 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
owned_attempt=owned_attempt,
)
return
# [STEP] 运行时预算耗尽且仍有 pending Unit:保留已抽成果,入队续抽,禁止终态 partially_completed。
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(
ShippingOrderProcessingUnit.position.asc(),
).all()
pending_left = any(str(unit.status or '') == 'pending' for unit in units)
if runtime_budget_stopped and pending_left:
record_run_progress(
run=run,
event_code='budget_stopped',
reason_code='budget_runtime_limit',
summary={
**_selection_progress_summary(run),
'max_runtime_seconds': max_runtime_seconds,
'pending_unit_count': sum(
1 for unit in units if str(unit.status or '') == 'pending'
),
'merged_unit_count': len(pending_merge_unit_ids),
},
job_id=job.id,
commit=False,
)
continue_job_id = _enqueue_ready_order_extraction_job(
run, message='运行时预算已用尽,继续识别剩余附件',
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
job.id,
result={
'run_no': run.run_no,
'budget_stopped': True,
'waiting_continue': True,
'handoff_status': 'runtime_budget_continue',
'merged_unit_count': len(pending_merge_unit_ids),
'pending_unit_count': sum(
1 for unit in units if str(unit.status or '') == 'pending'
),
'continue_job_id': int(continue_job_id),
},
message='运行时预算已用尽,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
)
return
orders = persisted_orders + merged_orders
execution = {
'mode': 'deterministic',
@@ -866,10 +866,29 @@ def schedule_layout_version(
return version
def _document_has_active_or_current_layout(document: ShippingOrderDocument) -> bool:
"""
判断文档是否已有进行中或可用的版面,从而本轮不必再占配额新建。
核心逻辑:queued/running 算进行中;current 指向 ready/needs_review 算可用。
历史 unsupported(含预算跳过审计)不算可用,允许后续波次重新排程。
"""
for item in list(getattr(document, 'layout_versions', None) or []):
if str(item.status or '') in {'queued', 'running'}:
return True
current = getattr(document, 'current_layout_version', None)
return current is not None and str(current.status or '') in CURRENT_LAYOUT_STATUSES
def schedule_document_layouts(
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
) -> list[ShippingDocumentLayoutVersion]:
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
"""
在 Document 持久化事务内为支持附件建立独立布局版本。
核心逻辑:只对尚无进行中/可用版面的 PDF 占配额;本轮最多新建 max_documents 个 Job。
超出配额的文档本轮不排程、不写 unsupported 伪终态,留给后续 schedule 调用继续排。
"""
from pathlib import Path
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
@@ -882,30 +901,9 @@ def schedule_document_layouts(
if item.asset_id is not None
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
]
needing = [item for item in eligible if not _document_has_active_or_current_layout(item)]
result: list[ShippingDocumentLayoutVersion] = []
for index, document in enumerate(eligible):
if index >= max_documents:
existing = ShippingDocumentLayoutVersion.query.filter_by(
document_id=int(document.id), source_content_hash=str(document.content_hash or ''),
parser_key=current_layout_parser_key(), status='unsupported',
).first()
if existing is None:
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
document_id=int(document.id),
).scalar() or 0) + 1
existing = ShippingDocumentLayoutVersion(
document_id=int(document.id), version=version_no, status='unsupported',
source_content_hash=str(document.content_hash or ''),
parser_key=current_layout_parser_key(),
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
contract_version=LAYOUT_CONTRACT_VERSION,
issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0,
finished_at=datetime.utcnow(),
)
db.session.add(existing)
db.session.flush()
result.append(existing)
continue
for document in needing[:max_documents]:
version = schedule_layout_version(document, created_by_id=created_by_id)
if version is not None:
result.append(version)
@@ -7,7 +7,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
身份表头按各 table_patterns.header_bbox 对齐到对应表区后只读窗口(正确页码),
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
@@ -1352,7 +1353,7 @@ def _observe_layout_features(
)
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
primary_bbox=primary_bbox, signature=signature,
)
static_text_centers = _observe_static_text_centers(
@@ -1722,53 +1723,71 @@ _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
if not isinstance(bbox, dict):
continue
median = bbox.get('median')
if isinstance(median, list) and len(median) == 4:
try:
return [float(item) for item in median]
except (TypeError, ValueError):
continue
median = _pattern_table_bbox_median(pattern if isinstance(pattern, dict) else None)
if median is not None:
return median
return None
def _align_signature_header_bbox_to_primary(
def _pattern_header_bbox(pattern: dict[str, Any] | None) -> list[float] | None:
"""读取单个 table_pattern 的 header_bbox。"""
if not isinstance(pattern, dict):
return None
value = pattern.get('header_bbox')
if isinstance(value, list) and len(value) == 4:
try:
return [float(item) for item in value]
except (TypeError, ValueError):
return None
return None
def _pattern_table_bbox_median(pattern: dict[str, Any] | None) -> list[float] | None:
"""读取单个 table_pattern.bbox.median。"""
if not isinstance(pattern, dict):
return None
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
if not isinstance(bbox, dict):
return None
median = bbox.get('median')
if isinstance(median, list) and len(median) == 4:
try:
return [float(item) for item in median]
except (TypeError, ValueError):
return None
return None
def _align_header_bbox_to_table(
*,
signature: dict[str, Any] | None,
primary_bbox: list[float],
header_bbox: list[float],
signature_table_y0: float | None,
table_bbox: list[float],
) -> list[float] | None:
"""
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
将签名表头框按目标表顶边做整体 deltaY 对齐并夹在表内。
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
核心逻辑:x/高度保持 header_bbox;deltaY = table.y0 - signature_table.y0。
"""
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
if not isinstance(table_bbox, list) or len(table_bbox) != 4:
return None
header_bbox = _signature_header_bbox(signature)
if header_bbox is None:
if not isinstance(header_bbox, list) or len(header_bbox) != 4:
return None
table_median = _signature_table_bbox_median(signature)
try:
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
py0, py1 = float(table_bbox[1]), float(table_bbox[3])
except (TypeError, ValueError, IndexError):
return None
if hy1 <= hy0 or py1 <= py0:
return None
delta_y = 0.0
if table_median is not None:
if signature_table_y0 is not None:
try:
delta_y = py0 - float(table_median[1])
except (TypeError, ValueError, IndexError):
delta_y = py0 - float(signature_table_y0)
except (TypeError, ValueError):
delta_y = 0.0
aligned_y0 = hy0 + delta_y
aligned_y1 = hy1 + delta_y
# [STEP] 夹在主表内;保持最小可读高度。
height = max(0.02, aligned_y1 - aligned_y0)
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
clipped_y1 = min(clipped_y0 + height, py1)
@@ -1777,51 +1796,106 @@ def _align_signature_header_bbox_to_primary(
return [hx0, clipped_y0, hx1, clipped_y1]
def _observe_primary_table_header(
def _align_signature_header_bbox_to_primary(
*,
glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any],
pages: dict[str, Any],
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
宽带搜索,避免印刷括号注记污染身份原子。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
if not isinstance(glyphs, list):
glyphs = []
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
glyphs.extend(table_glyphs)
page = pages.get('1') or pages.get(1)
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
return [], [], []
aligned = _align_signature_header_bbox_to_primary(
signature=signature, primary_bbox=primary_bbox,
primary_bbox: list[float],
) -> list[float] | None:
"""兼容入口:用签名首个 header_bbox / table median 对齐到主表。"""
header_bbox = _signature_header_bbox(signature)
if header_bbox is None:
return None
table_median = _signature_table_bbox_median(signature)
signature_table_y0 = float(table_median[1]) if table_median is not None else None
return _align_header_bbox_to_table(
header_bbox=header_bbox,
signature_table_y0=signature_table_y0,
table_bbox=primary_bbox,
)
if aligned is not None:
region = {
'x0': float(aligned[0]), 'y0': float(aligned[1]),
'x1': float(aligned[2]), 'y1': float(aligned[3]),
}
else:
region = {
'x0': float(primary_bbox[0]),
'y0': float(primary_bbox[1]),
'x1': float(primary_bbox[2]),
'y1': float(primary_bbox[1]) + max(
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
),
}
def _normalized_layout_tables(
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
) -> list[tuple[list[float], Any, dict[str, Any]]]:
"""将 layout.tables 规范为 (归一化 bbox, page_no, page)。"""
normalized: list[tuple[list[float], Any, dict[str, Any]]] = []
for table in tables:
page_no = table.get('page_no') or 1
page = pages.get(str(page_no)) or pages.get(page_no)
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
if not isinstance(page, dict) or not isinstance(bbox, dict):
continue
try:
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (KeyError, TypeError, ValueError):
continue
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
continue
norm = raw if max(raw) <= 1 else [
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
]
normalized.append((norm, page_no, page))
return normalized
def _best_table_for_pattern_bbox(
*,
pattern_bbox: list[float] | None,
normalized_tables: list[tuple[list[float], Any, dict[str, Any]]],
fallback: list[float] | None,
) -> tuple[list[float], Any, dict[str, Any]] | None:
"""按与 pattern.bbox.median 的 IoU 选运行时表;无重叠时回退 fallback 及其最近页。"""
if pattern_bbox is not None and normalized_tables:
best: tuple[float, list[float], Any, dict[str, Any]] | None = None
for bbox, page_no, page in normalized_tables:
overlap = _bbox_overlap(pattern_bbox, bbox)
if best is None or overlap > best[0]:
best = (overlap, bbox, page_no, page)
if best is not None and best[0] > 0:
return best[1], best[2], best[3]
if fallback is None or len(fallback) != 4 or not normalized_tables:
return None
nearest = max(
normalized_tables,
key=lambda item: _bbox_overlap(fallback, item[0]),
)
return fallback, nearest[1], nearest[2]
def _glyphs_for_page(
*,
page_no: Any,
page_glyphs: dict[str, Any],
glyph_tables: dict[str, Any],
) -> list[dict[str, Any]]:
"""按页取 glyphs;缺页时回退全部 table glyphs。"""
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
if isinstance(glyphs, list) and glyphs:
return glyphs
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
if isinstance(glyphs, list) and glyphs:
return glyphs
merged: list[dict[str, Any]] = []
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
merged.extend(table_glyphs)
return merged
def _observe_header_region(
*,
region: dict[str, float],
page: dict[str, Any],
glyphs: list[dict[str, Any]],
table_bbox: list[float],
merge_wrap: bool,
) -> tuple[list[str], list[float], list[float]]:
"""在指定页的相对区域内读取表头 token/列中心/宽度比。"""
width = float(page.get('width') or 0)
if width <= 0:
if width <= 0 or not glyphs:
return [], [], []
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
spans = [
@@ -1830,11 +1904,11 @@ def _observe_primary_table_header(
][:32]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
table_span = max(float(table_bbox[2]) - float(table_bbox[0]), 0.0001)
band_widths = [
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
]
if _signature_single_logical_header(signature):
if merge_wrap:
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
band_tokens, band_centers, band_widths,
)
@@ -1846,6 +1920,97 @@ def _observe_primary_table_header(
return band_tokens, band_centers, band_widths
def _observe_primary_table_header(
*,
tables: list[dict[str, Any]],
glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any],
pages: dict[str, Any],
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
核心逻辑:对每个带 header_bbox 的 table_pattern,选 IoU 最大的运行时表,按该表
所在页做 deltaY 对齐后只读窗口;多 pattern 的 token 并集对应签名身份并集。无
header_bbox 时才用主表顶 18% 保守带。禁止表顶多行宽带搜索。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
patterns = [
item for item in (signature or {}).get('table_patterns') or []
if isinstance(item, dict) and _pattern_header_bbox(item) is not None
]
normalized_tables = _normalized_layout_tables(tables=tables, pages=pages)
observed_tokens: list[str] = []
observed_centers: list[float] = []
observed_widths: list[float] = []
if patterns:
for pattern in patterns:
header_bbox = _pattern_header_bbox(pattern)
if header_bbox is None:
continue
pattern_median = _pattern_table_bbox_median(pattern)
matched = _best_table_for_pattern_bbox(
pattern_bbox=pattern_median,
normalized_tables=normalized_tables,
fallback=primary_bbox,
)
if matched is None:
continue
table_bbox, page_no, page = matched
aligned = _align_header_bbox_to_table(
header_bbox=header_bbox,
signature_table_y0=(
float(pattern_median[1]) if pattern_median is not None else None
),
table_bbox=table_bbox,
)
if aligned is None:
continue
region = {
'x0': float(aligned[0]), 'y0': float(aligned[1]),
'x1': float(aligned[2]), 'y1': float(aligned[3]),
}
glyphs = _glyphs_for_page(
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
)
tokens, centers, widths = _observe_header_region(
region=region, page=page, glyphs=glyphs, table_bbox=table_bbox,
merge_wrap=int(pattern.get('header_row_count') or 1) <= 1,
)
observed_tokens.extend(tokens)
observed_centers.extend(centers)
observed_widths.extend(widths)
if observed_tokens:
return observed_tokens, observed_centers, observed_widths
# 无签名表头框或 pattern 均未读到:主表顶 18% 保守带(与签名生成兜底一致)。
page_no, page = _page_for_primary_table_bbox(
primary_bbox, tables=tables, pages=pages,
)
if not isinstance(page, dict):
return [], [], []
glyphs = _glyphs_for_page(
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
)
region = {
'x0': float(primary_bbox[0]),
'y0': float(primary_bbox[1]),
'x1': float(primary_bbox[2]),
'y1': float(primary_bbox[1]) + max(
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
),
}
return _observe_header_region(
region=region, page=page, glyphs=glyphs, table_bbox=primary_bbox,
merge_wrap=_signature_single_logical_header(signature),
)
def _merge_following_wrap_candidate(
*,
header: dict[str, Any],
@@ -1165,12 +1165,28 @@ def order_extraction_layout_prerequisite_issues(run: ShippingOrderProcessingRun)
)
version = active_versions[0] if active_versions else document.current_layout_version
if version is None:
issues[int(document.id)] = 'layout_missing'
# 有原件但尚未排到版面(配额延后或历史 budget unsupported 未绑 current):
# 记 pending 等待后续 schedule,禁止当成 layout_missing 永久 failed。
if document.asset_id:
issues[int(document.id)] = 'layout_pending'
else:
issues[int(document.id)] = 'layout_missing'
continue
if str(version.status or '') in {'queued', 'running'}:
issues[int(document.id)] = 'layout_pending'
continue
if str(version.status or '') != 'ready':
issues_list = [
str(item) for item in (version.issues_json or []) if str(item or '').strip()
]
# 历史预算跳过审计:视为延后排程,不进硬失败。
if (
str(version.status or '') == 'unsupported'
and 'mineru_intake_document_budget_exceeded' in issues_list
and bool(document.asset_id)
):
issues[int(document.id)] = 'layout_pending'
continue
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
# PDF 坐标证据可从原始附件按需恢复;压缩导致的 failed/不完整版本不应
# 在正式模板匹配前提前阻断,workflow 会在内存中恢复并继续做确定性匹配。
@@ -1204,11 +1220,48 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
'candidate_ready', 'review_required', 'failed', 'cancelled',
})
_LAYOUT_PREREQUISITE_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED'
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
_ORDER_EXTRACTION_READY_PRIORITY = 10
def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) -> int:
"""
版面已就绪时,将 layout 前置失败的 Unit 重置为 pending 以便重抽。
核心逻辑:仅复活 error_code=LAYOUT_PREREQUISITE_FAILED 且 document 现已 ready 的 Unit;
同步清掉 Document 上对应的 failed 投影,避免首屏仍显示解析失败。
Returns:
复活的 Unit 数量。
"""
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
ready_ids = order_extraction_ready_document_ids(run)
if not ready_ids:
return 0
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
if plan is None:
return 0
revived = 0
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all():
if str(unit.status or '') != 'failed':
continue
if str(unit.error_code or '') != _LAYOUT_PREREQUISITE_FAILED_CODE:
continue
if int(unit.document_id or 0) not in ready_ids:
continue
transition_order_extraction_unit(unit, target_status='pending')
document = db.session.get(ShippingOrderDocument, int(unit.document_id))
if document is not None and str(document.order_extraction_status or '') == 'failed':
document.order_extraction_status = 'not_started'
document.order_extraction_error_code = None
document.order_extraction_error_message = None
revived += 1
return revived
def _enqueue_ready_order_extraction_job(
run: ShippingOrderProcessingRun, *, message: str,
) -> int:
@@ -1265,9 +1318,10 @@ def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun)
"""
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
Unit 未到 candidate_ready/review_required/failed/cancelled)。
核心逻辑:先尝试复活 layout 前置失败 Unit;有 ready PDF 且(尚无 Plan / Plan 为空 →
需要建计划抽取;或存在对应 Unit 未到 candidate_ready/review_required/failed/cancelled)。
"""
revive_layout_prerequisite_failed_units(run)
ready_ids = order_extraction_ready_document_ids(run)
if not ready_ids:
return False
@@ -1334,13 +1388,11 @@ def schedule_order_extraction_layouts(
"""
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
核心逻辑:调用 schedule_document_layouts;配额延后的 PDF 本轮可不排程,返回 True 继续等待;
已有 queued/running/ready 的不重复占用配额。
"""
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
from app.core.errors import ValidationError
documents = _run_layout_documents(run)
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
@@ -1374,7 +1426,7 @@ def schedule_order_extraction_layouts(
for document in documents
if document.current_layout_version_id is not None
}
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
# 配额延后的 PDF 本轮可不排程;保留 pending,禁止当成排程失败抬 ValidationError。
missing = [
document_id for document_id in pdf_document_ids
if (
@@ -1384,11 +1436,7 @@ def schedule_order_extraction_layouts(
)
]
if missing:
raise ValidationError(
'Order PDF layout job was not created',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
details={'document_ids': missing},
)
return True
return order_extraction_layouts_pending(run)
@@ -1460,6 +1508,44 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
)
resumed += 1
continue
# 无版面 pending、无可抽/可复活工作:收口卡住的 waiting_layout,避免永久 processing。
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
units = (
ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
if plan is not None else []
)
if not units or any(
str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES for unit in units
):
continue
deterministic = sum(1 for unit in units if str(unit.status or '') == 'candidate_ready')
failed = sum(1 for unit in units if str(unit.status or '') == 'failed')
review = sum(1 for unit in units if str(unit.status or '') == 'review_required')
if deterministic == 0 and failed > 0 and review == 0:
final_status = 'failed'
elif deterministic == 0 and review > 0 and failed == 0:
final_status = 'review_required'
elif review > 0 or failed > 0 or deterministic < len(units):
final_status = 'partially_completed'
else:
final_status = 'completed'
if run.status == 'queued':
transition_order_extraction_run(run, target_status='processing', phase=final_status)
transition_order_extraction_run(run, target_status=final_status, phase=final_status)
record_run_progress(
run=run,
event_code='run_completed',
summary={
'document_id': int(document_id),
'handoff_status': 'waiting_layout_closed',
'deterministic_unit_count': deterministic,
'failed_unit_count': failed,
'review_required_unit_count': review,
},
commit=False,
)
resumed += 1
if resumed:
db.session.commit()
return resumed
@@ -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
+2 -2
View File
@@ -221,7 +221,7 @@
"candidate_confirmation": "Order candidates are ready — confirm each one",
"technical_failure": "Some attachments failed — retry or view details",
"auto_freeze_blocked": "Auto-freeze did not pass the gate — review the reasons",
"budget_stopped": "Initial parsing budget is exhausted — check remaining attachments"
"budget_stopped": "Initial parsing budget is exhausted — remaining attachments will continue automatically"
},
"reason": {
"profile_not_auto_freeze_approved": "Profile is not approved for auto-freeze",
@@ -306,7 +306,7 @@
"review_required": "This PDF requires manual review.",
"technical_retrying": "Retrying the failed attachment.",
"technical_failed": "The system could not finish this attachment.",
"budget_stopped": "The current attachment budget has been reached. Remaining attachments require manual review.",
"budget_stopped": "The current attachment budget has been reached. Remaining attachments will continue automatically.",
"run_completed": "This order parsing run is complete.",
"generic_processing": "The system is processing the order attachment.",
"cancellation_requested": "Cancellation requested; stopping at a safe point.",
+2 -2
View File
@@ -221,7 +221,7 @@
"candidate_confirmation": "สร้างรายการคำสั่งซื้อแล้ว — ยืนยันทีละรายการ",
"technical_failure": "บางไฟล์แนบล้มเหลว — ลองใหม่หรือดูรายละเอียด",
"auto_freeze_blocked": "การแช่แข็งอัตโนมัติไม่ผ่านเงื่อนไข — ดูสาเหตุ",
"budget_stopped": "งบแยกวิเคราะห์รอบแรกหมดแล้ว — ตรวจไฟล์ที่ยังไม่ประมวลผล"
"budget_stopped": "งบแยกวิเคราะห์รอบแรกหมดแล้ว — ไฟล์ที่เหลือจะถูกแยกวิเคราะห์ต่อโดยอัตโนมัติ"
},
"reason": {
"profile_not_auto_freeze_approved": "เทมเพลตยังไม่ผ่านคุณสมบัติแช่แข็งอัตโนมัติ",
@@ -306,7 +306,7 @@
"review_required": "PDF นี้ต้องตรวจสอบด้วยตนเอง",
"technical_retrying": "ระบบกำลังลองประมวลผลไฟล์แนบที่ล้มเหลวอีกครั้ง",
"technical_failed": "ระบบไม่สามารถประมวลผลไฟล์แนบนี้ได้",
"budget_stopped": "ถึงงบประมาณไฟล์แนบของรอบนี้แล้ว ไฟล์ที่เหลือต้องตรวจสอบด้วยตนเอง",
"budget_stopped": "ถึงงบประมาณไฟล์แนบของรอบนี้แล้ว ไฟล์ที่เหลือจะถูกแยกวิเคราะห์ต่อโดยอัตโนมัติ",
"run_completed": "การแยกวิเคราะห์คำสั่งซื้อรอบนี้เสร็จแล้ว",
"generic_processing": "ระบบกำลังประมวลผลไฟล์แนบคำสั่งซื้อ",
"cancellation_requested": "ได้รับคำขอยกเลิกแล้ว กำลังหยุดอย่างปลอดภัย",
+2 -2
View File
@@ -221,7 +221,7 @@
"candidate_confirmation": "订单候选已生成,请逐份人工确认",
"technical_failure": "部分附件处理失败,可重试或查看详情",
"auto_freeze_blocked": "自动冻结未通过门禁,请查看原因并处理",
"budget_stopped": "首轮识别预算已用尽,请查看未处理附件"
"budget_stopped": "首轮识别预算已用尽,剩余附件将自动继续识别"
},
"reason": {
"profile_not_auto_freeze_approved": "模板未通过自动冻结资格审批",
@@ -340,7 +340,7 @@
"review_required": "该 PDF 需要人工复核。",
"technical_retrying": "系统正在重试失败的附件。",
"technical_failed": "系统未能完成该附件处理。",
"budget_stopped": "已达到当前附件预算,剩余附件等待人工复核。",
"budget_stopped": "已达到当前附件预算,剩余附件将自动继续识别。",
"run_completed": "本次订单解析已完成。",
"cancellation_requested": "已收到取消请求,正在安全停止。",
"cancellation_completed": "取消已完成。",
+2 -2
View File
@@ -221,7 +221,7 @@
"candidate_confirmation": "訂單候選已生成,請逐份人工確認",
"technical_failure": "部分附件處理失敗,可重試或查看詳情",
"auto_freeze_blocked": "自動凍結未通過門禁,請查看原因並處理",
"budget_stopped": "首輪識別預算已用盡,請查看未處理附件"
"budget_stopped": "首輪識別預算已用盡,剩餘附件將自動繼續識別"
},
"reason": {
"profile_not_auto_freeze_approved": "模板未通過自動凍結資格審批",
@@ -306,7 +306,7 @@
"review_required": "該 PDF 需要人工覆核。",
"technical_retrying": "系統正在重試失敗附件。",
"technical_failed": "系統未能完成該附件處理。",
"budget_stopped": "已達目前附件預算,剩餘附件等待人工覆核。",
"budget_stopped": "已達目前附件預算,剩餘附件將自動繼續識別。",
"run_completed": "本次訂單解析已完成。",
"generic_processing": "系統正在處理訂單附件。",
"cancellation_requested": "已收到取消請求,正在安全停止。",