diff --git a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py index 8533f2f..a918b3a 100644 --- a/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py +++ b/web/backend/services/automation/jobs/platform_fulfillment_lease_reaper.py @@ -5,6 +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.orm import Session from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask @@ -97,12 +98,25 @@ def run_platform_fulfillment_lease_reaper( # 分配并发/重试可能留下「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) 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, + ), ) .order_by(AccountLease.id.asc()) .limit(max(1, int(job.batch_size or 500))) @@ -110,19 +124,6 @@ def run_platform_fulfillment_lease_reaper( ) 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,