From 77a881bdf830c681a1c4e9b9608879a8c3de1917 Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 19:23:23 +0800 Subject: [PATCH] =?UTF-8?q?fix(fulfillment):=20=E5=AD=A4=E5=84=BF=E7=A7=9F?= =?UTF-8?q?=E7=BA=A6=E5=9B=9E=E6=94=B6=E6=8C=89=20SQL=20=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E5=90=8E=E5=86=8D=E9=99=90=E6=89=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 先取前 500 条 active pf 租约会被合法租约占满,8877 等高 ID 孤儿永远轮不到 - 改为 outer join task,直接筛 task 不存在/账号或租约不一致 - 保留 batch_size 作为本轮释放上限 --- .../jobs/platform_fulfillment_lease_reaper.py | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) 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,