feat(fulfillment): 支持选号优先级、三皮肤联合资格捆绑与同角色共享租约

This commit is contained in:
yml
2026-11-28 11:26:24 +08:00
parent ef226c9041
commit 20314a2f1d
24 changed files with 2504 additions and 495 deletions
@@ -5,7 +5,7 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import Integer, cast, func, or_
from sqlalchemy import select
from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
@@ -123,28 +123,24 @@ 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 的真实归属回收。
# 注意:不能在过滤孤儿前先 limit active 租约。生产有 3,900+ 条 active
# pf 租约,先取前 500 条会被合法租约占满,后面的孤儿永远轮不到。
# 这里直接用 SQL 关联出「task 不存在 / task 账号或租约不一致」。
task_id_expr = cast(func.substring(AccountLease.batch_id, 4), Integer)
# 分配并发/重试或任务清空可能留下「batch_id 指向 pf:task,但没有任何未取消任务
# 真正持有该租约」的孤儿 active 租约。使用 EXISTS(~has_holder) 避免 SQL `NULL != id`
# 为 UNKNOWN 漏掉被清空 account_id/lease_id 的孤儿租约,同时也兼容同角色共享租约。
has_holder = (
select(PlatformFulfillmentTask.id)
.where(
PlatformFulfillmentTask.lease_id == AccountLease.id,
PlatformFulfillmentTask.account_id == AccountLease.account_id,
)
.exists()
)
orphan_leases = (
db.query(AccountLease)
.outerjoin(
PlatformFulfillmentTask,
PlatformFulfillmentTask.id == task_id_expr,
)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.batch_id.like("pf:%"),
or_(
PlatformFulfillmentTask.id.is_(None),
PlatformFulfillmentTask.account_id != AccountLease.account_id,
PlatformFulfillmentTask.lease_id != AccountLease.id,
),
~has_holder,
)
.order_by(AccountLease.id.asc())
.limit(max(1, int(job.batch_size or 500)))