fix(automation): 修复账号供给补货队列饥饿

- 拆分订单补货和通用供给水位,供给保留独立 pending 配额
- 每批固定供给槽位,避免订单补货占满队列
- 只补覆盖/可兑换缺口,可分配缺口不再无效入队
- 重登工作超过 24h 自动转人工,清理待处理积压
- 补货阻塞告警和队列诊断信息
- 增加供给公平调度/过期清理回归测试
This commit is contained in:
yml
2026-11-24 13:38:19 +08:00
parent 5b6d146f93
commit eda6115ca3
10 changed files with 462 additions and 42 deletions
@@ -17,6 +17,7 @@ from ..models import (
AccountSyncRun,
AccountSyncState,
AccountWorkItem,
AutomationJob,
LoginAttempt,
)
from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED
@@ -322,6 +323,30 @@ def _supply_snapshot(
"message": "尚未配置启用的账号供给目标",
}
)
refreshable = any(
item.covered_shortage or item.available_shortage
for item in inventories
)
supply_job = (
db.query(AutomationJob)
.filter(AutomationJob.key == "account_supply_replenishment")
.first()
)
if (
refreshable
and supply_job is not None
and "供给补货被订单队列阻塞" in str(supply_job.last_message or "")
):
alerts.append(
{
"code": "supply_replenishment_blocked",
"severity": "warning",
"message": (
"供给补货被同步队列占满,缺口未下降:"
f"{str(supply_job.last_message or '')[:240]}"
),
}
)
return supply_targets, alerts
+54 -19
View File
@@ -31,6 +31,7 @@ from .account_query_filters import (
from .account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
from .account_value import is_high_value_expr
from .account_work_queue import (
SUPPLY_REASON_PREFIX,
active_account_work_count,
active_account_work_exists,
enqueue_account_work,
@@ -93,6 +94,14 @@ class SupplyReplenishmentResult:
targets: int
queued: int
shortages: int
refreshable_shortages: int = 0
capacity_shortages: int = 0
pending_sync: int = 0
pending_supply: int = 0
total_headroom: int = 0
supply_headroom: int = 0
total_cap: int = 0
supply_cap: int = 0
def _value_filter(value_class: str, *, now: datetime):
@@ -664,20 +673,20 @@ def _sync_candidate_query(
)
def _account_sync_queue_target_pending() -> int:
raw = os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")
def _sync_total_target() -> int:
"""同步队列总水位;订单补货和通用供给共享的硬上限。"""
try:
total = max(1, int(raw))
return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "120")))
except ValueError:
total = 60
# 通用供给补货只占低水位;剩余水位留给有明确订单的履约商品,
# 防止注册顺序靠前的普通补货把待分配订单的紧急刷新挤到下一轮。
raw_supply = os.getenv("ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING", "20")
return 120
def _supply_queue_target() -> int:
"""通用供给补货自己的保留水位,不被订单补货占用。"""
try:
supply = max(1, int(raw_supply))
return max(1, int(os.getenv("ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING", "50")))
except ValueError:
supply = 20
return min(total, supply)
return 50
def enqueue_supply_replenishment(
@@ -689,27 +698,45 @@ def enqueue_supply_replenishment(
"""按本地目标缺口定向入队 storehome 同步,不发起外部请求。"""
moment = now or datetime.now(UTC)
inventories = load_supply_snapshot_inventories(db, now=moment)
queued = 0
shortages = 0
pending = active_account_work_count(
total_cap = _sync_total_target()
supply_cap = _supply_queue_target()
total_pending = active_account_work_count(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
)
headroom = max(0, _account_sync_queue_target_pending() - pending)
supply_pending = active_account_work_count(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
reason_prefix=SUPPLY_REASON_PREFIX,
)
# 供给有自己的保留水位,同时不能突破队列总水位。
# 旧逻辑用“总 pending”去减供给的 20,订单补货一忙,供给永远排队 0。
total_headroom = max(0, total_cap - total_pending)
supply_headroom = max(0, supply_cap - supply_pending)
headroom = min(total_headroom, supply_headroom)
queued = 0
shortages = 0
refreshable_shortages = 0
capacity_shortages = 0
for inventory in inventories:
if not inventory.needs_replenishment:
continue
shortages += 1
# 覆盖/可兑换缺口可以靠刷新账号能力解决;只有可分配缺口
# 是租约/协作/冷却造成的,刷新能力解决不了,不能占补货队列。
missing = max(
inventory.covered_shortage,
inventory.available_shortage,
)
if missing <= 0:
capacity_shortages += 1
continue
refreshable_shortages += 1
if headroom <= 0:
continue
target = db.get(AccountSupplyTarget, inventory.target_id)
if target is None:
continue
missing = max(
inventory.covered_shortage,
inventory.available_shortage,
inventory.allocatable_shortage,
)
limit = max(1, min(int(max_per_target), missing, headroom))
account_ids = [
int(account_id)
@@ -744,6 +771,14 @@ def enqueue_supply_replenishment(
targets=len(inventories),
queued=queued,
shortages=shortages,
refreshable_shortages=refreshable_shortages,
capacity_shortages=capacity_shortages,
pending_sync=total_pending,
pending_supply=supply_pending,
total_headroom=total_headroom,
supply_headroom=supply_headroom,
total_cap=total_cap,
supply_cap=supply_cap,
)
+50 -2
View File
@@ -23,6 +23,7 @@ from .account_sync_service import (
sync_storehome_snapshot,
)
from .account_work_queue import (
SUPPLY_REASON_PREFIX,
claim_account_work,
complete_account_work,
fail_account_work,
@@ -299,6 +300,50 @@ def execute_account_work_item(
session.close()
def _supply_queue_quota(limit: int) -> int:
"""每批给通用供给补货保留的槽位数,避免被订单补货永久饿死。"""
import os
try:
configured = max(1, int(os.getenv("ACCOUNT_SUPPLY_QUEUE_QUOTA", "8")))
except ValueError:
configured = 8
# 配置按 20 条满批理解;可用槽位变小时按比例缩,避免只剩 3 个槽位时
# 供给全拿走、订单补货完全饿死。
scaled = max(1, round(int(limit) * configured / 20))
return max(1, min(int(limit), scaled))
def claim_sync_work_batch(
db: Session,
*,
limit: int,
now: datetime,
) -> tuple[list[AccountWorkItem], list[AccountWorkItem]]:
"""按固定配额领取供给工作和订单/其他同步工作。
供给任务优先占 ``ACCOUNT_SUPPLY_QUEUE_QUOTA`` 个槽位;剩余槽位再给
订单能力补货。年龄超过 30 分钟的任务仍然由 claim 内部的 aging 规则优先。
"""
safe_limit = max(1, int(limit))
supply_quota = _supply_queue_quota(safe_limit)
supply_items = claim_account_work(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
limit=supply_quota,
now=now,
reason_prefix=SUPPLY_REASON_PREFIX,
)
normal_items = claim_account_work(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
limit=max(0, safe_limit - len(supply_items)),
now=now,
exclude_reason_prefix=SUPPLY_REASON_PREFIX,
)
return supply_items, normal_items
def run_account_sync_queue(
db: Session,
*,
@@ -320,12 +365,12 @@ def run_account_sync_queue(
"message": "账号同步槽已满,本轮跳过",
}
limit = max(1, min(int(batch_size), capacity))
items = claim_account_work(
supply_items, normal_items = claim_sync_work_batch(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
limit=limit,
now=moment,
)
items = [*supply_items, *normal_items]
db.commit()
if not items:
return {
@@ -371,8 +416,11 @@ def run_account_sync_queue(
"success": success,
"failed": failed,
"skipped": skipped,
"supply": len(supply_items),
"order": len(normal_items),
"message": (
f"账号同步完成 {success} 条"
+ f"(供给 {len(supply_items)} / 订单 {len(normal_items)})"
+ (f",失败 {failed} 条" if failed else "")
+ (f",跳过 {skipped} 条" if skipped else "")
),
+72 -9
View File
@@ -13,6 +13,11 @@ from ..models import Account, AccountWorkItem
WORK_AGING_SECONDS = 30 * 60
#: 供给补货任务的 reason 前缀;队列靠它给通用供给保留固定处理配额。
SUPPLY_REASON_PREFIX = "供给短缺:"
#: 履约商品能力补货任务的 reason 前缀;队列把它归入订单补货一侧。
ORDER_REFRESH_REASON_PREFIX = "待履约商品补货:"
def active_account_work_exists(*, work_type: str):
"""SQL 子查询:同一账号已有同类型的待执行或运行中工作。"""
@@ -31,19 +36,23 @@ def active_account_work_count(
db: Session,
*,
work_types: tuple[str, ...],
reason_prefix: str | None = None,
exclude_reason_prefix: str | None = None,
) -> int:
"""当前账号同步队列中尚未结束的工作数。"""
"""当前账号同步队列中尚未结束的工作数(可按 reason 分类)。"""
if not work_types:
return 0
return int(
db.query(func.count(AccountWorkItem.id))
.filter(
AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.status.in_(("pending", "running")),
)
.scalar()
or 0
query = db.query(func.count(AccountWorkItem.id)).filter(
AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.status.in_(("pending", "running")),
)
if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
if exclude_reason_prefix:
query = query.filter(
~AccountWorkItem.reason.like(f"{exclude_reason_prefix}%")
)
return int(query.scalar() or 0)
def enqueue_account_work(
@@ -106,6 +115,8 @@ def claim_account_work(
limit: int = 10,
now: datetime | None = None,
account_ids: tuple[int, ...] | None = None,
reason_prefix: str | None = None,
exclude_reason_prefix: str | None = None,
) -> list[AccountWorkItem]:
moment = now or datetime.now(UTC)
query = (
@@ -120,6 +131,12 @@ def claim_account_work(
if not account_ids:
return []
query = query.filter(AccountWorkItem.account_id.in_(account_ids))
if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
if exclude_reason_prefix:
query = query.filter(
~AccountWorkItem.reason.like(f"{exclude_reason_prefix}%")
)
rows = (
query
.order_by(
@@ -233,6 +250,52 @@ def recover_running_account_work(
return len(items)
def expire_stale_login_work(
db: Session,
*,
now: datetime | None = None,
ttl_seconds: int | None = None,
) -> int:
"""关闭长时间未执行的重登工作,避免暂停作业后永久挂在待处理。
重登作业因 100% 失败自动暂停时,队列里会残留 pending 的
``login_relogin``;它们既不会执行,也会在页面上冒充“待处理”。超过 TTL
后置为 failed,转人工处理,不再占用队列观测。
"""
import os
moment = now or datetime.now(UTC)
if ttl_seconds is None:
try:
ttl_seconds = max(
60,
int(os.getenv("ACCOUNT_RELOGIN_WORK_TTL_SECONDS", "86400")),
)
except ValueError:
ttl_seconds = 86400
cutoff = (moment - timedelta(seconds=ttl_seconds)).replace(microsecond=0)
items = (
db.query(AccountWorkItem)
.filter(
AccountWorkItem.work_type == "login_relogin",
AccountWorkItem.status.in_(("pending", "running")),
AccountWorkItem.due_at < cutoff,
)
.all()
)
for item in items:
item.status = "failed"
item.finished_at = moment
item.last_error = (
f"重登工作超过 {ttl_seconds // 3600} 小时未执行"
"(重登作业可能已暂停),已转人工处理"
)
item.updated_at = moment
if items:
db.flush()
return len(items)
def reschedule_account_work_type(
db: Session,
*,
@@ -21,6 +21,7 @@ from ....models import (
)
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
from ...account_work_queue import (
SUPPLY_REASON_PREFIX,
active_account_work_count,
enqueue_account_work,
)
@@ -66,13 +67,17 @@ def _pending_demand_rows(
return list(db.execute(statement).all())
def _queue_target_pending() -> int:
def _order_queue_target_pending() -> int:
"""订单能力补货自己的水位;通用供给有自己的保留水位。"""
import os
raw = os.getenv("ACCOUNT_ORDER_QUEUE_TARGET_PENDING")
if raw is None:
raw = os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "70")
try:
return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")))
return max(1, int(raw))
except ValueError:
return 60
return 70
def _build_select_query(
@@ -130,8 +135,9 @@ def run_account_capability_refresh(
pending = active_account_work_count(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
exclude_reason_prefix=SUPPLY_REASON_PREFIX,
)
headroom = max(0, _queue_target_pending() - pending)
headroom = max(0, _order_queue_target_pending() - pending)
if headroom <= 0:
return {
"scanned": 0,
@@ -179,6 +185,7 @@ def run_account_capability_refresh(
"detail": {
"queued": queued,
"pending": pending,
"order_cap": _order_queue_target_pending(),
"headroom": headroom,
"commodities": commodity_ids[:20],
},
@@ -24,20 +24,43 @@ def run_account_supply_replenishment(
db,
max_per_target=max(1, int(job.batch_size or 50)),
)
blocked = bool(
result.refreshable_shortages
and result.queued == 0
and result.pending_supply == 0
and result.total_headroom == 0
)
message = (
f"评估 {result.targets} 个目标;"
f"覆盖/可兑换短缺 {result.refreshable_shortages} 个,"
f"仅可分配短缺 {result.capacity_shortages} 个(需容量);"
f"队列待处理 {result.pending_sync}"
f"(供给 {result.pending_supply}/{result.supply_cap},"
f"总量 {result.pending_sync}/{result.total_cap});"
f"本轮新排队 {result.queued}"
if result.targets
else "未配置账号供给目标"
)
if blocked:
message += ";供给补货被订单队列阻塞"
return {
"scanned": result.targets,
"success": result.queued,
"invalid": 0,
"skipped": max(0, result.targets - result.shortages),
"message": (
f"评估 {result.targets} 个供给目标,"
f"短缺 {result.shortages} 个,新排队 {result.queued} 个账号同步"
if result.targets
else "未配置账号供给目标"
),
"skipped": result.capacity_shortages,
"message": message,
"detail": {
"shortages": result.shortages,
"refreshable_shortages": result.refreshable_shortages,
"capacity_shortages": result.capacity_shortages,
"queued": result.queued,
"pending_sync": result.pending_sync,
"pending_supply": result.pending_supply,
"total_headroom": result.total_headroom,
"supply_headroom": result.supply_headroom,
"total_cap": result.total_cap,
"supply_cap": result.supply_cap,
"blocked": blocked,
"snapshots": len(snapshots),
},
}
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
from ....models import AccountWorkItem, AutomationJob
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue
from ...account_work_queue import expire_stale_login_work
JOB_KEY = "account_sync_queue"
@@ -31,12 +32,22 @@ def run_account_sync_queue_job(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
moment = datetime.now(UTC)
expired = expire_stale_login_work(db, now=moment)
if expired:
db.commit()
result = run_account_sync_queue(
db,
batch_size=max(1, int(job.batch_size or 20)),
)
if result.get("scanned"):
result["remaining"] = count_pending_work(db)
if expired:
result["expired_login"] = expired
result["message"] = (
f"{result.get('message') or '账号同步完成'},"
f"过期重登转人工 {expired} 条"
)
return result