Files
hugoandCursor b4c793145e fix(shipping-notice): 同事务完成订单抽取续抽交接
避免 running 仍占唯一索引时 INSERT 后继 Job 触发 UniqueViolation,导致批次卡在接收解析。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 11:29:27 +08:00

1108 lines
40 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/jobs/queue.py
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层;
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。
"""
from __future__ import annotations
import socket
from datetime import datetime, timedelta
from collections.abc import Callable, Sequence
from typing import Any
from flask import current_app
from sqlalchemy import update
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import Session
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.jobs.types import JobType
from app.models import Job
ACTIVE_STATUSES = ("queued", "running")
QUEUED_ONLY_STATUSES = ("queued",)
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
# 与 models.Job.uq_jobs_shipping_parse_queued_ref 对齐
_PARSE_QUEUED_UNIQUE_TYPE = JobType.SHIPPING_NOTICE_PARSE.value
def _orm_session() -> Session:
"""
取得底层 Session。
scoped_session 代理不转发 in_transaction/get_transaction,须解包后使用。
"""
return db.session()
def _is_retryable_exc(exc: BaseException) -> bool:
"""按异常类型分级判断任务失败是否可重试(通用裁定,不区分业务域)。
业务 NotFound / AppError.retryable=False(含 ValidationError)视为不可再排队;
仅瞬时基础设施异常(503 ServiceUnavailable 或未归类异常)才允许重试。
"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
def _ensure_outer_dbapi_transaction(session: Session) -> None:
"""
确保 begin_nested() 不会成为数据库最外层事务。
核心逻辑:SQLite 在尚未 BEGIN 时执行 SAVEPOINT,随后 RELEASE 等价于 COMMIT,
会破坏 commit=False / 外层 rollback。先 materialize 连接事务;SQLite 必要时
显式 DBAPI BEGIN(已在事务中则忽略)。
"""
if not session.in_transaction():
session.begin()
bind = session.connection()
if str(bind.dialect.name or "") != "sqlite":
return
dbapi_conn = bind.connection.dbapi_connection
in_txn = getattr(dbapi_conn, "in_transaction", None)
if callable(in_txn) and in_txn():
return
try:
dbapi_conn.execute("BEGIN")
except Exception:
# 已在事务中:sqlite 会报错,可安全忽略
pass
def _normalize_job_type(job_type: JobType | str) -> str:
"""把 JobType 或字符串统一成数据库保存值。"""
return str(getattr(job_type, "value", job_type) or "").strip()
def _subject_to_parse_queued_unique(job_type: str | None) -> bool:
"""是否受 shipping_notice_parse queued 部分唯一索引约束。"""
return str(job_type or "").strip() == _PARSE_QUEUED_UNIQUE_TYPE
def _lock_other_active_parse_job(
*,
domain: str,
job_type: str,
business_ref: str | None,
exclude_id: int,
) -> Job | None:
"""
FOR UPDATE 锁定同业务锚点下优先级最高的 queued/running 预解析 Job。
核心逻辑:queued 受部分唯一索引保护且天然可安全替代,因此必须优先于
running;仅无 queued 时才按最小 id 选择 running,并交由
`_is_safe_supersede_target` 校验精确 Intake lease。持锁期间 Worker 的
claim(SKIP LOCKED)会跳过最终候选。
Args:
domain / job_type / business_ref: 与待降级 Job 相同的锚点。
exclude_id: 排除自身主键。
Returns:
锁定的最高优先级同伴;没有则 None。
"""
ref = str(business_ref or "").strip() or None
if not ref:
return None
return (
db.session.query(Job)
.filter(
Job.domain == str(domain),
Job.job_type == str(job_type),
Job.business_ref == ref,
Job.status.in_(("queued", "running")),
Job.id != int(exclude_id),
)
.order_by((Job.status == "queued").desc(), Job.id.asc())
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
def _parse_lease_for_job(job: Job) -> str:
"""构造 `{job_id}:{attempts}` 执行代次 lease。"""
return f"{int(job.id)}:{int(job.attempts or 0)}"
def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
"""
判定锁定的同伴是否可安全取代旧 running Job。
核心逻辑:
- queued:可 supersede(旧取消,Intake 回到排队挂 keep);
- running:仅当 Intake 已明确持有该 Job 的精确 parse_job_id + parse_lease
(Worker 已真正 claim Intake)。否则可能 Worker 已按旧 id 决定 skip+finish,
若此时伪造 lease 会导致 Intake 永久 parsing。
Returns:
True 表示可取消旧 Job 并重指;False 表示应让旧 Job 正常 requeue。
"""
db.session.refresh(sibling)
status = str(sibling.status or "")
if status == "queued":
return True
if status != "running":
return False
from app.models import ShippingOrderIntake
intake_no = str(
(cancelled_job.payload_json or {}).get("intake_no")
or cancelled_job.business_ref
or sibling.business_ref
or ""
).strip().upper()
if not intake_no:
return False
locked = (
db.session.query(ShippingOrderIntake)
.filter(ShippingOrderIntake.intake_no == intake_no)
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
if locked is None:
return False
expected_lease = _parse_lease_for_job(sibling)
return (
str(locked.parse_status or "") == "parsing"
and locked.parse_job_id is not None
and int(locked.parse_job_id) == int(sibling.id)
and str(locked.parse_lease or "") == expected_lease
)
def _resolve_safe_supersede_sibling(
*,
domain: str,
job_type: str,
business_ref: str | None,
exclude_id: int,
cancelled_job: Job,
) -> Job | None:
"""
锁定同伴并过滤为可安全 supersede 的目标;不安全则视为无替代者。
"""
sibling = _lock_other_active_parse_job(
domain=domain,
job_type=job_type,
business_ref=business_ref,
exclude_id=exclude_id,
)
if sibling is None:
return None
if not _is_safe_supersede_target(sibling, cancelled_job=cancelled_job):
return None
return sibling
def _retarget_intake_parse_job_after_supersede(
*,
cancelled_job: Job,
keep_job: Job,
) -> None:
"""
旧 running 预解析 Job 被安全同伴取代时,同事务重指 Intake.parse_job_id。
核心逻辑:FOR UPDATE Intake 后复检 keep_job.status——
keep 仍为 queued:parsing→queued 并清 parse_lease;
keep 已 running:仅在 Intake 已持有其精确 lease 时保留状态,绝不伪造 lease
(否则会踩到已决定 skip+finish 的 Worker,造成永久 parsing)。
"""
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
return
from app.models import ShippingOrderIntake
intake_no = str(
(cancelled_job.payload_json or {}).get("intake_no")
or cancelled_job.business_ref
or ""
).strip().upper()
if not intake_no:
return
# 锁内复检同伴状态(调用方应已 FOR UPDATE keep_job)
db.session.refresh(keep_job)
keep_status = str(keep_job.status or "")
if keep_status not in {"queued", "running"}:
return
locked = (
db.session.query(ShippingOrderIntake)
.filter(ShippingOrderIntake.intake_no == intake_no)
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
if locked is None:
return
current_job_id = int(locked.parse_job_id) if locked.parse_job_id is not None else None
cancelled_id = int(cancelled_job.id)
keep_id = int(keep_job.id)
# 已指向第三方 Job:不抢占
if current_job_id is not None and current_job_id not in {cancelled_id, keep_id}:
return
now = datetime.utcnow()
current_lease = str(locked.parse_lease or "") or None
status_now = str(locked.parse_status or "")
if keep_status == "queued":
if current_job_id in {cancelled_id, None}:
locked.parse_job_id = keep_id
# 仅当仍挂旧 Job/旧代次时才打回 queued,避免清掉 keep 新 Worker 的 lease
if status_now == "parsing" and (
current_job_id == cancelled_id
or current_lease is None
or str(current_lease).startswith(f"{cancelled_id}:")
):
locked.parse_status = "queued"
locked.parse_lease = None
locked.updated_at = now
return
# keep 已 running:只保留已真正接管的状态,禁止伪造 lease 转移
keep_lease = _parse_lease_for_job(keep_job)
if (
status_now == "parsing"
and current_job_id == keep_id
and current_lease == keep_lease
):
locked.updated_at = now
return
# 未真正接管:调用方本不应 supersede;此处 no-op 防误伤
return
def _cancel_running_job_superseded(
*,
job_id: int,
now: datetime,
message: str,
owned_attempt: int | None = None,
snap_attempts: int | None = None,
) -> int:
"""
将仍为 running 的 Job 标为 cancelled(已被新 queued 取代)。
Returns:
条件 UPDATE 影响行数。
"""
where = [Job.id == int(job_id), Job.status == "running"]
if owned_attempt is not None:
where.append(Job.attempts == int(owned_attempt))
elif snap_attempts is not None:
where.append(Job.attempts == int(snap_attempts))
stmt = (
update(Job)
.where(*where)
.values(
status="cancelled",
progress=100,
message=str(message or "已被新的 queued Job 取代")[:500],
locked_by=None,
locked_at=None,
started_at=None,
finished_at=now,
updated_at=now,
)
)
return int(db.session.execute(stmt).rowcount or 0)
def _worker_id() -> str:
"""生成当前 worker 标识,用于锁记录和排障。"""
try:
host = socket.gethostname()
except Exception:
host = "unknown-host"
return f"{host}:{id(db.session)}"
def _find_shipping_notice_job_id(task_no: str) -> int | None:
"""
按 task_no 查找发货任务对应的 KbJob。
Args:
task_no: 发货任务号;由 AI 或业务代码传入时可大小写混用。
Returns:
匹配到的最新 KbJob 主键;未找到返回 None。
"""
from app import db
from app.models import KbJob
normalized_task_no = str(task_no or '').strip().upper()
candidates = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status.in_(('queued', 'running', 'success', 'failed')),
)
.order_by(KbJob.id.desc())
.limit(50)
.all()
)
for job in candidates:
payload_json = job.payload_json or {}
if str(payload_json.get('task_no') or '').strip().upper() == normalized_task_no:
return job.id
return None
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
"""
兼容旧知识库后台任务入队入口。
Args:
job_id: KbJob 主键;由清洗、路径上传、Dify 同步等知识库流程传入。
Returns:
(是否接受入队, 队列状态说明)。
"""
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job as _enqueue_kb_job
return _enqueue_kb_job(job_id)
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
"""
兼容旧清洗任务入队入口。
Args:
job_id: clean 类型 KbJob 主键。
Returns:
(是否接受入队, 队列状态说明)。
"""
return enqueue_kb_job(job_id)
def enqueue(
job_type: JobType | str,
payload: dict[str, Any],
*,
domain: str = "default",
business_ref: str | None = None,
created_by_id: int | None = None,
priority: int = 0,
max_attempts: int = 3,
message: str | None = None,
dedupe_active: bool = True,
dedupe_statuses: Sequence[str] | None = None,
commit: bool = True,
correlation_id: str | None = None,
scheduled_at: Any = None,
task_id: int | None = None,
execution_id: int | None = None,
gate_id: int | None = None,
candidate_set_id: int | None = None,
fencing_token: str | None = None,
) -> int:
"""
将任务写入通用 jobs 队列并返回 job id。
核心逻辑:先按 domain/type/business_ref + dedupe_statuses 查复用;
无则 SAVEPOINT 插入。撞上 shipping_notice_parse 的 queued 部分唯一索引时
IntegrityError 回读已有 Job(并发双插幂等)。commit=False 时不开自动提交,
由调用方与业务行同事务提交。
Args:
job_type: 任务类型。
payload: JSON payload。
domain: 业务域,如 shipping_notice。
business_ref: 业务幂等锚点,如发货任务号。
created_by_id: 创建人。
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
dedupe_active: 是否复用同业务键下指定状态中的任务。
dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。
重试场景应传仅 queued,避免复用即将结束的 running Job。
commit: False 时仅 flush,由调用方与业务行同一事务提交。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
task_id / execution_id / gate_id / candidate_set_id: 正式业务作用域;AutoProgress
使用这些列实施 Task 级活动唯一与版本围栏。
fencing_token: Worker 领取前写入的代次围栏;迟到副作用必须比对。
"""
normalized_type = _normalize_job_type(job_type)
if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}:
raw_job_id = (payload or {}).get("job_id") if isinstance(payload, dict) else None
if not raw_job_id:
raise ValidationError("job_id is required")
ok, message_text = enqueue_kb_job(int(raw_job_id))
if not ok:
raise ValidationError(message_text or "enqueue kb job failed")
return int(raw_job_id)
normalized_domain = str(domain or "").strip() or "default"
normalized_ref = str(business_ref or correlation_id or "").strip() or None
if not normalized_type:
raise ValueError("job_type is required")
if not isinstance(payload, dict):
raise ValueError("payload must be a dict")
statuses = tuple(dedupe_statuses) if dedupe_statuses is not None else ACTIVE_STATUSES
def _find_active_dedupe_job() -> Job | None:
if not (dedupe_active and normalized_ref and statuses):
return None
return (
db.session.query(Job)
.filter(
Job.domain == normalized_domain,
Job.job_type == normalized_type,
Job.business_ref == normalized_ref,
Job.status.in_(statuses),
)
.order_by(Job.created_at.desc(), Job.id.desc())
.first()
)
existing = _find_active_dedupe_job()
if existing is not None:
return int(existing.id)
now = datetime.utcnow()
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
job = Job(
domain=normalized_domain,
job_type=normalized_type,
status="queued",
priority=int(priority or 0),
business_ref=normalized_ref,
payload_json=payload,
progress=0,
message=message or "等待后台处理",
attempts=0,
max_attempts=max(1, int(max_attempts or 1)),
created_by_id=created_by_id,
task_id=task_id,
execution_id=execution_id,
gate_id=gate_id,
candidate_set_id=candidate_set_id,
fencing_token=fencing_token,
created_at=queue_at,
updated_at=now,
)
# [STEP] SAVEPOINT 边界:仅在 begin_nested 内 add+flush。
# begin_nested 会先 autoflush pending;若 Job 提前进入 Session,冲突会落在 SAVEPOINT 之外,
# 毒化外层事务并在异常分支触发 PendingRollbackError。
session = _orm_session()
_ensure_outer_dbapi_transaction(session)
try:
with session.begin_nested():
session.add(job)
session.flush()
except IntegrityError:
# SAVEPOINT 已回滚;确保失败对象不残留为 pending
try:
session.expunge(job)
except Exception:
pass
# 即使 dedupe_active=False,唯一冲突仍须回落已有 queued(索引层幂等)
raced = _find_active_dedupe_job()
if raced is None and normalized_ref:
raced = (
db.session.query(Job)
.filter(
Job.domain == normalized_domain,
Job.job_type == normalized_type,
Job.business_ref == normalized_ref,
Job.status == "queued",
)
.order_by(Job.id.asc())
.first()
)
if raced is not None:
return int(raced.id)
raise
if commit:
session.commit()
return int(job.id)
def _job_id(job: Job | int) -> int:
"""统一解析 Job 主键。"""
return int(job if isinstance(job, int) else job.id)
def recover_stale_jobs(
*,
domain: str,
timeout_seconds: float,
job_type: str | JobType | None = None,
on_recovered: Callable[[Job], None] | None = None,
) -> int:
"""
回收指定业务域内超时 running 的通用任务。
核心逻辑:FOR UPDATE SKIP LOCKED 领取待回收行,再以
status=running AND attempts=快照 条件 UPDATE;同事务回调 on_recovered。
多 Worker 并发回收时不会双写同一 Job,也不会把已被新 Worker 领取的代次打回 queued。
若已存在同锚点 queued 同伴(parse 唯一索引),旧 Job 标 cancelled 并重指 Intake,
每条更新包在 SAVEPOINT 内,避免单行 IntegrityError 毒化整批回收。
Args:
on_recovered: 每条 Job 条件更新成功后、统一 commit 前的回调。
"""
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
query = db.session.query(Job).filter(
Job.domain == domain,
Job.status == "running",
Job.started_at.isnot(None),
Job.started_at < cutoff,
)
normalized_type = _normalize_job_type(job_type) if job_type else ""
if normalized_type:
query = query.filter(Job.job_type == normalized_type)
try:
stale_jobs = (
query.order_by(Job.started_at.asc(), Job.id.asc())
.with_for_update(skip_locked=True)
.all()
)
except OperationalError:
db.session.rollback()
raise
if not stale_jobs:
db.session.rollback()
return 0
session = _orm_session()
_ensure_outer_dbapi_transaction(session)
now = datetime.utcnow()
recovered = 0
for job in stale_jobs:
# 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running)
if str(job.status or "") != "running":
continue
if job.started_at is None or job.started_at >= cutoff:
continue
snap_attempts = int(job.attempts or 0)
max_attempts = int(job.max_attempts or 1)
job_id = int(job.id)
sibling: Job | None = None
rowcount = 0
if snap_attempts < max_attempts:
if _subject_to_parse_queued_unique(str(job.job_type or "")):
try:
sibling = _resolve_safe_supersede_sibling(
domain=str(job.domain),
job_type=str(job.job_type),
business_ref=job.business_ref,
exclude_id=job_id,
cancelled_job=job,
)
except OperationalError:
# 死锁会使整个事务失败;回滚后由下一轮回收重试
db.session.rollback()
return 0
# [STEP] SAVEPOINT:queued 唯一冲突不得毁掉整批外层事务
try:
with session.begin_nested():
if sibling is not None:
rowcount = _cancel_running_job_superseded(
job_id=job_id,
now=now,
message="超时回收:已存在安全替代解析 Job,旧 Job 已取消",
snap_attempts=snap_attempts,
)
else:
result = db.session.execute(
update(Job)
.where(
Job.id == job_id,
Job.status == "running",
Job.attempts == snap_attempts,
)
.values(
status="queued",
message="任务执行超时,已停止,等待用户选择下一步动作",
locked_by=None,
locked_at=None,
started_at=None,
updated_at=now,
)
)
rowcount = int(result.rowcount or 0)
except IntegrityError:
try:
sibling = _resolve_safe_supersede_sibling(
domain=str(job.domain),
job_type=str(job.job_type),
business_ref=job.business_ref,
exclude_id=job_id,
cancelled_job=job,
)
except OperationalError:
db.session.rollback()
return 0
if sibling is None:
continue
with session.begin_nested():
rowcount = _cancel_running_job_superseded(
job_id=job_id,
now=now,
message="超时回收:queued 唯一冲突,旧 Job 已取消",
snap_attempts=snap_attempts,
)
else:
timeout_msg = f"任务执行超时(超过 {int(timeout_seconds)}s)"
result = db.session.execute(
update(Job)
.where(
Job.id == job_id,
Job.status == "running",
Job.attempts == snap_attempts,
)
.values(
status="failed",
error_message=timeout_msg,
message=timeout_msg,
progress=100,
locked_by=None,
locked_at=None,
finished_at=now,
updated_at=now,
)
)
rowcount = int(result.rowcount or 0)
if rowcount != 1:
continue
db.session.expire(job)
db.session.refresh(job)
if str(job.status or "") == "cancelled" and sibling is not None:
_retarget_intake_parse_job_after_supersede(
cancelled_job=job,
keep_job=sibling,
)
if on_recovered is not None:
on_recovered(job)
current_app.logger.warning(
"合同任务超时回收 job_id=%s job_type=%s status=%s attempts=%s/%s timeout_seconds=%s message=%s",
job.id, job.job_type, job.status, snap_attempts, max_attempts, int(timeout_seconds), job.message,
)
recovered += 1
db.session.commit()
if recovered:
current_app.logger.warning("合同任务超时回收完成 domain=%s recovered=%d", domain, recovered)
return recovered
def claim_next_job(*, domain: str | None, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
"""
原子领取指定业务域下一条 queued 任务。
核心逻辑:有 domain 时按业务域隔离;传入 None 时只按 job_types 领取,
供共享的合同 worker 消费合同审查与合同付款预警子域。
Args:
domain: 业务域;None 表示不按域过滤。
job_types: 可领取的任务类型。
worker_id: 可选 worker 标识,用于领取审计。
Returns:
已置为 running 的任务;无可领取任务时返回 None。
"""
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
now = datetime.utcnow()
try:
query = db.session.query(Job).filter(Job.status == "queued", Job.created_at <= now)
if domain is not None:
query = query.filter(Job.domain == str(domain))
if normalized_types:
query = query.filter(Job.job_type.in_(normalized_types))
job = (
query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc())
.with_for_update(skip_locked=True)
.first()
)
except OperationalError:
db.session.rollback()
raise
if not job:
db.session.rollback()
return None
job.status = "running"
# 每次领取刷新 started_at,避免 fail_job requeue 残留旧时间导致立刻被超时回收
job.started_at = now
job.locked_at = now
job.locked_by = worker_id or _worker_id()
job.attempts = int(job.attempts or 0) + 1
job.progress = max(int(job.progress or 0), 1)
job.message = "worker 已领取任务"
job.updated_at = now
db.session.commit()
return job
def _sync_parse_intake_after_job_mutation(job_id: int) -> None:
"""
shipping_notice_parse Job 状态变更后同步 Intake(同事务、commit 前)。
核心逻辑:委托 sync_intake_after_parse_job_recovery,覆盖 requeue→queued、
failed→parse_failed、cancelled→安全重指/终态清理,避免 Intake 永久 parsing。
"""
job = db.session.get(Job, int(job_id))
if job is None or not _subject_to_parse_queued_unique(str(job.job_type or "")):
return
db.session.expire(job)
db.session.refresh(job)
from app.services.shipping_notice.intake_parse_workflow import (
sync_intake_after_parse_job_recovery,
)
sync_intake_after_parse_job_recovery(job)
def _sync_shipping_order_extraction_run_after_job_failure(job_id: int) -> None:
"""将最终失败的订单抽取 Job 收口到对应 Run,避免用户界面永久轮询。"""
job = db.session.get(Job, int(job_id))
if job is None or str(job.job_type or '') != JobType.SHIPPING_ORDER_EXTRACTION.value:
return
db.session.expire(job)
db.session.refresh(job)
if str(job.status or '') != 'failed':
return
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_failure,
)
sync_order_extraction_run_after_job_failure(job)
def finish_job(
job: Job | int,
*,
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)。
"""
now = datetime.utcnow()
job_id = _job_id(job)
where = [Job.id == job_id, Job.status == "running"]
if owned_attempt is not None:
where.append(Job.attempts == int(owned_attempt))
stmt = (
update(Job)
.where(*where)
.values(
status="success",
progress=100,
result_json=result or {},
message=message or "任务处理完成",
error_message=None,
locked_by=None,
locked_at=None,
finished_at=now,
updated_at=now,
)
)
rowcount = int(db.session.execute(stmt).rowcount or 0)
if commit:
db.session.commit()
cached = db.session.get(Job, job_id)
if cached is not None:
db.session.expire(cached)
return rowcount == 1
def fail_job(
job: Job | int,
*,
error: str,
result: dict[str, Any] | None = None,
retryable: bool = False,
owned_attempt: int | None = None,
) -> bool:
"""
条件收口失败:仅 running(且可选 attempts 匹配)时改 queued/failed/cancelled。
核心逻辑:retryable 且 attempts 未耗尽时,优先安全 supersede,否则 requeue
(清空 started_at)并同步 Intake;唯一冲突窗口消失时保持 running 返回 False,
禁止误标 failed。attempts 耗尽则 failed 并同步 Intake 离开 parsing。
Returns:
是否实际更新到一行。
"""
now = datetime.utcnow()
job_id = _job_id(job)
error_text = str(error or "job failed")[:1000]
payload = result or {}
base_where = [Job.id == job_id, Job.status == "running"]
if owned_attempt is not None:
base_where.append(Job.attempts == int(owned_attempt))
session = _orm_session()
_ensure_outer_dbapi_transaction(session)
def _expire_cached() -> None:
cached = db.session.get(Job, job_id)
if cached is not None:
db.session.expire(cached)
if retryable:
# 先锁住自身 running 行,再锁同伴,缩短无锁窗口且便于复检 attempts
job_row = (
db.session.query(Job)
.filter(Job.id == job_id, Job.status == "running")
.execution_options(populate_existing=True)
.with_for_update()
.first()
)
sibling: Job | None = None
if job_row is not None and _subject_to_parse_queued_unique(str(job_row.job_type or "")):
try:
sibling = _resolve_safe_supersede_sibling(
domain=str(job_row.domain),
job_type=str(job_row.job_type),
business_ref=job_row.business_ref,
exclude_id=job_id,
cancelled_job=job_row,
)
except OperationalError:
db.session.rollback()
return False
attempts_ok = (
job_row is not None
and int(job_row.attempts or 0) < int(job_row.max_attempts or 1)
)
if sibling is not None and attempts_ok:
# 仅安全替代者:取消旧 Job(running 且已真正接管 Intake,或仍为 queued)
rowcount = _cancel_running_job_superseded(
job_id=job_id,
now=now,
message="失败重试:已存在安全替代解析 Job,旧 Job 已取消",
owned_attempt=owned_attempt,
)
if rowcount == 1:
cancelled = db.session.get(Job, job_id)
if cancelled is not None:
_retarget_intake_parse_job_after_supersede(
cancelled_job=cancelled,
keep_job=sibling,
)
_sync_parse_intake_after_job_mutation(job_id)
db.session.commit()
_expire_cached()
return True
elif sibling is None and attempts_ok:
# 无安全替代(含:同伴 running 但尚未 claim Intake)→ 正常 requeue
requeue_stmt = (
update(Job)
.where(*base_where, Job.attempts < Job.max_attempts)
.values(
status="queued",
progress=0,
result_json=payload,
error_message=error_text,
message="任务失败,等待重试",
locked_by=None,
locked_at=None,
started_at=None,
finished_at=None,
updated_at=now,
)
)
try:
with session.begin_nested():
rowcount = int(db.session.execute(requeue_stmt).rowcount or 0)
except IntegrityError:
try:
sibling = (
_resolve_safe_supersede_sibling(
domain=str(job_row.domain),
job_type=str(job_row.job_type),
business_ref=job_row.business_ref,
exclude_id=job_id,
cancelled_job=job_row,
)
if job_row is not None
else None
)
except OperationalError:
db.session.rollback()
return False
if sibling is None:
# 唯一冲突窗口已消失:保持 running,勿强行 failed 造成永久 parsing
db.session.rollback()
return False
with session.begin_nested():
rowcount = _cancel_running_job_superseded(
job_id=job_id,
now=now,
message="失败重试:queued 唯一冲突,旧 Job 已取消",
owned_attempt=owned_attempt,
)
if rowcount == 1:
cancelled = db.session.get(Job, job_id)
if cancelled is not None:
_retarget_intake_parse_job_after_supersede(
cancelled_job=cancelled,
keep_job=sibling,
)
_sync_parse_intake_after_job_mutation(job_id)
db.session.commit()
_expire_cached()
return True
else:
if rowcount == 1:
_sync_parse_intake_after_job_mutation(job_id)
db.session.commit()
_expire_cached()
return True
# 终态 failed:同步 Intake 离开 parsing,避免永久卡住
fail_stmt = (
update(Job)
.where(*base_where)
.values(
status="failed",
progress=100,
result_json=payload,
error_message=error_text,
message=error_text,
locked_by=None,
locked_at=None,
started_at=None,
finished_at=now,
updated_at=now,
)
)
rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
if rowcount == 1:
_sync_parse_intake_after_job_mutation(job_id)
# 订单抽取的用户态以 Run 为准;Job 耗尽重试后必须同事务收口。
_sync_shipping_order_extraction_run_after_job_failure(job_id)
db.session.commit()
_expire_cached()
return rowcount == 1
def process_next_job(
*,
ctx: Any,
domain: str,
job_types: list[str | JobType] | None = None,
timeout_config_key: str | None = None,
default_timeout_seconds: float = 300,
) -> tuple[bool, str]:
"""
领取并分发一条通用任务。
核心逻辑:超时回收必须与本次允许领取的 job_types 同范围,避免同 domain
下其他类型被错误阈值或缺少业务回调的入口提前回收;未指定类型时才回收整个 domain。
"""
import app.jobs.handlers # noqa: F401
from app.jobs.registry import get_handler
timeout_seconds = float(
current_app.config.get(timeout_config_key, default_timeout_seconds)
if timeout_config_key
else default_timeout_seconds
)
normalized_types = list(
dict.fromkeys(
_normalize_job_type(item)
for item in (job_types or [])
if _normalize_job_type(item)
)
)
if normalized_types:
for normalized_type in normalized_types:
on_recovered = None
if normalized_type == JobType.SHIPPING_NOTICE_PARSE.value:
from app.services.shipping_notice.intake_parse_workflow import (
sync_intake_after_parse_job_recovery,
)
on_recovered = sync_intake_after_parse_job_recovery
elif normalized_type == JobType.SHIPPING_ORDER_EXTRACTION.value:
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_recovery,
)
on_recovered = sync_order_extraction_run_after_job_recovery
elif normalized_type == JobType.SHIPPING_DOCUMENT_LAYOUT.value:
from app.services.shipping_notice.document_layout.lifecycle import (
sync_layout_after_job_recovery,
)
on_recovered = sync_layout_after_job_recovery
recover_stale_jobs(
domain=domain,
timeout_seconds=timeout_seconds,
job_type=normalized_type,
on_recovered=on_recovered,
)
else:
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
job = claim_next_job(domain=domain, job_types=job_types)
if not job:
return False, "no_job"
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
job_type_value = str(job.job_type or "").strip()
payload = dict(job.payload_json or {})
payload.setdefault("job_id", job_id)
handler = get_handler(JobType(job_type_value))
if handler is None:
fail_job(
job_id,
error=f"no handler registered for {job.job_type}",
owned_attempt=owned_attempt,
)
return True, "missing_handler"
try:
handler(ctx, payload)
# 条件收口:Handler 已 finish/fail 或代次失效时 rowcount=0,不覆盖
finish_job(job_id, message="任务处理完成", owned_attempt=owned_attempt)
return True, job_type_value
except Exception as exc:
db.session.rollback()
# 失败收口的可重试性由异常类型分级裁定,不按业务域一刀切;
# handler 已自行 fail_job 收敛的绝不应进入此处,此处仅兜底 handler 逃逸的异常。
fail_job(
job_id,
error=str(exc),
retryable=_is_retryable_exc(exc),
owned_attempt=owned_attempt,
)
raise