fix(automation): 修复账号供给补货队列饥饿
- 拆分订单补货和通用供给水位,供给保留独立 pending 配额 - 每批固定供给槽位,避免订单补货占满队列 - 只补覆盖/可兑换缺口,可分配缺口不再无效入队 - 重登工作超过 24h 自动转人工,清理待处理积压 - 补货阻塞告警和队列诊断信息 - 增加供给公平调度/过期清理回归测试
This commit is contained in:
@@ -800,6 +800,71 @@ CK:
|
|||||||
- 自动重登触发到成功的延迟;
|
- 自动重登触发到成功的延迟;
|
||||||
- 因配额被延后的账号数和预计等待时间。
|
- 因配额被延后的账号数和预计等待时间。
|
||||||
|
|
||||||
|
## 2026-11-24 补货队列饥饿与公平调度
|
||||||
|
|
||||||
|
### 生产只读诊断
|
||||||
|
|
||||||
|
2026-11-24 13:16(UTC+8)只读检查:
|
||||||
|
|
||||||
|
```text
|
||||||
|
account_supply_replenishment:
|
||||||
|
评估 2 个供给目标,短缺 2 个,新排队 0 个账号同步
|
||||||
|
account_capability_refresh:
|
||||||
|
本轮筛选 20 个待补货账号,新入队 20 个(待履约商品 bag412)
|
||||||
|
account_sync_queue:
|
||||||
|
账号同步完成 20 条
|
||||||
|
```
|
||||||
|
|
||||||
|
- 待处理同步工作:**59 个 `storehome_sync` + 1 个 `points_sync` = 60**;
|
||||||
|
- 供给补货的低水位:`min(总 60, 供给 20) = 20`;
|
||||||
|
- `headroom = 20 - 60 = 0`,所以每次只排队 0 个;
|
||||||
|
- `account_capability_refresh` 每分钟固定入队 20 个(订单商品 `bag412`),
|
||||||
|
同步队列每分钟处理 20 个,正好打平;通用供给永远拿不到槽位。
|
||||||
|
- 另有 **76 个 `login_relogin` pending**;`ck_relogin` 因重登 100% 失败
|
||||||
|
(email_code)已自动暂停,这些工作永不执行。
|
||||||
|
- 普通池覆盖 `867/2060`(缺 1193),但可分配只有 `50/260`;同期
|
||||||
|
预售绑定 1904、协作单绑定 1704,可分配缺口主要是保护/租约,不是能力快照。
|
||||||
|
|
||||||
|
### 调度改造
|
||||||
|
|
||||||
|
1. **水位拆分**(不再用一个 `min(60,20)`):
|
||||||
|
- 同步队列总量 `ACCOUNT_SYNC_QUEUE_TARGET_PENDING` 默认 120;
|
||||||
|
- 订单补货水位 `ACCOUNT_ORDER_QUEUE_TARGET_PENDING` 默认 70;
|
||||||
|
- 供给补货保留水位 `ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING` 默认 50;
|
||||||
|
- 供给入队 headroom = `min(供给水位 - 供给 pending, 总量水位 - 总量 pending)`。
|
||||||
|
2. **每批固定配额**:
|
||||||
|
- `ACCOUNT_SUPPLY_QUEUE_QUOTA` 默认 8(按 20 条满批理解);
|
||||||
|
- `run_account_sync_queue` 每批先领最多 8 条 `reason LIKE '供给短缺:%'`,
|
||||||
|
剩余槽位再领订单补货;
|
||||||
|
- 可用槽位变小时按比例缩,避免只剩 1-3 个槽位时供给全拿走。
|
||||||
|
3. **订单补货水位独立**:
|
||||||
|
- `account_capability_refresh` 只数订单补货 pending(排除供给 reason),
|
||||||
|
使用订单水位;不会再把通用供给的空间吃掉。
|
||||||
|
4. **只补“可刷新的缺口”**:
|
||||||
|
- `covered_shortage` / `available_shortage` 才入队;
|
||||||
|
- 只有 `allocatable_shortage` 的目标(例如高价值池 239/260)标记为
|
||||||
|
“需容量”,不再每轮重复入队浪费队列;
|
||||||
|
- 补货任务消息带:覆盖/可兑换短缺、仅可分配短缺、供给 pending/水位、
|
||||||
|
总 pending/水位、本轮排队数。
|
||||||
|
5. **重登死队列清理**:
|
||||||
|
- `login_relogin` pending 超过 `ACCOUNT_RELOGIN_WORK_TTL_SECONDS`(默认 24h)
|
||||||
|
置 failed,last_error 标记“转人工”;
|
||||||
|
- 由 `account_sync_queue` 作业每分钟顺带清理,避免暂停作业后 76 条工作
|
||||||
|
永久挂在“待处理”。
|
||||||
|
6. **可观测告警**:
|
||||||
|
- 供给目标存在可刷新缺口,而补货作业消息包含“新排队 0”时,
|
||||||
|
账号运行总览增加 `supply_replenishment_blocked` 告警。
|
||||||
|
|
||||||
|
### 预期效果
|
||||||
|
|
||||||
|
- 队列处理 20/分钟:12 条订单补货 + 8 条供给补货;
|
||||||
|
- 供给补货约 **8 个/分钟 ≈ 480/小时**,1193 个覆盖缺口约 **2.5 小时**
|
||||||
|
可以补完(若候选账号足够);
|
||||||
|
- 订单补货从 20/分钟降到 12/分钟,持续约 2.5 小时;之后供给 pending 下降,
|
||||||
|
队列自动恢复。
|
||||||
|
- **可分配 50/260 不会仅靠刷新能力变成 260**:它受 1904 预售 + 1704 协作保护、
|
||||||
|
租约和冷却限制;需要增加普通账号或调整保护/目标。
|
||||||
|
|
||||||
## 验收标准
|
## 验收标准
|
||||||
|
|
||||||
1. 每个 CK 周期都有签发、有效、失效和观测寿命记录;
|
1. 每个 CK 周期都有签发、有效、失效和观测寿命记录;
|
||||||
@@ -834,3 +899,4 @@ CK:
|
|||||||
| 日期 | 变更 |
|
| 日期 | 变更 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 2026-11-21 | 根据生产 CK 事件和账号数据建立 CK 生命周期、供给目标、查询同步和防重复设计 |
|
| 2026-11-21 | 根据生产 CK 事件和账号数据建立 CK 生命周期、供给目标、查询同步和防重复设计 |
|
||||||
|
| 2026-11-24 | 拆分订单/供给水位,增加每批供给配额、只补可刷新缺口、重登过期清理和补货阻塞告警 |
|
||||||
|
|||||||
@@ -42,7 +42,11 @@ from web.backend.services.account_supply_service import (
|
|||||||
refresh_supply_snapshots,
|
refresh_supply_snapshots,
|
||||||
upsert_supply_target,
|
upsert_supply_target,
|
||||||
)
|
)
|
||||||
from web.backend.services.account_work_queue import enqueue_account_work
|
from web.backend.services.account_work_queue import (
|
||||||
|
ORDER_REFRESH_REASON_PREFIX,
|
||||||
|
SUPPLY_REASON_PREFIX,
|
||||||
|
enqueue_account_work,
|
||||||
|
)
|
||||||
|
|
||||||
NOW = datetime.now(UTC).replace(microsecond=0)
|
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||||
|
|
||||||
@@ -811,3 +815,75 @@ def test_account_platform_status_alerts_on_persistently_low_trends(db):
|
|||||||
"login_success_rate_low",
|
"login_success_rate_low",
|
||||||
"relogin_failure_trend_high",
|
"relogin_failure_trend_high",
|
||||||
} <= codes
|
} <= codes
|
||||||
|
|
||||||
|
|
||||||
|
def test_supply_replenishment_queues_when_order_queue_is_busy(db):
|
||||||
|
# 60 个订单补货工作把旧版“总待处理 60 - 供给水位 20”占满;
|
||||||
|
# 新版供给有独立水位,仍应至少排入一个账号。
|
||||||
|
accounts = [_account(f"supply-busy-{index}", points=400) for index in range(65)]
|
||||||
|
db.add_all(accounts)
|
||||||
|
db.flush()
|
||||||
|
for account in accounts[:60]:
|
||||||
|
enqueue_account_work(
|
||||||
|
db,
|
||||||
|
account_id=account.id,
|
||||||
|
work_type="storehome_sync",
|
||||||
|
priority=10,
|
||||||
|
reason=f"{ORDER_REFRESH_REASON_PREFIX} C",
|
||||||
|
due_at=NOW,
|
||||||
|
)
|
||||||
|
db.add(
|
||||||
|
AccountSupplyTarget(
|
||||||
|
platform="douyu",
|
||||||
|
scope="elite",
|
||||||
|
commodity_id="C",
|
||||||
|
value_class=VALUE_HIGH,
|
||||||
|
target_covered=1,
|
||||||
|
target_available=1,
|
||||||
|
target_allocatable=0,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
result = enqueue_supply_replenishment(db, now=NOW, max_per_target=10)
|
||||||
|
|
||||||
|
assert result.pending_sync == 60
|
||||||
|
assert result.pending_supply == 0
|
||||||
|
assert result.total_cap == 120
|
||||||
|
assert result.supply_cap == 50
|
||||||
|
assert result.queued == 1
|
||||||
|
supply_work = (
|
||||||
|
db.query(AccountWorkItem)
|
||||||
|
.filter(AccountWorkItem.reason.like(f"{SUPPLY_REASON_PREFIX}%"))
|
||||||
|
.one()
|
||||||
|
)
|
||||||
|
assert supply_work.account_id in {account.id for account in accounts[60:]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_supply_replenishment_skips_allocatable_only_shortage(db):
|
||||||
|
account = _account("supply-allocatable-only", points=400)
|
||||||
|
db.add(account)
|
||||||
|
db.flush()
|
||||||
|
db.add_all(
|
||||||
|
[
|
||||||
|
_state(account),
|
||||||
|
AccountSupplyTarget(
|
||||||
|
platform="douyu",
|
||||||
|
scope="elite",
|
||||||
|
commodity_id="C",
|
||||||
|
value_class=VALUE_HIGH,
|
||||||
|
target_covered=1,
|
||||||
|
target_available=1,
|
||||||
|
target_allocatable=2,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
result = enqueue_supply_replenishment(db, now=NOW, max_per_target=10)
|
||||||
|
|
||||||
|
assert result.shortages == 1
|
||||||
|
assert result.refreshable_shortages == 0
|
||||||
|
assert result.capacity_shortages == 1
|
||||||
|
assert result.queued == 0
|
||||||
|
assert db.query(AccountWorkItem).count() == 0
|
||||||
|
|||||||
@@ -17,12 +17,16 @@ from web.backend.services.account_sync_runner import (
|
|||||||
WORK_ESPORTS_SYNC,
|
WORK_ESPORTS_SYNC,
|
||||||
WORK_EXCHANGE_RECORDS_SYNC,
|
WORK_EXCHANGE_RECORDS_SYNC,
|
||||||
WORK_STOREHOME_SYNC,
|
WORK_STOREHOME_SYNC,
|
||||||
|
claim_sync_work_batch,
|
||||||
execute_account_work_item,
|
execute_account_work_item,
|
||||||
run_account_sync_queue,
|
run_account_sync_queue,
|
||||||
)
|
)
|
||||||
from web.backend.services.account_work_queue import (
|
from web.backend.services.account_work_queue import (
|
||||||
|
ORDER_REFRESH_REASON_PREFIX,
|
||||||
|
SUPPLY_REASON_PREFIX,
|
||||||
claim_account_work,
|
claim_account_work,
|
||||||
enqueue_account_work,
|
enqueue_account_work,
|
||||||
|
expire_stale_login_work,
|
||||||
recover_running_account_work,
|
recover_running_account_work,
|
||||||
)
|
)
|
||||||
from web.backend.services.douyu_read_gateway import StorehomeSnapshot
|
from web.backend.services.douyu_read_gateway import StorehomeSnapshot
|
||||||
@@ -337,3 +341,65 @@ def test_restart_recovers_running_work(db):
|
|||||||
assert row.status == "pending"
|
assert row.status == "pending"
|
||||||
assert row.due_at <= datetime.now(UTC)
|
assert row.due_at <= datetime.now(UTC)
|
||||||
assert "服务重启" in row.last_error
|
assert "服务重启" in row.last_error
|
||||||
|
|
||||||
|
|
||||||
|
def test_claim_sync_work_batch_reserves_supply_quota(db, monkeypatch):
|
||||||
|
monkeypatch.setenv("ACCOUNT_SUPPLY_QUEUE_QUOTA", "5")
|
||||||
|
moment = datetime.now(UTC).replace(microsecond=0)
|
||||||
|
accounts = [_account(f"quota-{index}") for index in range(25)]
|
||||||
|
db.add_all(accounts)
|
||||||
|
db.flush()
|
||||||
|
for account in accounts[:20]:
|
||||||
|
enqueue_account_work(
|
||||||
|
db,
|
||||||
|
account_id=account.id,
|
||||||
|
work_type=WORK_STOREHOME_SYNC,
|
||||||
|
priority=10,
|
||||||
|
reason=f"{ORDER_REFRESH_REASON_PREFIX} C",
|
||||||
|
due_at=moment,
|
||||||
|
)
|
||||||
|
for account in accounts[20:]:
|
||||||
|
enqueue_account_work(
|
||||||
|
db,
|
||||||
|
account_id=account.id,
|
||||||
|
work_type=WORK_STOREHOME_SYNC,
|
||||||
|
priority=35,
|
||||||
|
reason=f"{SUPPLY_REASON_PREFIX} elite/all/high_value",
|
||||||
|
due_at=moment,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
supply, normal = claim_sync_work_batch(db, limit=20, now=moment)
|
||||||
|
|
||||||
|
assert len(supply) == 5
|
||||||
|
assert len(normal) == 15
|
||||||
|
assert all(
|
||||||
|
item.reason.startswith(SUPPLY_REASON_PREFIX) for item in supply
|
||||||
|
)
|
||||||
|
assert all(
|
||||||
|
not item.reason.startswith(SUPPLY_REASON_PREFIX) for item in normal
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_expire_stale_login_work(db):
|
||||||
|
moment = datetime.now(UTC).replace(microsecond=0)
|
||||||
|
account = _account("relogin-stale")
|
||||||
|
db.add(account)
|
||||||
|
db.flush()
|
||||||
|
item = enqueue_account_work(
|
||||||
|
db,
|
||||||
|
account_id=account.id,
|
||||||
|
work_type="login_relogin",
|
||||||
|
priority=30,
|
||||||
|
due_at=moment - timedelta(days=2),
|
||||||
|
max_attempts=20,
|
||||||
|
reason="CK 已判定失效,等待受预算控制的重登",
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
expired = expire_stale_login_work(db, now=moment, ttl_seconds=86400)
|
||||||
|
|
||||||
|
db.refresh(item)
|
||||||
|
assert expired == 1
|
||||||
|
assert item.status == "failed"
|
||||||
|
assert "已转人工" in item.last_error
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from ..models import (
|
|||||||
AccountSyncRun,
|
AccountSyncRun,
|
||||||
AccountSyncState,
|
AccountSyncState,
|
||||||
AccountWorkItem,
|
AccountWorkItem,
|
||||||
|
AutomationJob,
|
||||||
LoginAttempt,
|
LoginAttempt,
|
||||||
)
|
)
|
||||||
from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED
|
from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED
|
||||||
@@ -322,6 +323,30 @@ def _supply_snapshot(
|
|||||||
"message": "尚未配置启用的账号供给目标",
|
"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
|
return supply_targets, alerts
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ from .account_query_filters import (
|
|||||||
from .account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
|
from .account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
|
||||||
from .account_value import is_high_value_expr
|
from .account_value import is_high_value_expr
|
||||||
from .account_work_queue import (
|
from .account_work_queue import (
|
||||||
|
SUPPLY_REASON_PREFIX,
|
||||||
active_account_work_count,
|
active_account_work_count,
|
||||||
active_account_work_exists,
|
active_account_work_exists,
|
||||||
enqueue_account_work,
|
enqueue_account_work,
|
||||||
@@ -93,6 +94,14 @@ class SupplyReplenishmentResult:
|
|||||||
targets: int
|
targets: int
|
||||||
queued: int
|
queued: int
|
||||||
shortages: 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):
|
def _value_filter(value_class: str, *, now: datetime):
|
||||||
@@ -664,20 +673,20 @@ def _sync_candidate_query(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _account_sync_queue_target_pending() -> int:
|
def _sync_total_target() -> int:
|
||||||
raw = os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")
|
"""同步队列总水位;订单补货和通用供给共享的硬上限。"""
|
||||||
try:
|
try:
|
||||||
total = max(1, int(raw))
|
return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "120")))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
total = 60
|
return 120
|
||||||
# 通用供给补货只占低水位;剩余水位留给有明确订单的履约商品,
|
|
||||||
# 防止注册顺序靠前的普通补货把待分配订单的紧急刷新挤到下一轮。
|
|
||||||
raw_supply = os.getenv("ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING", "20")
|
def _supply_queue_target() -> int:
|
||||||
|
"""通用供给补货自己的保留水位,不被订单补货占用。"""
|
||||||
try:
|
try:
|
||||||
supply = max(1, int(raw_supply))
|
return max(1, int(os.getenv("ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING", "50")))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
supply = 20
|
return 50
|
||||||
return min(total, supply)
|
|
||||||
|
|
||||||
|
|
||||||
def enqueue_supply_replenishment(
|
def enqueue_supply_replenishment(
|
||||||
@@ -689,27 +698,45 @@ def enqueue_supply_replenishment(
|
|||||||
"""按本地目标缺口定向入队 storehome 同步,不发起外部请求。"""
|
"""按本地目标缺口定向入队 storehome 同步,不发起外部请求。"""
|
||||||
moment = now or datetime.now(UTC)
|
moment = now or datetime.now(UTC)
|
||||||
inventories = load_supply_snapshot_inventories(db, now=moment)
|
inventories = load_supply_snapshot_inventories(db, now=moment)
|
||||||
queued = 0
|
total_cap = _sync_total_target()
|
||||||
shortages = 0
|
supply_cap = _supply_queue_target()
|
||||||
pending = active_account_work_count(
|
total_pending = active_account_work_count(
|
||||||
db,
|
db,
|
||||||
work_types=ACCOUNT_SYNC_WORK_TYPES,
|
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:
|
for inventory in inventories:
|
||||||
if not inventory.needs_replenishment:
|
if not inventory.needs_replenishment:
|
||||||
continue
|
continue
|
||||||
shortages += 1
|
shortages += 1
|
||||||
|
# 覆盖/可兑换缺口可以靠刷新账号能力解决;只有可分配缺口
|
||||||
|
# 是租约/协作/冷却造成的,刷新能力解决不了,不能占补货队列。
|
||||||
|
missing = max(
|
||||||
|
inventory.covered_shortage,
|
||||||
|
inventory.available_shortage,
|
||||||
|
)
|
||||||
|
if missing <= 0:
|
||||||
|
capacity_shortages += 1
|
||||||
|
continue
|
||||||
|
refreshable_shortages += 1
|
||||||
if headroom <= 0:
|
if headroom <= 0:
|
||||||
continue
|
continue
|
||||||
target = db.get(AccountSupplyTarget, inventory.target_id)
|
target = db.get(AccountSupplyTarget, inventory.target_id)
|
||||||
if target is None:
|
if target is None:
|
||||||
continue
|
continue
|
||||||
missing = max(
|
|
||||||
inventory.covered_shortage,
|
|
||||||
inventory.available_shortage,
|
|
||||||
inventory.allocatable_shortage,
|
|
||||||
)
|
|
||||||
limit = max(1, min(int(max_per_target), missing, headroom))
|
limit = max(1, min(int(max_per_target), missing, headroom))
|
||||||
account_ids = [
|
account_ids = [
|
||||||
int(account_id)
|
int(account_id)
|
||||||
@@ -744,6 +771,14 @@ def enqueue_supply_replenishment(
|
|||||||
targets=len(inventories),
|
targets=len(inventories),
|
||||||
queued=queued,
|
queued=queued,
|
||||||
shortages=shortages,
|
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,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from .account_sync_service import (
|
|||||||
sync_storehome_snapshot,
|
sync_storehome_snapshot,
|
||||||
)
|
)
|
||||||
from .account_work_queue import (
|
from .account_work_queue import (
|
||||||
|
SUPPLY_REASON_PREFIX,
|
||||||
claim_account_work,
|
claim_account_work,
|
||||||
complete_account_work,
|
complete_account_work,
|
||||||
fail_account_work,
|
fail_account_work,
|
||||||
@@ -299,6 +300,50 @@ def execute_account_work_item(
|
|||||||
session.close()
|
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(
|
def run_account_sync_queue(
|
||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
@@ -320,12 +365,12 @@ def run_account_sync_queue(
|
|||||||
"message": "账号同步槽已满,本轮跳过",
|
"message": "账号同步槽已满,本轮跳过",
|
||||||
}
|
}
|
||||||
limit = max(1, min(int(batch_size), capacity))
|
limit = max(1, min(int(batch_size), capacity))
|
||||||
items = claim_account_work(
|
supply_items, normal_items = claim_sync_work_batch(
|
||||||
db,
|
db,
|
||||||
work_types=ACCOUNT_SYNC_WORK_TYPES,
|
|
||||||
limit=limit,
|
limit=limit,
|
||||||
now=moment,
|
now=moment,
|
||||||
)
|
)
|
||||||
|
items = [*supply_items, *normal_items]
|
||||||
db.commit()
|
db.commit()
|
||||||
if not items:
|
if not items:
|
||||||
return {
|
return {
|
||||||
@@ -371,8 +416,11 @@ def run_account_sync_queue(
|
|||||||
"success": success,
|
"success": success,
|
||||||
"failed": failed,
|
"failed": failed,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
|
"supply": len(supply_items),
|
||||||
|
"order": len(normal_items),
|
||||||
"message": (
|
"message": (
|
||||||
f"账号同步完成 {success} 条"
|
f"账号同步完成 {success} 条"
|
||||||
|
+ f"(供给 {len(supply_items)} / 订单 {len(normal_items)})"
|
||||||
+ (f",失败 {failed} 条" if failed else "")
|
+ (f",失败 {failed} 条" if failed else "")
|
||||||
+ (f",跳过 {skipped} 条" if skipped else "")
|
+ (f",跳过 {skipped} 条" if skipped else "")
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ from ..models import Account, AccountWorkItem
|
|||||||
|
|
||||||
WORK_AGING_SECONDS = 30 * 60
|
WORK_AGING_SECONDS = 30 * 60
|
||||||
|
|
||||||
|
#: 供给补货任务的 reason 前缀;队列靠它给通用供给保留固定处理配额。
|
||||||
|
SUPPLY_REASON_PREFIX = "供给短缺:"
|
||||||
|
#: 履约商品能力补货任务的 reason 前缀;队列把它归入订单补货一侧。
|
||||||
|
ORDER_REFRESH_REASON_PREFIX = "待履约商品补货:"
|
||||||
|
|
||||||
|
|
||||||
def active_account_work_exists(*, work_type: str):
|
def active_account_work_exists(*, work_type: str):
|
||||||
"""SQL 子查询:同一账号已有同类型的待执行或运行中工作。"""
|
"""SQL 子查询:同一账号已有同类型的待执行或运行中工作。"""
|
||||||
@@ -31,19 +36,23 @@ def active_account_work_count(
|
|||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
work_types: tuple[str, ...],
|
work_types: tuple[str, ...],
|
||||||
|
reason_prefix: str | None = None,
|
||||||
|
exclude_reason_prefix: str | None = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
"""当前账号同步队列中尚未结束的工作数。"""
|
"""当前账号同步队列中尚未结束的工作数(可按 reason 分类)。"""
|
||||||
if not work_types:
|
if not work_types:
|
||||||
return 0
|
return 0
|
||||||
return int(
|
query = db.query(func.count(AccountWorkItem.id)).filter(
|
||||||
db.query(func.count(AccountWorkItem.id))
|
AccountWorkItem.work_type.in_(work_types),
|
||||||
.filter(
|
AccountWorkItem.status.in_(("pending", "running")),
|
||||||
AccountWorkItem.work_type.in_(work_types),
|
|
||||||
AccountWorkItem.status.in_(("pending", "running")),
|
|
||||||
)
|
|
||||||
.scalar()
|
|
||||||
or 0
|
|
||||||
)
|
)
|
||||||
|
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(
|
def enqueue_account_work(
|
||||||
@@ -106,6 +115,8 @@ def claim_account_work(
|
|||||||
limit: int = 10,
|
limit: int = 10,
|
||||||
now: datetime | None = None,
|
now: datetime | None = None,
|
||||||
account_ids: tuple[int, ...] | None = None,
|
account_ids: tuple[int, ...] | None = None,
|
||||||
|
reason_prefix: str | None = None,
|
||||||
|
exclude_reason_prefix: str | None = None,
|
||||||
) -> list[AccountWorkItem]:
|
) -> list[AccountWorkItem]:
|
||||||
moment = now or datetime.now(UTC)
|
moment = now or datetime.now(UTC)
|
||||||
query = (
|
query = (
|
||||||
@@ -120,6 +131,12 @@ def claim_account_work(
|
|||||||
if not account_ids:
|
if not account_ids:
|
||||||
return []
|
return []
|
||||||
query = query.filter(AccountWorkItem.account_id.in_(account_ids))
|
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 = (
|
rows = (
|
||||||
query
|
query
|
||||||
.order_by(
|
.order_by(
|
||||||
@@ -233,6 +250,52 @@ def recover_running_account_work(
|
|||||||
return len(items)
|
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(
|
def reschedule_account_work_type(
|
||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from ....models import (
|
|||||||
)
|
)
|
||||||
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
|
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
|
||||||
from ...account_work_queue import (
|
from ...account_work_queue import (
|
||||||
|
SUPPLY_REASON_PREFIX,
|
||||||
active_account_work_count,
|
active_account_work_count,
|
||||||
enqueue_account_work,
|
enqueue_account_work,
|
||||||
)
|
)
|
||||||
@@ -66,13 +67,17 @@ def _pending_demand_rows(
|
|||||||
return list(db.execute(statement).all())
|
return list(db.execute(statement).all())
|
||||||
|
|
||||||
|
|
||||||
def _queue_target_pending() -> int:
|
def _order_queue_target_pending() -> int:
|
||||||
|
"""订单能力补货自己的水位;通用供给有自己的保留水位。"""
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
raw = os.getenv("ACCOUNT_ORDER_QUEUE_TARGET_PENDING")
|
||||||
|
if raw is None:
|
||||||
|
raw = os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "70")
|
||||||
try:
|
try:
|
||||||
return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")))
|
return max(1, int(raw))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return 60
|
return 70
|
||||||
|
|
||||||
|
|
||||||
def _build_select_query(
|
def _build_select_query(
|
||||||
@@ -130,8 +135,9 @@ def run_account_capability_refresh(
|
|||||||
pending = active_account_work_count(
|
pending = active_account_work_count(
|
||||||
db,
|
db,
|
||||||
work_types=ACCOUNT_SYNC_WORK_TYPES,
|
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:
|
if headroom <= 0:
|
||||||
return {
|
return {
|
||||||
"scanned": 0,
|
"scanned": 0,
|
||||||
@@ -179,6 +185,7 @@ def run_account_capability_refresh(
|
|||||||
"detail": {
|
"detail": {
|
||||||
"queued": queued,
|
"queued": queued,
|
||||||
"pending": pending,
|
"pending": pending,
|
||||||
|
"order_cap": _order_queue_target_pending(),
|
||||||
"headroom": headroom,
|
"headroom": headroom,
|
||||||
"commodities": commodity_ids[:20],
|
"commodities": commodity_ids[:20],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -24,20 +24,43 @@ def run_account_supply_replenishment(
|
|||||||
db,
|
db,
|
||||||
max_per_target=max(1, int(job.batch_size or 50)),
|
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 {
|
return {
|
||||||
"scanned": result.targets,
|
"scanned": result.targets,
|
||||||
"success": result.queued,
|
"success": result.queued,
|
||||||
"invalid": 0,
|
"invalid": 0,
|
||||||
"skipped": max(0, result.targets - result.shortages),
|
"skipped": result.capacity_shortages,
|
||||||
"message": (
|
"message": message,
|
||||||
f"评估 {result.targets} 个供给目标,"
|
|
||||||
f"短缺 {result.shortages} 个,新排队 {result.queued} 个账号同步"
|
|
||||||
if result.targets
|
|
||||||
else "未配置账号供给目标"
|
|
||||||
),
|
|
||||||
"detail": {
|
"detail": {
|
||||||
"shortages": result.shortages,
|
"shortages": result.shortages,
|
||||||
|
"refreshable_shortages": result.refreshable_shortages,
|
||||||
|
"capacity_shortages": result.capacity_shortages,
|
||||||
"queued": result.queued,
|
"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),
|
"snapshots": len(snapshots),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from ....models import AccountWorkItem, AutomationJob
|
from ....models import AccountWorkItem, AutomationJob
|
||||||
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue
|
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"
|
JOB_KEY = "account_sync_queue"
|
||||||
|
|
||||||
@@ -31,12 +32,22 @@ def run_account_sync_queue_job(
|
|||||||
db: Session,
|
db: Session,
|
||||||
job: AutomationJob,
|
job: AutomationJob,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
|
moment = datetime.now(UTC)
|
||||||
|
expired = expire_stale_login_work(db, now=moment)
|
||||||
|
if expired:
|
||||||
|
db.commit()
|
||||||
result = run_account_sync_queue(
|
result = run_account_sync_queue(
|
||||||
db,
|
db,
|
||||||
batch_size=max(1, int(job.batch_size or 20)),
|
batch_size=max(1, int(job.batch_size or 20)),
|
||||||
)
|
)
|
||||||
if result.get("scanned"):
|
if result.get("scanned"):
|
||||||
result["remaining"] = count_pending_work(db)
|
result["remaining"] = count_pending_work(db)
|
||||||
|
if expired:
|
||||||
|
result["expired_login"] = expired
|
||||||
|
result["message"] = (
|
||||||
|
f"{result.get('message') or '账号同步完成'},"
|
||||||
|
f"过期重登转人工 {expired} 条"
|
||||||
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user