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
@@ -48,6 +48,7 @@ from .account_selector import (
capability_candidate_rows,
capability_refresh_candidate_accounts,
lease_account,
release_lease,
)
from .common import (
DEFAULT_CAPABILITY_CANDIDATE_LIMIT,
@@ -61,7 +62,7 @@ from .common import (
_now,
)
from .outbox import _emit_order_site_binding_state
from .repository import _load_task
from .repository import _load_task, _load_task_for_update
from .runtime import (
_append_event,
_apply_task_lease_policy,
@@ -329,6 +330,18 @@ def _allocate_task_from_capability(
current: User,
) -> dict[str, Any]:
"""只用本地能力索引选号;外部资格查询留给独立同步队列。"""
# 同一任务并发点击/调度重试时,先在任务行上加锁。否则两个请求会各自
# 领到一个账号租约,后提交的一方覆盖 task.lease_id,先前的 active 租约
# 就变成孤儿(生产 7482/8877 就是这么来的)。
task = _load_task_for_update(db, int(task.id))
if task.account_id and task.lease_id:
current_lease = (
db.query(AccountLease)
.filter(AccountLease.id == int(task.lease_id))
.first()
)
if current_lease is not None and current_lease.status == "active":
return get_task_detail(db, task.id)
moment = _now()
required_points = int(task.required_points or 0)
try:
@@ -511,6 +524,23 @@ def _allocate_task_from_capability(
return get_task_detail(db, task.id)
selected_account = selected.account
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = selected_account.id
task.lease_id = lease.id
task.operator_id = current.id