feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测

This commit is contained in:
hugo committed 2026-07-14 21:12:36 +08:00
1 parent 729546a7b7
commit ceb49461e8
72 files changed
+14270 -460

No files matched your search

@@ -2,101 +2,275 @@
backend/app/jobs/handlers/shipping_notice_parse.py
用途:发货通知接入记录异步预解析 handler。
依赖:jobs.context、jobs.registry、intake_parse_workflow。
逻辑:worker 消费 shipping_notice_parse 队列任务,更新 intake 状态 parsed/parse_failed。
领取与写回前均跳过 cancelled/expired/consumed,避免用户取消后被重新解析。
依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。
逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease;
Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE,
禁止依赖 Session 身份映射判断执行权。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import and_, or_, update
from app import db
from app.core.errors import NotFoundError
from app.core.errors import AppError, NotFoundError
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingNoticeIntake
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_parse_workflow import (
fail_intake_with_stage2_cleanup,
run_intake_parse,
)
# 终态:不可再领取解析;含用户取消与 TTL 过期
_SKIP_CLAIM_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
# 允许领取进入 parsing 的状态(含失败后重试)
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parsing', 'parse_failed'})
# 真终态:无论 Job 身份都不再领取
_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
# 正常可领取进入 parsing
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'})
def _load_asset(asset_id: int) -> FileAsset:
"""
加载父级 FileAsset;软删或不存在则抛 NotFoundError。
Args:
asset_id: FileAsset 主键。
Returns:
可用的 FileAsset。
Raises:
NotFoundError: 资产不存在或已软删。
"""
asset = db.session.get(FileAsset, asset_id)
if not asset or asset.deleted_at is not None:
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
return asset
def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str:
"""
构造本轮解析执行代次 token。
核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐;
无 Job(单测直调)时使用随机 UUID。
"""
if job_id is not None and owned_attempt is not None:
return f'{int(job_id)}:{int(owned_attempt)}'
return uuid.uuid4().hex
def _claim_intake_for_parsing(
intake_no: str,
*,
job_id: int | None,
owned_attempt: int | None,
) -> tuple[ShippingNoticeIntake, str] | None:
"""
原子领取 Intake 并轮转 parse_lease。
核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job
(回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。
Returns:
(Intake, lease) 或 None。
"""
now = datetime.utcnow()
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
if job_id is not None:
claim_predicate = or_(
claim_predicate,
and_(
ShippingNoticeIntake.parse_status == 'parsing',
ShippingNoticeIntake.parse_job_id == int(job_id),
),
)
values: dict = {
'parse_status': 'parsing',
'parse_lease': lease,
'updated_at': now,
}
if job_id is not None:
values['parse_job_id'] = int(job_id)
stmt = (
update(ShippingNoticeIntake)
.where(
ShippingNoticeIntake.intake_no == intake_no,
claim_predicate,
)
.values(**values)
)
result = db.session.execute(stmt)
if int(result.rowcount or 0) != 1:
db.session.rollback()
return None
db.session.commit()
intake = (
db.session.query(ShippingNoticeIntake)
.filter_by(intake_no=intake_no)
.first()
)
if intake is None:
return None
return intake, lease
def _is_retryable_exc(exc: BaseException) -> bool:
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
"""
消费发货通知预解析任务。
Args:
ctx: Worker 上下文。
payload: 须含 job_id 或 intake_no。
"""
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
job_id = int(job.id) if job is not None else None
# claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE)
owned_attempt = int(job.attempts or 0) if job is not None else None
intake_no = str(
(job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or ''
).strip().upper()
if not intake_no:
if job:
fail_job(job, error='missing intake_no')
raise RuntimeError('missing intake_no')
if job_id is not None:
fail_job(
job_id,
error='missing intake_no',
retryable=False,
owned_attempt=owned_attempt,
)
return
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
if not intake:
if job:
fail_job(job, error=f'intake not found: {intake_no}')
raise RuntimeError(f'intake not found: {intake_no}')
# [STEP 1] 领取前跳过终态(含 cancelled/expired)
if intake.parse_status in _SKIP_CLAIM_STATUSES:
if job:
finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True})
return
if intake.parse_status not in _CLAIMABLE_STATUSES:
if job:
finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True})
if job_id is not None:
fail_job(
job_id,
error=f'intake not found: {intake_no}',
retryable=False,
owned_attempt=owned_attempt,
)
return
intake.parse_status = 'parsing'
intake.updated_at = datetime.utcnow()
db.session.commit()
# [STEP 1] 真终态跳过
if intake.parse_status in _TERMINAL_SKIP_STATUSES:
if job_id is not None:
finish_job(
job_id,
result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True},
owned_attempt=owned_attempt,
)
return
# [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过
if (
intake.parse_status == 'parsing'
and job_id is not None
and (
intake.parse_job_id is None
or int(intake.parse_job_id) != int(job_id)
)
):
finish_job(
job_id,
result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True},
owned_attempt=owned_attempt,
)
return
# [STEP 2] 原子领取并轮转 lease
claimed = _claim_intake_for_parsing(
intake_no, job_id=job_id, owned_attempt=owned_attempt
)
if claimed is None:
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
if job_id is not None:
finish_job(
job_id,
result={
'status': str(getattr(current, 'parse_status', None) or 'unknown'),
'intake_no': intake_no,
'skipped': True,
},
owned_attempt=owned_attempt,
)
return
intake, parse_lease = claimed
intake_id = int(intake.id)
preserved_parser = str(intake.parser_version or 'v6')
preserved_text = intake.extracted_text
preserved_structured = (
dict(intake.structured_result_json)
if isinstance(intake.structured_result_json, dict)
else {}
)
preserved_warnings = list(intake.parse_warnings_json or [])
asset = _load_asset(intake.asset_id)
try:
result = run_intake_parse(intake, asset)
if job:
refreshed = db.session.get(Job, job.id)
if refreshed and refreshed.status == 'running':
status = str(result.get('status') or '')
if status in {'parsed', 'skipped'}:
finish_job(refreshed, result=result, message='发货通知预解析完成' if status == 'parsed' else '接入已取消或过期,跳过')
else:
fail_job(
refreshed,
error=str(result.get('error_message') or intake.error_message or 'parse failed'),
retryable=False,
)
asset = _load_asset(intake.asset_id)
result = run_intake_parse(intake, asset, parse_lease=parse_lease)
if job_id is None:
return
status = str(result.get('status') or '')
if status in {'parsed', 'skipped'}:
finish_job(
job_id,
result=result,
message=(
'发货通知预解析完成'
if status == 'parsed'
else '接入已取消、过期或执行代次失效,跳过'
),
owned_attempt=owned_attempt,
)
else:
fail_job(
job_id,
error=str(result.get('error_message') or 'parse failed'),
retryable=False,
owned_attempt=owned_attempt,
)
except Exception as exc:
db.session.rollback()
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
# 取消/过期后不再覆盖为 parse_failed
if intake and intake.parse_status not in _SKIP_CLAIM_STATUSES:
intake.parse_status = 'parse_failed'
intake.error_code = 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
intake.error_message = str(exc)[:1000]
db.session.commit()
if job:
refreshed = db.session.get(Job, job.id)
if refreshed:
fail_job(refreshed, error=str(exc), retryable=True)
raise
error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
fail_result = fail_intake_with_stage2_cleanup(
intake_id=intake_id,
intake_no=intake_no,
parser_version=preserved_parser,
error_code=str(error_code),
error_message=str(exc)[:1000],
extracted_text=preserved_text,
structured_result_json=preserved_structured,
parse_warnings_json=preserved_warnings,
allowed_statuses=frozenset({'parsing', 'queued', 'created'}),
required_lease=parse_lease,
)
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
return
retryable = _is_retryable_exc(exc)
if job_id is not None:
fail_job(
job_id,
error=str(exc),
retryable=retryable,
owned_attempt=owned_attempt,
)
if retryable:
raise
+757 -73
View File
@@ -2,17 +2,25 @@
backend/app/jobs/queue.py
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
依赖: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;
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.exc import OperationalError
from sqlalchemy import update
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import Session
from app import db
from app.core.errors import ValidationError
@@ -20,7 +28,43 @@ 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 _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:
@@ -28,6 +72,242 @@ def _normalize_job_type(job_type: JobType | str) -> str:
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 ShippingNoticeIntake
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(ShippingNoticeIntake)
.filter(ShippingNoticeIntake.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 ShippingNoticeIntake
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(ShippingNoticeIntake)
.filter(ShippingNoticeIntake.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:
@@ -103,12 +383,19 @@ def enqueue(
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,
) -> 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。
@@ -118,7 +405,10 @@ def enqueue(
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
dedupe_active: 是否复用 active 状态的同业务任务。
dedupe_active: 是否复用同业务键下指定状态中的任务。
dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。
重试场景应传仅 queued,避免复用即将结束的 running Job。
commit: False 时仅 flush,由调用方与业务行同一事务提交。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
"""
@@ -139,20 +429,26 @@ def enqueue(
if not isinstance(payload, dict):
raise ValueError("payload must be a dict")
if dedupe_active and normalized_ref:
existing = (
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_(ACTIVE_STATUSES),
Job.status.in_(statuses),
)
.order_by(Job.created_at.desc(), Job.id.desc())
.first()
)
if existing:
return int(existing.id)
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
@@ -171,50 +467,207 @@ def enqueue(
created_at=queue_at,
updated_at=now,
)
db.session.add(job)
db.session.commit()
# [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 recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
"""回收指定业务域内超时 running 的通用任务。"""
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,
)
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)
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
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:
if int(job.attempts or 0) < int(job.max_attempts or 1):
job.status = "queued"
job.message = "任务执行超时,已回收等待重试"
job.locked_by = None
job.locked_at = None
job.started_at = None
job.updated_at = now
# 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running)
if str(job.status or "") != "running":
continue
job.status = "failed"
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
job.message = job.error_message
job.progress = 100
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
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)
recovered += 1
db.session.commit()
return len(stale_jobs)
return recovered
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
@@ -243,7 +696,8 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
return None
job.status = "running"
job.started_at = job.started_at or now
# 每次领取刷新 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
@@ -254,35 +708,235 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
return job
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
"""标记任务成功完成。"""
now = datetime.utcnow()
job.status = "success"
job.progress = 100
job.result_json = result or {}
job.message = message or "任务处理完成"
job.error_message = None
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
db.session.commit()
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 fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
"""标记任务失败;retryable 且未达上限时重新排队。"""
def finish_job(
job: Job | int,
*,
result: dict[str, Any] | None = None,
message: str | None = None,
owned_attempt: int | None = None,
) -> bool:
"""
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
Returns:
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
"""
now = datetime.utcnow()
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
job.status = "queued" if can_retry else "failed"
job.progress = 0 if can_retry else 100
job.result_json = result or {}
job.error_message = str(error or "job failed")[:1000]
job.message = "任务失败,等待重试" if can_retry else job.error_message
job.locked_by = None
job.locked_at = None
job.finished_at = None if can_retry else now
job.updated_at = now
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)
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)
db.session.commit()
_expire_cached()
return rowcount == 1
def process_next_job(
@@ -293,7 +947,12 @@ def process_next_job(
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
@@ -302,29 +961,54 @@ def process_next_job(
if timeout_config_key
else default_timeout_seconds
)
recover_stale_jobs(domain=domain, timeout_seconds=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
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, error=f"no handler registered for {job.job_type}")
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)
refreshed = db.session.get(Job, job_id)
if refreshed and refreshed.status == "running":
finish_job(refreshed, message="任务处理完成")
# 条件收口: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()
refreshed = db.session.get(Job, job_id)
if refreshed:
fail_job(refreshed, error=str(exc), retryable=True)
fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
raise
+12 -2
View File
@@ -43,13 +43,23 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
continue
handler = get_handler(job['job_type'])
owned_attempt = job.get('attempts')
owned_attempt_int = int(owned_attempt) if owned_attempt is not None else None
if not handler:
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
store.mark_failed(
job['id'],
message=f'no handler for {job.get("job_type")}',
owned_attempt=owned_attempt_int,
)
continue
try:
handler(ctx, job.get('payload') or {})
except Exception as exc:
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
store.mark_failed(job['id'], message=str(exc))
store.mark_failed(
job['id'],
message=str(exc),
owned_attempt=owned_attempt_int,
)
+14 -4
View File
@@ -20,6 +20,8 @@ def _normalize_generic_job(job: Job) -> dict[str, Any]:
'id': job.id,
'job_type': JobType(job_type_value),
'raw_job_type': job_type_value,
# 领取时代次,供异常收口条件 UPDATE(勿信 Session 缓存)
'attempts': int(job.attempts or 0),
'payload': {
'job_id': job.id,
**(job.payload_json or {}),
@@ -96,21 +98,29 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
return None
def mark_failed(job_id: int, *, message: str) -> None:
def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None:
"""
handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
Args:
job_id: 任务主键。
message: 失败原因(截断至 1000 字符)。
owned_attempt: 领取时的 Job.attempts;通用 Job 用条件 UPDATE,避免覆盖新代次。
"""
from datetime import datetime
from app import db
from app.jobs.queue import fail_job
job = db.session.get(Job, job_id)
if job and job.status == 'running':
fail_job(job, error=message[:1000], retryable=True)
# 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
if generic is not None:
fail_job(
int(job_id),
error=message[:1000],
retryable=True,
owned_attempt=owned_attempt,
)
return
kb_job = db.session.get(KbJob, job_id)