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,
@@ -86,6 +86,20 @@ def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
assert len(orders or []) == 1
def test_approved_pdf_promotes_unique_po_to_header_and_strips_line_copies():
"""唯一 PO 提升到 Header 后,明细行不得残留同 field_id,否则持久化会因 scope 失败。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), _row('PO-1', 'P-2')]},
)
assert reason is None
order = (orders or [])[0]
assert any(item['field_id'] == 'po' for item in order['header_fields'])
for line in order['lines']:
assert not any(item['field_id'] == 'po' for item in line['fields'])
assert {item['field_id'] for item in order['lines'][0]['fields']} == {'part', 'qty'}
def test_approved_pdf_writes_unnumbered_reservation_to_header_and_line_value_to_its_row():
"""同一证据区可同时提供整单默认 Reservation 与指定行覆盖值。"""
orders, reason = _build_approved_profile_order_result(
@@ -2689,6 +2689,12 @@ def test_final_order_extraction_job_failure_marks_queued_run_failed(app):
assert failed_run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
assert event.job_id == job.id
assert intake.order_extraction_status == 'failed'
# 关键断言:附件 Document 必须同步 failed,否则首屏摘要仍投影为「系统处理中」。
document = ShippingOrderDocument.query.filter_by(intake_id=intake.id).filter(
ShippingOrderDocument.document_type != 'email_body',
).one()
assert document.order_extraction_status == 'failed'
assert document.order_extraction_error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
def test_failed_run_retry_reuses_snapshot_and_execution_result(app):
@@ -631,6 +631,110 @@ def test_business_sync_reuses_same_gate_active_attempt(app):
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_inventory_ready_sync_leaves_retry_preparation_attempt_for_outer_complete(app):
"""库存已就绪时,sync 不得提前收口 retry_inventory_preparation Attempt。
回归:OT 自动推进复用 ready 快照后,handler 内 sync 见 has_inventory_lines=True
若提前 complete,外层 execute_queued_attempt 再 complete 会抛
Attempt already finished,Job rollback 后收成 technical_failure_present,
界面卡在获取库存(真实单 OT-20260908-95514841)。
契约:非 poll 的活动准备 Attempt 由外层统一 complete;sync 只返回、不收口。
"""
from app.services.shipping_notice.process_gate_service import (
complete_gate_attempt,
mark_attempt_running,
)
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='invreadyouter')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id=None,
idempotency_key='inv-ready-outer-complete',
input_snapshot={
'action_code': 'retry_inventory_preparation',
'payload': {'trigger': 'gate_attempt_passed'},
},
)
mark_attempt_running(attempt_id=int(attempt.id), worker_id='inv-ready-outer')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
'derived_fulfillment_status': 'inventory_ready',
},
idempotency_key='inv-ready-must-not-early-complete',
)
db.session.refresh(attempt)
assert gate.status == 'running'
assert attempt.status == 'running'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
# [断言] 外层唯一收口可成功;不得再抛 Attempt already finished。
completed = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='passed',
effective_result_json={'findings': [], 'tool_status': 'ok'},
output_snapshot={'action_code': 'retry_inventory_preparation'},
)
assert completed.status == 'passed'
db.session.refresh(attempt)
assert attempt.status == 'succeeded'
def test_inventory_ready_sync_still_completes_auto_poll_attempt(app):
"""poll_inventory_preparation 无外层 complete,sync 在库存就绪时仍须收口。"""
from app.services.shipping_notice.process_gate_service import mark_attempt_running
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='invreadypoll')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id='external-wait-poll',
idempotency_key='inv-ready-poll-complete',
input_snapshot={
'action_code': 'poll_inventory_preparation',
'payload': {'poll': True},
},
)
mark_attempt_running(attempt_id=int(attempt.id), worker_id='inv-ready-poll')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=True,
effective_result_json={
'findings': [],
'has_inventory_lines': True,
},
idempotency_key='inv-ready-poll-must-complete',
)
db.session.refresh(attempt)
assert gate.status == 'passed'
assert attempt.status == 'succeeded'
def test_business_sync_does_not_swallow_passed_when_gate_has_active_user_attempt(app):
"""活动 Attempt 不得吞掉 sync 的 passed 结论。
@@ -396,7 +396,14 @@ def test_failed_run_overrides_stale_unit_review_stage_for_eml_leaf(app) -> None:
assert leaves[0]['user_status'] == 'failed'
assert leaves[0]['user_stage'] == 'document_parsing'
assert leaves[0]['primary_action'] is None
# Run 已失败且无 Case 时必须授权重解析,不能只标失败却无恢复入口。
assert leaves[0]['primary_action'] == {
'code': 'reparse',
'variant': 'primary',
'label_key': 'shipping.actions.reparse',
}
assert leaves[0]['available_actions'] == ['reparse']
assert leaves[0]['run_no'] == run.run_no
def test_eml_leaf_preserves_case_business_action_instead_of_replacing_it_with_navigation(app) -> None:
@@ -1346,19 +1353,28 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
"""首屏摘要必须下发四个文件状态数,避免概览总数与状态数来自不同合同。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
user, _agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-FILE-STATUS-COUNTS',
)
intake.source_type = 'eml'
run, _ = create_order_extraction_run(
user=user,
agent_id=_agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
# 模拟 Unit/Run 失败后 Document 已回写 failed(首屏摘要的权威输入)。
document.order_extraction_status = 'failed'
document.order_extraction_error_code = 'processing_failed'
db.session.commit()
summary = project_conversation_processing_summary(
projection = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)['conversation_processing']['summary']
)['conversation_processing']
summary = projection['summary']
# 关键断言:总文件与四个互斥状态数同源,批次概览不能因缺字段降为全 0。
assert summary['total_files'] == 1
@@ -1366,6 +1382,9 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
assert summary['waiting_human_files'] == 0
assert summary['processing_files'] == 0
assert summary['completed_files'] == 0
failed_leaf = projection['status_groups']['failed'][0]['aggregate_children'][0]
assert failed_leaf['run_no'] == run.run_no
assert failed_leaf['ui_state']['primary_action']['code'] == 'reparse'
def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None: