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
+27
View File
@@ -288,3 +288,30 @@ live-hub 创建新的绑定任务。
- 自动兑换
- 多数量拆分
- 电竞手册、和平小店、虎牙和微博
## 租约孤儿与协作单接管冲突(2026-11-24)
订单 `2632301937741357` / 任务 #1057 在“当前待办”搜不到,是因为任务已经是
`manual_required` / `lease_expired`,需要到“需要人工”里查。
协作单编辑报“平台履约任务 #7482 与账号租约不一致”,根因不是 #1057,而是
任务 #7482 的分配重试留下了孤儿租约:
```text
lease 8877 account 5566 batch_id pf:7482
task 7482 account 5567 lease_id 8879
```
协作单按 `batch_id=pf:7482` 找到任务,再核对账号/租约不一致,拒绝接管。
修复:
1. `allocate_task` 先对平台任务行加锁,避免同一任务并发领到两个租约;
2. 分配落库前释放同任务下其他 active 租约(reason=`allocation_replaced`);
3. `platform_fulfillment_lease_reaper` 增加孤儿租约回收:
- active 租约的 `batch_id=pf:<task>`;
- task 不存在,或 task.account_id / task.lease_id 与租约不一致;
- 释放 reason=`lease_task_mismatch`。
这条回收会顺带释放账号 5566 的 8877。释放后把任务 #1057 重新分配到 5566,
协作单才能正常接管。
+32
View File
@@ -4915,6 +4915,38 @@ class TestBindingAndCompletion(_Base):
assert result["expired"] == 0
assert task.execution_status == "allocated"
def test_reaper_releases_orphan_active_lease_from_task_retry(self):
task = self._allocated()
orphan_account = self.account("orphan-retry-account")
orphan_lease = AccountLease(
account_id=orphan_account.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
status="active",
batch_id=f"pf:{task.id}",
commodity_id=task.commodity_id,
)
self.session.add(orphan_lease)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(orphan_lease)
task_lease = (
self.session.query(AccountLease)
.filter(AccountLease.id == task.lease_id)
.one()
)
assert result["orphan_released"] == 1
assert orphan_lease.status == "released"
assert task_lease.status == "active"
assert task.account_id is not None
def test_expired_platform_lease_hands_off_to_active_collab(self):
task = self._allocated()
lease = self.session.query(AccountLease).one()
@@ -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} 条",
}
@@ -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