Merge branch 'dev' into runny827

This commit is contained in:
runny committed 2026-09-08 18:34:14 +08:00
commit dfa2a43a6b
9 files changed
+287 -25

No files matched your search

@@ -2,8 +2,9 @@
services/shipping_notice/order_extraction_plan.py
用途:把 Run 冻结快照编译为可恢复、可审计的文档级抽取计划。
依赖:ShippingOrderProcessingRun、Plan/Unit ORM、统一校验错误。
逻辑:创建 Run 和 Worker 恢复时复用同一幂等入口;仅附件形成执行单元,正文补充事实不复制正文。
依赖:ShippingOrderProcessingRun、Plan/Unit/Document ORM、统一校验错误。
逻辑:创建 Run 和 Worker 恢复时复用同一幂等入口;仅附件形成执行单元,正文补充事实不复制正文;
Unit 失败时同步 Document.order_extraction_status,供首屏摘要投影失败态。
"""
from __future__ import annotations
@@ -336,6 +337,9 @@ def transition_order_extraction_unit(
"""
单调推进一个附件单元并同步计划汇总状态。
核心逻辑:按 UNIT_TRANSITIONS 校验;failed 时同步 Document.order_extraction_status,
保证首屏摘要不再把失败附件投影为「系统处理中」。
Args:
unit: 已加载且由调用方在事务内持有的计划单元。
target_status: 当前状态允许的下一状态;失败重试必须先回到 pending 再开启新 attempt。
@@ -402,6 +406,18 @@ def transition_order_extraction_unit(
unit.finished_at = now
unit.retry_status = 'failed'
unit.technical_failure_reason_code = unit.error_code
# [STEP] 首屏摘要只读 Document.order_extraction_status,不读 Unit。
# Unit 失败必须同步到 Document,否则会话卡会永久卡在「系统处理中」且无重解析。
try:
document = db.session.get(ShippingOrderDocument, int(unit.document_id))
except RuntimeError:
document = None
if document is not None:
current_doc_status = str(document.order_extraction_status or '').strip().lower()
if current_doc_status not in {'completed', 'partially_completed'}:
document.order_extraction_status = 'failed'
document.order_extraction_error_code = unit.error_code
document.order_extraction_error_message = unit.error_message
elif target_status == 'pending':
unit.finished_at = None
unit.reason_code = None
@@ -11,6 +11,7 @@ backend/app/services/shipping_notice/order_extraction_run_service.py
同会话跨上传批次的完整附件内容指纹相同时,复用活跃或待处理 Workflow Item,避免重复 Workflow;
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进;
Document 物化后立即 ensure WorkflowItem 与 Process Execution,使版面阶段即有 Item 与 Gate;
Run/Unit 失败时同步 Document.order_extraction_status,避免首屏摘要卡在「系统处理中」;
工作区 Run 序列化失败时附带 explainability(责任方/下一步/request_id),禁止只返回技术错误码。
会话多任务(2026-08-03 阶段 1):统一入口 submit_order_extraction 裁决 appended/created;
can_append 仅当 queued + input_lifecycle=open + input_frozen_at 为空;
@@ -4299,6 +4300,13 @@ def transition_order_extraction_run(
intake.order_extraction_status = 'failed'
intake.order_extraction_error_code = run.error_code
intake.order_extraction_error_message = run.error_message
# [STEP] 首屏摘要只读 Document.order_extraction_status。Run 失败时回填
# 尚未终态的附件,避免 Unit 未同步时会话卡永久停在「系统处理中」。
_sync_documents_order_extraction_failed(
intake_ids=intake_ids,
error_code=run.error_code,
error_message=run.error_message,
)
# [BE-01] 新版失败:恢复被替代的旧 Run / Candidate。
_restore_candidates_after_failed_reparse(run, restore_reason='successor_failed')
elif target_status == 'cancelled':
@@ -4308,6 +4316,11 @@ def transition_order_extraction_run(
intake.order_extraction_status = 'failed'
intake.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED'
intake.order_extraction_error_message = 'Order extraction was cancelled'
_sync_documents_order_extraction_failed(
intake_ids=intake_ids,
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED',
error_message='Order extraction was cancelled',
)
# [BE-01] 新版取消同样恢复旧有效版本,避免整任务失去当前结果。
_restore_candidates_after_failed_reparse(run, restore_reason='successor_cancelled')
if target_status in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
@@ -4328,6 +4341,45 @@ def transition_order_extraction_run(
return run
def _sync_documents_order_extraction_failed(
*,
intake_ids: list[int],
error_code: str | None,
error_message: str | None,
) -> None:
"""
将尚未终态的附件 Document 标记为订单抽取失败。
核心逻辑:首屏摘要只读 Document.order_extraction_status;Run/Unit 失败后若
Document 仍停留在 not_started/extracting,会话卡会永久显示「系统处理中」。
已 completed/partially_completed 的附件不覆盖。
Args:
intake_ids: 本 Run 关联的 Intake 主键列表。
error_code: 写入 Document.order_extraction_error_code。
error_message: 写入 Document.order_extraction_error_message。
"""
if not intake_ids:
return
documents = (
db.session.query(ShippingOrderDocument)
.filter(
ShippingOrderDocument.intake_id.in_(tuple(int(item) for item in intake_ids)),
ShippingOrderDocument.document_type != 'email_body',
)
.all()
)
code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')[:64]
message = str(error_message or 'Order extraction failed')[:2000]
for document in documents:
current = str(document.order_extraction_status or '').strip().lower()
if current in {'completed', 'partially_completed'}:
continue
document.order_extraction_status = 'failed'
document.order_extraction_error_code = code
document.order_extraction_error_message = message
def _restore_candidates_after_failed_reparse(
run: ShippingOrderProcessingRun,
*,
@@ -6,6 +6,7 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
order_extraction_route_contract、xfa_profile_*、统一错误类型。
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
"""
@@ -1901,10 +1902,12 @@ def _build_approved_profile_order_result(
Returns:
``(订单, 原因码)``;失败时订单为 None,原因码只表达路由事实。
"""
# [STEP] 与 persist_dynamic_order 对齐:line_no 是系统项次,不进 LLM/模板字段裁决回传。
fields = [
item for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
and item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
and str(item.get('field_code') or '').strip() != 'line_no'
]
by_id = {str(item.get('field_id') or ''): item for item in fields}
po_field_ids = {
@@ -2101,10 +2104,18 @@ def _build_approved_profile_order_result(
if len(distinct_pos) <= 1:
if line_pos:
_value, _group, po_field = line_pos[0]
# [STEP] 唯一 PO 提升到 Header 后,必须从各明细行剥离同 field_id;
# 否则 persist_dynamic_order 会因 header scope 出现在 line 组而报
# Dynamic field identity or scope is invalid。
base_order['header_fields'].append({
'field_id': str(po_field.get('field_id') or ''),
'observations': [po_field.get('observations', [None])[0]],
})
for group in line_groups:
group['fields'] = [
field for field in group.get('fields') or []
if str(field.get('field_id') or '') not in po_field_ids
]
return [base_order], None
return None, 'multiple_po_detected'
@@ -1165,6 +1165,8 @@ def sync_gate_from_business_result(
核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。
已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。
已有活动 Attempt 时:仅 auto poll_inventory_preparation 可提前收口;
其余(含库存就绪的 retry_inventory_preparation)留给外层 Attempt 统一 complete。
Args:
invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。
@@ -1197,25 +1199,21 @@ def sync_gate_from_business_result(
.first()
)
if active_attempt is not None:
# 库存快照已落库时,自动轮询已获得其等待的正式事实。直接复用此 Attempt
# 完成库存准备,避免先终止后重新排队时被自动推进器插入新的轮询。用户主动
# Attempt 绝不在这里完成或覆盖。
# [STEP] 仅 poll_inventory_preparation 可在此提前收口:
# run_inventory_external_wait_poll 无外层 complete,库存就绪时必须由 sync 结束 Attempt。
# retry_inventory_preparation(含自动首投)由 execute_queued_attempt 外层统一 complete;
# 若因 has_inventory_lines 在此提前 passed,外层再 complete 会抛 Attempt already finished,
# Job rollback 后误收成 technical_failure(OT-20260908-95514841)。
snapshot = (
active_attempt.input_snapshot_json
if isinstance(active_attempt.input_snapshot_json, dict)
else {}
)
inventory_ready = bool(
gate_code == 'inventory_preparation'
and passed
and isinstance(effective_result_json, dict)
and effective_result_json.get('has_inventory_lines')
)
is_auto_poll = (
active_attempt.trigger_type == 'auto'
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
)
if (inventory_ready or is_auto_poll) and passed:
if is_auto_poll and passed:
return complete_gate_attempt(
attempt_id=int(active_attempt.id),
outcome='passed',
@@ -16,6 +16,7 @@ services/shipping_notice/shipping_processing_projection.py
同源(project_stage_for_task);**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);
已建 Notice 时填 shipping_notice_no;work_items 构建后由
_conversation_processing_from_work_items 构建正式 conversation_processing;
首屏摘要在订单抽取失败且无 Case 时下发 reparse + 最新 run_no;
不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。
"""
@@ -2502,7 +2503,8 @@ def _eml_aggregate_document_children(
getattr(unit_run, 'status', '') or '',
).strip().lower() == 'failed'
unit_failed = unit_status == 'failed' or unit_run_failed
unit_reparse_authorized = unit_status == 'failed'
# 无 Case 的失败附件(含 Run 已失败但 Unit 仍是陈旧中间态)可授权重解析。
unit_reparse_authorized = unit_failed
failure_reason_code = (
str(
getattr(unit_run, 'error_code', None)
@@ -4187,6 +4189,33 @@ def project_conversation_processing_summary(
for case in current_case_by_document_id.values()
if case.run_id is not None
)
# 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析;
# 仅 load id/run_no,不触碰 Plan/Unit。
latest_run_by_intake_id: dict[int, Any] = {}
if intake_ids:
for intake_id, run_id, run_no in (
db.session.query(
ShippingOrderProcessingRunIntake.intake_id,
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
)
.join(
ShippingOrderProcessingRun,
ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id,
)
.filter(ShippingOrderProcessingRunIntake.intake_id.in_(intake_ids))
.order_by(
ShippingOrderProcessingRunIntake.intake_id.asc(),
ShippingOrderProcessingRun.created_at.desc(),
ShippingOrderProcessingRunIntake.created_at.desc(),
)
.all()
):
key = int(intake_id)
if key in latest_run_by_intake_id:
continue
latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()}
run_ids.add(int(run_id))
runs_by_id = {
int(run.id): run
for run in (
@@ -4287,14 +4316,26 @@ def project_conversation_processing_summary(
available_actions = [gate_action]
primary_action = {'code': gate_action, 'variant': 'primary'}
elif extraction_failed and case is None:
# Intake 解析失败的恢复入口只指向既有 retry API;不猜测 Case/订单入口。
available_actions = ['retry_parse']
primary_action = {
'code': 'retry_parse',
'variant': 'primary',
'label_key': 'shipping.actions.retry_parse',
}
intake_parse_authorized = True
# 订单抽取失败(Document.order_extraction_status=failed)走 Run 重解析;
# 仅 Intake 邮件解析失败、尚无 Processing Run 时才回退 retry_parse。
latest = latest_run_by_intake_id.get(int(document.intake_id))
latest_run_no = str((latest or {}).get('run_no') or '').strip()
if latest_run_no:
available_actions = ['reparse']
primary_action = {
'code': 'reparse',
'variant': 'primary',
'label_key': 'shipping.actions.reparse',
}
intake_parse_authorized = True
else:
available_actions = ['retry_parse']
primary_action = {
'code': 'retry_parse',
'variant': 'primary',
'label_key': 'shipping.actions.retry_parse',
}
intake_parse_authorized = True
elif case is not None and not terminal_case:
if has_current_candidate:
# Case 已绑定可复核 Candidate 后进入订单复核;仅用已批量读取的
@@ -4345,7 +4386,8 @@ def project_conversation_processing_summary(
if task is not None and getattr(task, 'extraction_run_id', None) in runs_by_id
else str(getattr(runs_by_id.get(int(candidate.order_extraction_run_id)), 'run_no', '') or '').strip()
if candidate is not None and getattr(candidate, 'order_extraction_run_id', None) in runs_by_id
else None
else str((latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('run_no') or '').strip()
or None
),
'intake_no': str(getattr(document, 'intake_id', None) or '').strip() or None,
'case_no': str(getattr(case, 'case_no', None) or '').strip() or None,