fix(fulfillment): 修复分配重试产生的孤儿租约

- 分配前锁平台任务行,避免同一任务并发领两个账
- 落库前释放同任务下其他 active 租约
- 租约回收作业增加 task/租约不一致的孤儿回收
- 补充孤儿租约回收测试与订单 2632301937741357 复盘
This commit is contained in:
yml
2026-11-24 19:03:07 +08:00
parent 1081e93522
commit b10018efdd
4 changed files with 133 additions and 4 deletions
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
from ...platform_fulfillment.account_selector import (
expire_platform_fulfillment_leases,
release_lease,
)
from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes
@@ -93,6 +94,44 @@ def run_platform_fulfillment_lease_reaper(
if task is not None:
converted_tasks[int(task.id)] = task
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
orphan_leases = (
db.query(AccountLease)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.batch_id.like("pf:%"),
)
.order_by(AccountLease.id.asc())
.limit(max(1, int(job.batch_size or 500)))
.all()
)
orphan_released = 0
for lease in orphan_leases:
try:
task_id = int(str(lease.batch_id).removeprefix("pf:"))
except ValueError:
task_id = 0
task = (
db.get(PlatformFulfillmentTask, task_id) if task_id else None
)
if (
task is not None
and task.account_id == lease.account_id
and task.lease_id == lease.id
):
continue
if release_lease(
db,
lease,
reason="lease_task_mismatch",
now=moment,
commit=False,
):
orphan_released += 1
expired = expire_platform_fulfillment_leases(
db,
now=moment,
@@ -126,14 +165,15 @@ def run_platform_fulfillment_lease_reaper(
task.last_error = "账号租约已过期,请重新分配账号"
task.updated_at = moment
affected += 1
if released_ids or converted_tasks:
if released_ids or converted_tasks or orphan_released:
db.commit()
return {
"scanned": expired,
"scanned": expired + orphan_released,
"expired": expired,
"orphan_released": orphan_released,
"stale_binding_recovered": len(stale_binding_leases),
"affected_tasks": affected,
"message": f"直播账号履约租约回收 {expired} 条",
"message": f"直播账号履约租约回收 {expired + orphan_released} 条",
}