feat(shipping-notice): 增强发货通知与订单抽取功能,支持多进程处理与紧急停止
- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置 - 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS - 实现发货通知 worker 进程,支持并发处理订单抽取任务 - 引入紧急停止功能,允许管理员在运行中控制订单解析状态 - 更新相关 API,支持读取与设置紧急停止状态 - 增强文档与代码注释,反映新的业务逻辑与功能要求
This commit is contained in:
1 parent
d0fe084999
commit
b352c281d5
149 files changed
+12550
-1874
No files matched your search
@@ -9,6 +9,8 @@ backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from time import perf_counter
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
@@ -134,12 +136,22 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0))
|
||||
if asset is None:
|
||||
raise ValueError('layout document asset is unavailable')
|
||||
total_started = perf_counter()
|
||||
asset_started = perf_counter()
|
||||
content = read_asset_bytes(asset)
|
||||
timings = {
|
||||
'queue_wait_ms': max(round((job.started_at - job.created_at).total_seconds() * 1000), 0)
|
||||
if job.started_at and job.created_at else 0,
|
||||
'asset_read_ms': round((perf_counter() - asset_started) * 1000),
|
||||
}
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=read_asset_bytes(asset),
|
||||
content=content,
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
timings=timings,
|
||||
)
|
||||
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
'snapshot_version': version.contract_version,
|
||||
@@ -156,12 +168,21 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
metadata={'status': str(snapshot.get('status') or 'failed')},
|
||||
)
|
||||
finish_job(
|
||||
job.id, result={'status': str(snapshot.get('status') or 'failed')},
|
||||
job.id, result={
|
||||
'status': str(snapshot.get('status') or 'failed'),
|
||||
'timings': {key: int(value) for key, value in timings.items()},
|
||||
},
|
||||
message='文档版面解析完成', owned_attempt=owned_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
|
||||
|
||||
resume_runs_waiting_for_layout(document_id=int(document.id))
|
||||
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
|
||||
if ctx.logger is not None:
|
||||
ctx.logger.info(
|
||||
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s',
|
||||
job.id, version.id, document.id, timings,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if ctx.logger is not None:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板确定性解析并持久化可复核结果。
|
||||
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行,失败时同步收口 Run;每个 Unit 再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;每个 Unit 按 STP route_decision
|
||||
直通或落 provisional;needs_review 剥离验收标记;不调用 Dify 主链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +13,6 @@ from __future__ import annotations
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -94,6 +94,13 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
'reason_codes': [str(code) for code in item.get('reason_codes') or []],
|
||||
'missing_required_anchor_ids': [str(anchor_id) for anchor_id in item.get('missing_required_anchor_ids') or []],
|
||||
} for item in candidates if isinstance(item, dict)]
|
||||
# 候选列表后附加路由契约摘要(非候选项),供自动冻结策略读取 route_type。
|
||||
route_contract_summary = {
|
||||
'_contract': 'order-extraction-route.v1',
|
||||
'route_type': str(decision.get('route_type') or ''),
|
||||
'route_decision': str(decision.get('route_decision') or ''),
|
||||
'policy_versions': decision.get('policy_versions') if isinstance(decision.get('policy_versions'), dict) else {},
|
||||
}
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=attempt_no,
|
||||
decision=route_result.execution_mode,
|
||||
@@ -110,7 +117,7 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
matched_table_count=int(decision.get('matched_table_count') or 0),
|
||||
parsed_table_count=int(decision.get('parsed_table_count') or 0),
|
||||
approved_table_count=int(decision.get('approved_table_count') or 0),
|
||||
candidate_summary_json=safe_candidates,
|
||||
candidate_summary_json=safe_candidates + [route_contract_summary],
|
||||
fallback_reason_codes_json=[str(code) for code in decision.get('fallback_reason_codes') or []],
|
||||
))
|
||||
append_shipping_audit_event(
|
||||
@@ -126,8 +133,14 @@ def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) ->
|
||||
'matched_table_count': int(decision.get('matched_table_count') or 0),
|
||||
'parsed_table_count': int(decision.get('parsed_table_count') or 0),
|
||||
'match_status': str(decision.get('match_status') or 'no_match'),
|
||||
'route_type': str(decision.get('route_type') or ''),
|
||||
'route_decision': str(decision.get('route_decision') or ''),
|
||||
'reason_codes': [str(code) for code in decision.get('reason_codes') or decision.get('fallback_reason_codes') or []],
|
||||
'policy_versions': decision.get('policy_versions') if isinstance(decision.get('policy_versions'), dict) else {},
|
||||
'generic_completeness': (
|
||||
decision.get('generic_completeness')
|
||||
if isinstance(decision.get('generic_completeness'), dict) else None
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -444,19 +457,69 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
attempt_no=int(unit.attempt_count or 1),
|
||||
route_result=route_result,
|
||||
)
|
||||
if route_result.execution_mode == 'deterministic':
|
||||
stp_route_decision = str(route_result.decision.get('route_decision') or '').strip()
|
||||
decision_payload = route_result.decision if isinstance(route_result.decision, dict) else {}
|
||||
# [STEP] 标准进度事件:评分/通用解析/门禁与 profile_matched 分流,供工作区与审计覆盖。
|
||||
candidate_summary = decision_payload.get('candidate_summary')
|
||||
if isinstance(candidate_summary, list):
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='profile_candidates_scored',
|
||||
summary={
|
||||
'match_status': decision_payload.get('match_status'),
|
||||
'candidate_count': int(decision_payload.get('candidate_count') or len(candidate_summary)),
|
||||
'candidates': candidate_summary[:12],
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
route_type = str(decision_payload.get('route_type') or '').strip()
|
||||
if isinstance(decision_payload.get('generic_completeness'), dict):
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='generic_gate_evaluated',
|
||||
summary={
|
||||
'passed': bool(
|
||||
route_result.execution_mode == 'deterministic'
|
||||
and route_type == 'generic_deterministic'
|
||||
),
|
||||
'route_decision': stp_route_decision,
|
||||
'fallback_reason_codes': list(decision_payload.get('fallback_reason_codes') or []),
|
||||
'generic_completeness': decision_payload.get('generic_completeness'),
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
if route_result.execution_mode == 'deterministic' and route_type == 'generic_deterministic':
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='generic_extraction_completed',
|
||||
summary={
|
||||
'order_count': len(route_result.orders or []),
|
||||
'route_decision': stp_route_decision,
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
elif route_result.execution_mode == 'deterministic':
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='profile_matched',
|
||||
summary={
|
||||
'profile_code': route_result.decision.get('selected_profile_code'),
|
||||
'profile_version': route_result.decision.get('selected_profile_version'),
|
||||
'profile_code': decision_payload.get('selected_profile_code'),
|
||||
'profile_version': decision_payload.get('selected_profile_version'),
|
||||
'route_decision': stp_route_decision,
|
||||
'route_type': route_type or 'profile_deterministic',
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
db.session.commit()
|
||||
if route_result.execution_mode != 'deterministic':
|
||||
# [STEP] 非确定性,或确定性但 STP=needs_review 且无订单 → 人工复核,不进 candidate_ready。
|
||||
# 确定性 + needs_review 且仍有订单时继续落 provisional Candidate,供复核台编辑。
|
||||
if route_result.execution_mode != 'deterministic' or (
|
||||
stp_route_decision == 'needs_review' and not route_result.orders
|
||||
):
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='review_required',
|
||||
error_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0],
|
||||
@@ -464,6 +527,7 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
result={
|
||||
'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or [],
|
||||
'review_details': route_result.decision.get('review_details') or [],
|
||||
'route_decision': stp_route_decision or 'needs_review',
|
||||
},
|
||||
)
|
||||
record_unit_progress(
|
||||
@@ -471,7 +535,10 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
unit=unit,
|
||||
event_code='review_required',
|
||||
reason_code=(route_result.decision.get('fallback_reason_codes') or ['review_required'])[0],
|
||||
summary={'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or []},
|
||||
summary={
|
||||
'fallback_reason_codes': route_result.decision.get('fallback_reason_codes') or [],
|
||||
'route_decision': stp_route_decision or 'needs_review',
|
||||
},
|
||||
job_id=job.id,
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -482,11 +549,20 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
record_unit_progress(run=run, unit=unit, event_code='order_fields_extracted', job_id=job.id)
|
||||
for order in unit_orders:
|
||||
order['_hxops_intake_id'] = int(unit.intake_id)
|
||||
# needs_review 路径再次剥离验收标记(双保险,与 STP 裁决一致)。
|
||||
if stp_route_decision == 'needs_review':
|
||||
order.pop('_hxops_acceptance', None)
|
||||
unit_orders = _json_safe_order_payload(unit_orders)
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='merging_supplement',
|
||||
result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}},
|
||||
result={
|
||||
'orders': unit_orders,
|
||||
'execution': {
|
||||
'mode': 'deterministic',
|
||||
'route_decision': stp_route_decision or 'straight_through',
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return unit_orders
|
||||
|
||||
Reference in new issue
Block a user