fix(shipping-notice): 同事务完成订单抽取续抽交接
避免 running 仍占唯一索引时 INSERT 后继 Job 触发 UniqueViolation,导致批次卡在接收解析。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
44c3bd0e80
commit
b4c793145e
4 files changed
+179
-32
No files matched your search
@@ -10,7 +10,9 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接;
|
||||
仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout;
|
||||
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
|
||||
两处续抽均 continue_from_running,避免复用即将结束的 running Job;
|
||||
两处续抽须同事务先 finish(commit=False) 再 enqueue(唯一索引含 running,
|
||||
否则会撞 uq_jobs_shipping_order_extraction_active_ref);continue_from_running
|
||||
仅对 queued 去重,避免复用已结束 Job;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
@@ -666,6 +668,62 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
return None
|
||||
|
||||
|
||||
def _handoff_continue_order_extraction(
|
||||
*,
|
||||
job: Job,
|
||||
run: ShippingOrderProcessingRun,
|
||||
owned_attempt: int,
|
||||
result: dict[str, Any],
|
||||
message: str,
|
||||
enqueue_message: str,
|
||||
phase: str,
|
||||
) -> bool:
|
||||
"""
|
||||
同事务自交接:当前 running Job → success,再 INSERT 续抽 queued Job。
|
||||
|
||||
核心逻辑:finish_job(commit=False) 释放
|
||||
uq_jobs_shipping_order_extraction_active_ref 槽位后,再
|
||||
_enqueue_ready_order_extraction_job(continue_from_running=True);
|
||||
写入 continue_job_id / Run.current_job_id 后一次 commit。
|
||||
禁止先 enqueue 再 finish(running 仍占唯一索引会 UniqueViolation)。
|
||||
|
||||
Args:
|
||||
job: 当前 running 的抽取 Job。
|
||||
run: 对应 ProcessingRun。
|
||||
owned_attempt: Worker 领取代次,传给 finish_job 围栏。
|
||||
result: 写入旧 Job.result_json 的业务结果(本函数会补 continue_job_id)。
|
||||
message: 旧 Job 收口说明。
|
||||
enqueue_message: 新 Job 初始 message。
|
||||
phase: 交接后 Run.phase(queued / waiting_layout)。
|
||||
|
||||
Returns:
|
||||
True 表示已成功收口并入队;False 表示 finish 未生效(代次失效),调用方应停止。
|
||||
"""
|
||||
# [STEP 1] 先释放 active 唯一槽,勿在 running 时 INSERT 后继
|
||||
if not finish_job(
|
||||
job.id,
|
||||
result=result,
|
||||
message=message,
|
||||
owned_attempt=owned_attempt,
|
||||
commit=False,
|
||||
):
|
||||
return False
|
||||
# [STEP 2] 同事务入队续抽;仅对 queued 去重,避免复用已 success 的本 Job
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run,
|
||||
message=enqueue_message,
|
||||
continue_from_running=True,
|
||||
)
|
||||
result['continue_job_id'] = int(continue_job_id)
|
||||
run.current_job_id = int(continue_job_id)
|
||||
run.phase = phase
|
||||
finished = db.session.get(Job, int(job.id))
|
||||
if finished is not None:
|
||||
finished.result_json = dict(result)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
@@ -1167,16 +1225,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
has_ready_work = order_extraction_has_extractable_ready_work(run)
|
||||
layouts_pending = order_extraction_layouts_pending(run)
|
||||
if has_ready_work:
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run,
|
||||
message='附件版面已就绪,继续识别剩余附件',
|
||||
continue_from_running=True,
|
||||
)
|
||||
run.current_job_id = continue_job_id
|
||||
run.phase = 'waiting_layout' if layouts_pending else 'queued'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
_handoff_continue_order_extraction(
|
||||
job=job,
|
||||
run=run,
|
||||
owned_attempt=owned_attempt,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': bool(layouts_pending),
|
||||
@@ -1184,10 +1236,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'handoff_status': 'layout_ready_continue',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'ready_document_ids': sorted(ready_document_ids),
|
||||
'continue_job_id': int(continue_job_id),
|
||||
},
|
||||
message='附件版面已就绪,已排队继续识别剩余附件',
|
||||
owned_attempt=owned_attempt,
|
||||
enqueue_message='附件版面已就绪,继续识别剩余附件',
|
||||
phase='waiting_layout' if layouts_pending else 'queued',
|
||||
)
|
||||
return
|
||||
if layouts_pending:
|
||||
@@ -1228,16 +1280,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
)
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run,
|
||||
message='运行时预算已用尽,继续识别剩余附件',
|
||||
continue_from_running=True,
|
||||
)
|
||||
run.current_job_id = continue_job_id
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
_handoff_continue_order_extraction(
|
||||
job=job,
|
||||
run=run,
|
||||
owned_attempt=owned_attempt,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'budget_stopped': True,
|
||||
@@ -1247,10 +1293,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'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,
|
||||
enqueue_message='运行时预算已用尽,继续识别剩余附件',
|
||||
phase='waiting_layout',
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
|
||||
@@ -6,6 +6,7 @@ backend/app/jobs/queue.py
|
||||
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
|
||||
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
|
||||
finish_job(commit=False) 可供与续抽 enqueue 同事务提交;
|
||||
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
|
||||
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
|
||||
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
|
||||
@@ -791,10 +792,22 @@ def finish_job(
|
||||
result: dict[str, Any] | None = None,
|
||||
message: str | None = None,
|
||||
owned_attempt: int | None = None,
|
||||
commit: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
|
||||
|
||||
核心逻辑:status/attempts 条件 UPDATE;commit=False 时不提交,供调用方与
|
||||
续抽 enqueue 等同事务提交(避免 shipping_order_extraction 唯一索引仍被
|
||||
本 Job running 占用时无法 INSERT 后继)。
|
||||
|
||||
Args:
|
||||
job: Job 实例或主键。
|
||||
result: 写入 result_json 的业务结果。
|
||||
message: 收口说明。
|
||||
owned_attempt: 非空时要求 Job.attempts 匹配,防止代次错收口。
|
||||
commit: False 时仅执行 UPDATE,由调用方统一 commit。
|
||||
|
||||
Returns:
|
||||
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
|
||||
"""
|
||||
@@ -819,7 +832,8 @@ def finish_job(
|
||||
)
|
||||
)
|
||||
rowcount = int(db.session.execute(stmt).rowcount or 0)
|
||||
db.session.commit()
|
||||
if commit:
|
||||
db.session.commit()
|
||||
cached = db.session.get(Job, job_id)
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
|
||||
@@ -1273,14 +1273,16 @@ def _enqueue_ready_order_extraction_job(
|
||||
|
||||
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
|
||||
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
|
||||
自交接续抽(预算耗尽 / layout ready)须 continue_from_running=True,仅对 queued
|
||||
去重,避免复用即将结束的 running Job。
|
||||
自交接续抽(预算耗尽 / layout ready)须先 finish(commit=False) 释放
|
||||
running 唯一槽,再以 continue_from_running=True 仅对 queued 去重入队,
|
||||
避免复用即将结束的 running Job,也避免 UniqueViolation。
|
||||
|
||||
Args:
|
||||
run: 订单抽取 Run。
|
||||
message: Job 初始状态说明。
|
||||
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 running
|
||||
Job 出口自交接;False(默认)可复用 queued/running,供 layout 完成回调唤醒。
|
||||
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 Job
|
||||
已同事务标 success 后的自交接;False(默认)可复用 queued/running,
|
||||
供 layout 完成回调唤醒。
|
||||
|
||||
Returns:
|
||||
入队或复用的 Job.id。
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
订单抽取 Worker 单元测试。
|
||||
|
||||
覆盖:物化顺序、partial waiting_layout、layout_ready_continue 自交接、
|
||||
runtime_budget_continue、layout 调度失败收口、以及 continue_from_running 去重。
|
||||
runtime_budget_continue、layout 调度失败收口、continue_from_running 去重、
|
||||
以及同事务 finish→enqueue 避免 UniqueViolation。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.jobs.handlers.shipping_order_extraction import (
|
||||
_expansion_trigger_reason_codes,
|
||||
@@ -354,6 +359,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
@@ -374,7 +380,12 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
assert finished['result']['budget_stopped'] is True
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
|
||||
assert finished['result']['continue_job_id'] == 999
|
||||
assert pending_unit.status == 'pending'
|
||||
# 方案 A:须先 finish(commit=False) 再 enqueue,避免 running 占唯一槽
|
||||
assert events.index('finished') < next(
|
||||
i for i, item in enumerate(events) if item.startswith('enqueue:')
|
||||
)
|
||||
|
||||
|
||||
def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(monkeypatch):
|
||||
@@ -477,6 +488,7 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
@@ -502,6 +514,7 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
|
||||
assert finished['result']['waiting_layout'] is False
|
||||
assert finished['result']['continue_job_id'] == 1006
|
||||
assert stale_pending_unit.status == 'pending'
|
||||
assert events.index('finished') < events.index('enqueue:continue=True')
|
||||
|
||||
|
||||
def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_pending(monkeypatch):
|
||||
@@ -595,7 +608,10 @@ def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_p
|
||||
handler, '_enqueue_ready_order_extraction_job',
|
||||
lambda _run, *, message, continue_from_running=False: 1007,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs))
|
||||
monkeypatch.setattr(
|
||||
handler, 'finish_job',
|
||||
lambda *_a, **kwargs: finished.update(kwargs) or True,
|
||||
)
|
||||
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)
|
||||
@@ -638,6 +654,75 @@ def test_enqueue_ready_order_extraction_job_continue_from_running_dedupes_queued
|
||||
assert captured.get('business_ref') == 'SNER-DEDUP'
|
||||
|
||||
|
||||
def test_order_extraction_handoff_finish_then_enqueue_same_txn(app):
|
||||
"""
|
||||
方案 A:同事务先 finish(commit=False) 再 enqueue,不得撞
|
||||
uq_jobs_shipping_order_extraction_active_ref。
|
||||
|
||||
断言:running 时直接 enqueue 失败;释放槽后同事务 INSERT 成功,旧 Job success。
|
||||
"""
|
||||
with app.app_context():
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.jobs.queue import enqueue, finish_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
run_no = 'SNER-HANDOFF-ATOMIC'
|
||||
running = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
|
||||
status='running',
|
||||
business_ref=run_no,
|
||||
payload_json={'run_no': run_no},
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
started_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(running)
|
||||
db.session.commit()
|
||||
running_id = int(running.id)
|
||||
|
||||
# 对照:仍 running 时直接 INSERT 必须撞唯一索引
|
||||
with pytest.raises(IntegrityError):
|
||||
enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run_no,
|
||||
dedupe_statuses=('queued',),
|
||||
dedupe_active=True,
|
||||
commit=True,
|
||||
)
|
||||
db.session.rollback()
|
||||
|
||||
assert finish_job(
|
||||
running_id,
|
||||
result={'handoff_status': 'runtime_budget_continue'},
|
||||
message='handoff',
|
||||
owned_attempt=1,
|
||||
commit=False,
|
||||
) is True
|
||||
continue_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run_no,
|
||||
dedupe_statuses=('queued',),
|
||||
dedupe_active=True,
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.expire_all()
|
||||
|
||||
old = db.session.get(Job, running_id)
|
||||
nxt = db.session.get(Job, int(continue_id))
|
||||
assert old is not None and old.status == 'success'
|
||||
assert nxt is not None and nxt.status == 'queued'
|
||||
assert nxt.id != running_id
|
||||
assert nxt.business_ref == run_no
|
||||
|
||||
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user