fix(fulfillment): 按任务归属收敛履约角色绑定

- 绑定任务创建时写入订单归属,不再按账号和最新任务猜测
- 只有订单自己的绑定证据能改变订单状态,查询任务不再结算
- 无归属确认必须匹配本单目标角色且创建于本租约
- 订单 bound 后冻结,失败只认当前绑定任务
- 启动对账支持确认回调丢失恢复
- 补充归属、目标、租约窗口回归测试与复盘文档,并记录生产只读审计结论
This commit is contained in:
yml
2026-11-24 01:44:57 +08:00
parent 58d782643b
commit efb140cf27
12 changed files with 1467 additions and 417 deletions
+1 -1
View File
@@ -186,7 +186,7 @@ def recover_orphaned_work() -> None:
reconciled_bindings = reconcile_binding_observations(db)
if reconciled_bindings:
logger.info(
"启动收敛账号角色观测到履约任务: {} 条",
"启动收敛履约绑定证据: {} 条",
reconciled_bindings,
)
seeded_targets = ensure_default_supply_targets(db)
+163
View File
@@ -0,0 +1,163 @@
"""绑定任务的归属判定:一条绑定任务到底属于哪个履约订单。
## 为什么需要这个模块
精英宝典工作台只关心「这条任务自己的结果」,所以任务和账号之间不需要归属关系。
直播账号履约不一样:一个订单会占用一个账号一段时间,期间账号上可能出现多条
绑定任务(订单自己创建的、运营从精英宝典工作台创建的、上一个订单遗留下来的)。
以前履约层靠「账号 + 最新 id + 租约 active」去猜一条任务属于哪张订单,猜错就会
把别人的绑定结果投影到当前订单上。
这里把归属变成显式事实:
1. 履约订单自己创建的绑定任务在创建时就带 ``platform_task_id``;
2. 运营从精英宝典工作台为**已租给履约订单**的账号创建绑码/确认任务时,
创建入口调用 :func:`active_fulfillment_binding_task_id` 把订单 id 盖到任务上;
3. 只有带 ``platform_task_id`` 的任务才是订单的权威证据;
4. 没有归属的历史任务只能走 ``binding.py`` 里受严格限制的兼容路径。
归属一确定,剩下的事情就简单了:阶段、租约、角色目标都是可验证的,不需要
再猜「最新任务是不是本次扫码」。
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from sqlalchemy import or_
from sqlalchemy.orm import Session
from ..models import AccountLease, DouyuTask, PlatformFulfillmentTask
#: 允许把工作台任务挂到订单上的绑定阶段。已 bound / manual_required 的订单
#: 不再接受自动归属,避免工作台的一次手工操作改写已完成订单。
BINDING_LINKABLE_STATUSES = frozenset(
{
"not_started",
"allocated",
"preparing",
"qr_pending",
"waiting_bind",
"role_ready",
}
)
#: 绑定任务类型。查询类任务(query_game_name / query_change_bind_time)故意
#: 不在此列:查询只能证明账号当前状态,不能证明某个订单的绑定已经确认。
BINDING_TASK_TYPES = frozenset({"get_bind_qr", "confirm_bind"})
#: 任务创建时间与租约起点的容差。两者由不同事务写入,允许几秒偏差;
#: 不允许跨租约归属(上一个订单的任务不能算到下一张订单上)。
LEASE_CLOCK_TOLERANCE = timedelta(seconds=5)
def active_fulfillment_lease(
db: Session,
account_id: int,
) -> AccountLease | None:
"""账号当前生效的履约租约;没有则返回 ``None``。"""
return (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(account_id),
AccountLease.status == "active",
AccountLease.purpose == "platform_fulfillment",
or_(
AccountLease.expires_at.is_(None),
AccountLease.expires_at > datetime.now(UTC),
),
)
.order_by(AccountLease.leased_at.desc(), AccountLease.id.desc())
.first()
)
def active_fulfillment_binding_task_id(
db: Session,
account_id: int,
) -> int | None:
"""账号当前租约对应的、仍可接收绑定证据的履约任务 id。
只用于任务创建入口主动打归属;``None`` 表示这是一次与履约无关的工作台操作。
"""
lease = active_fulfillment_lease(db, account_id)
if lease is None:
return None
task = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.lease_id == int(lease.id),
PlatformFulfillmentTask.account_id == int(account_id),
PlatformFulfillmentTask.scope == "elite",
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled", "manual_required")
),
PlatformFulfillmentTask.binding_status.in_(BINDING_LINKABLE_STATUSES),
)
.order_by(
PlatformFulfillmentTask.updated_at.desc(),
PlatformFulfillmentTask.id.desc(),
)
.first()
)
return int(task.id) if task is not None else None
def fulfillment_lease_for_task(
db: Session,
task: PlatformFulfillmentTask,
) -> AccountLease | None:
"""订单自己的租约(不按账号重新查,避免订单换号后拿到别的账号租约)。"""
if not task.lease_id:
return None
return db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first()
def lease_is_active(lease: AccountLease | None) -> bool:
if lease is None or lease.status != "active":
return False
expires_at = lease.expires_at
return not (
isinstance(expires_at, datetime) and expires_at <= datetime.now(UTC)
)
def source_created_within_lease(
lease: AccountLease | None,
source: DouyuTask | None,
) -> bool:
"""任务是否创建于本次租约期间。
这是防止「上一个订单的迟到任务结算当前订单」的硬约束。
"""
if lease is None or source is None:
return False
created_at = source.created_at
leased_at = lease.leased_at
if not isinstance(created_at, datetime) or not isinstance(leased_at, datetime):
return False
return created_at >= leased_at - LEASE_CLOCK_TOLERANCE
def normalize_role_name(value: object) -> str:
return str(value or "").strip().casefold()
def role_names_match(left: object, right: object) -> bool:
left_key = normalize_role_name(left)
right_key = normalize_role_name(right)
return bool(left_key) and left_key == right_key
__all__ = [
"BINDING_LINKABLE_STATUSES",
"BINDING_TASK_TYPES",
"LEASE_CLOCK_TOLERANCE",
"active_fulfillment_binding_task_id",
"active_fulfillment_lease",
"fulfillment_lease_for_task",
"lease_is_active",
"normalize_role_name",
"role_names_match",
"source_created_within_lease",
]
+15 -1
View File
@@ -15,6 +15,7 @@ from core.douyu.cookie_utils import cookie_value
from ..models import Account, DouyuConfig, DouyuTask
from . import account_query_filters as account_filters
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
from .binding_ownership import BINDING_TASK_TYPES, active_fulfillment_binding_task_id
from .douyu_binding import resolve_douyu_binding
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
@@ -370,8 +371,21 @@ def create_douyu_planned_tasks(
batch_id = uuid.uuid4().hex[:12]
payload = payload or {}
recharge_requested_at = datetime.now(UTC)
auto_link_binding = (
platform_task_id is None
and handbook_scope == "elite"
and task_type in BINDING_TASK_TYPES
)
task_rows: list[tuple[DouyuTask, Account]] = []
for account in accounts:
# 已租给履约订单的账号:运营从精英宝典工作台发起的绑码/确认任务在
# 创建时就写入订单归属,后续只认任务自己的 platform_task_id,不猜。
linked_platform_task_id = platform_task_id
if auto_link_binding:
linked_platform_task_id = active_fulfillment_binding_task_id(
db,
account.id,
)
task = DouyuTask(
batch_id=batch_id,
account_id=account.id,
@@ -382,7 +396,7 @@ def create_douyu_planned_tasks(
message="任务已创建,等待执行",
result={"payload": payload} if payload else None,
created_by=created_by,
platform_task_id=platform_task_id,
platform_task_id=linked_platform_task_id,
recharge_channel=recharge_channel,
recharge_amount=recharge_amount,
recharge_requested_at=(
File diff suppressed because it is too large Load Diff
@@ -134,6 +134,8 @@ const EVENT_LABELS: Record<string, string> = {
binding_pending_task_linked: '关联最新待确认角色',
binding_pending_observation_superseded: '旧待确认角色已被最新绑定替换',
binding_observation_confirmed: '账号观测确认角色绑定',
binding_confirmed: '履约绑定已确认',
binding_sync_rejected: '忽略不匹配的绑定证据',
eligibility_check_failed: '兑换资格查询失败',
eligibility_auto_refresh_failed: '自动刷新兑换资格失败',
exchange_eligibility_checked: '刷新兑换资格',
@@ -357,6 +359,19 @@ function eventDescription(event: { eventType: string; detail: Record<string, unk
if (event.eventType === 'binding_pending_observation_superseded') {
return `原待确认角色 ${String(detail.pendingRoleName || '-')} 已被当前绑定 ${String(detail.observedRoleName || '-')} 替换`;
}
if (event.eventType === 'binding_confirmed') {
const channel = String(detail.confirmedChannel || '');
return `已确认订单角色 ${String(detail.confirmedRoleName || '-')}${channel ? `(${channel})` : ''}`;
}
if (event.eventType === 'binding_sync_rejected') {
const reason = String(detail.reason || '');
if (reason === 'target_mismatch') {
return `确认角色 ${String(detail.confirmedRoleName || '-')} 与订单目标 ${String(detail.targetRoleName || '-')} 不一致,未结算`;
}
if (reason === 'source_outside_lease') return '账号绑定任务创建于本单租约之前,已忽略';
if (reason === 'missing_target') return '本单没有待确认角色,账号确认任务未结算';
return '该绑定任务不属于当前订单,已忽略';
}
if (event.eventType === 'task_created') return '订单已进入直播账号履约工作台';
return '履约状态已更新';
}