修复斗鱼同步与履约历史游标超时(迁移189)

This commit is contained in:
yml
2026-11-28 21:23:24 +08:00
parent 0094043f8a
commit ff2777a678
5 changed files with 158 additions and 7 deletions
@@ -0,0 +1,22 @@
-- 189_fulfillment_cursor_indexes.sql
--
-- carrier-dispatch 历史模式按 order_item_id 游标升序推进,同时保留自动化起算时间。
-- 188 的 created_at 优先索引适合 fresh 模式,但不适合历史游标;补 order_item_id 优先索引。
CREATE INDEX IF NOT EXISTS idx_fulfillments_assigned_carrier_cursor
ON fulfillments (order_item_id, created_at)
WHERE status = 'assigned'
AND channel IN ('affiliate_dash', 'work_order');
COMMENT ON INDEX idx_fulfillments_assigned_carrier_cursor IS
'carrier-dispatch 历史游标:按 order_item_id 推进并过滤自动化起算时间';
CREATE INDEX IF NOT EXISTS idx_fulfillments_assigned_manual_cursor
ON fulfillments (order_item_id, created_at)
WHERE status = 'assigned'
AND channel = 'manual';
COMMENT ON INDEX idx_fulfillments_assigned_manual_cursor IS
'人工履约历史游标:按 order_item_id 推进并过滤自动化起算时间';
ANALYZE fulfillments;
@@ -373,7 +373,10 @@ async function materializeDouyuFulfillmentTasks(input: {
? ` ? `
FROM order_items oi FROM order_items oi
JOIN orders o ON o.id = oi.order_id JOIN orders o ON o.id = oi.order_id
JOIN fulfillments f ON f.order_item_id = oi.id JOIN fulfillments f
ON f.order_item_id = oi.id
AND f.channel = 'manual'
AND f.status IN ('assigned', 'processing', 'completed')
` `
: ` : `
FROM orders o FROM orders o
@@ -410,8 +413,6 @@ async function materializeDouyuFulfillmentTasks(input: {
${candidateSourceSql} ${candidateSourceSql}
LEFT JOIN douyu_fulfillment_tasks existing ON existing.order_item_id = oi.id LEFT JOIN douyu_fulfillment_tasks existing ON existing.order_item_id = oi.id
WHERE f.fulfillment_config_id = ANY($1::bigint[]) WHERE f.fulfillment_config_id = ANY($1::bigint[])
AND f.channel = 'manual'
AND f.status IN ('assigned', 'processing', 'completed')
AND COALESCE(o.paid_at, o.created_at) >= ( AND COALESCE(o.paid_at, o.created_at) >= (
SELECT order_match_started_at SELECT order_match_started_at
FROM douyu_fulfillment_settings FROM douyu_fulfillment_settings
@@ -303,3 +303,101 @@ test(
} }
}, },
) )
test(
'宽范围立即同步按最近订单物化斗鱼任务,不引用候选子查询未投影的履约字段',
{ skip: !TEST_DATABASE_URL ? '未设置 DOUYU_FULFILLMENT_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
const { closeDb, query } = await import('../../db/client.js')
const { backfillDouyuFulfillmentTasks } = await import('./douyu-fulfillment-service.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const platformOrderId = `IT-DOUYU-SYNC-${suffix}`
const internalSku = `集成斗鱼立即同步-${suffix}`
let orderId = 0
let configId = 0
try {
const config = await query<{ id: number }>(
`INSERT INTO manual_fulfillment_configs (
sku_key, platform_key, credit_quantity, cost_mode, enabled,
douyu_fulfillment_enabled, created_at, updated_at
) VALUES ($1, 'nanhang', 1, 'fixed', TRUE, TRUE, NOW(), NOW())
RETURNING id`,
[internalSku],
)
configId = Number(config.rows[0]!.id)
const order = await query<{ id: number }>(
`INSERT INTO orders (
provider, platform, shop_id, shop_name, platform_order_id,
order_status, pay_status, total_amount, paid_at, created_at, updated_at
) VALUES (
'integration-test', 'integration-test', $1, '集成斗鱼立即同步测试店', $2,
'paid', 'paid', 9900, NOW(), NOW(), NOW()
) RETURNING id`,
[`shop-${suffix}`, platformOrderId],
)
orderId = Number(order.rows[0]!.id)
const item = await query<{ id: number }>(
`INSERT INTO order_items (
order_id, sku_code, sku_name, quantity, spec_json,
revenue_amount_fen, revenue_basis, created_at, updated_at
) VALUES (
$1, $2, $2, 1, $3::jsonb, 9900, 'order_total', NOW(), NOW()
) RETURNING id`,
[orderId, `sku-sync-${suffix}`, JSON.stringify({ skuNick: internalSku })],
)
const orderItemId = Number(item.rows[0]!.id)
const fulfillment = await query(
`UPDATE fulfillments
SET internal_sku = $2,
route_status = 'configured',
channel = 'manual',
carrier_status = 'ready',
status = 'assigned',
source = 'integration_test',
fulfillment_config_id = $3,
updated_at = NOW()
WHERE order_item_id = $1`,
[orderItemId, internalSku, configId],
)
assert.equal(fulfillment.rowCount, 1)
// 不传 orderItemIds,强制走“立即同步”的最近订单宽范围分支。
const synced = await backfillDouyuFulfillmentTasks({
limit: 100,
createdAfter: new Date(Date.now() - 60 * 60_000).toISOString(),
})
assert.ok(synced.created >= 1)
const task = await query<{ status: string }>(
`SELECT status
FROM douyu_fulfillment_tasks
WHERE order_item_id = $1`,
[orderItemId],
)
assert.deepEqual(
task.rows.map((row) => row.status),
['waiting_profile'],
)
} finally {
await query(
`DELETE FROM integration_outbox
WHERE payload_json->'data'->>'platformOrderId' = $1`,
[platformOrderId],
).catch(() => undefined)
if (orderId > 0) {
await query('DELETE FROM orders WHERE id = $1', [orderId]).catch(() => undefined)
}
if (configId > 0) {
await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId]).catch(
() => undefined,
)
}
await closeDb()
}
},
)
@@ -141,9 +141,10 @@ test('新单快速推进只处理 actionable 履约桶', () => {
assert.ok(!advance.includes('includeNonActionable')) assert.ok(!advance.includes('includeNonActionable'))
}) })
test('热路径数据库优化迁移 187/188 与对应仓储查询守卫生效', () => { test('热路径数据库优化迁移 187/188/189 与对应仓储查询守卫生效', () => {
const migration187 = source('../../db/migrations/187_order_site_hotpath_optimization.sql') const migration187 = source('../../db/migrations/187_order_site_hotpath_optimization.sql')
const migration188 = source('../../db/migrations/188_order_site_worker_fulfillment_hotpaths.sql') const migration188 = source('../../db/migrations/188_order_site_worker_fulfillment_hotpaths.sql')
const migration189 = source('../../db/migrations/189_fulfillment_cursor_indexes.sql')
const taskRepo = source('../../repositories/task-repo.ts') const taskRepo = source('../../repositories/task-repo.ts')
const affiliateFallback = source('./affiliate-fallback-service.ts') const affiliateFallback = source('./affiliate-fallback-service.ts')
const financeJobs = source('../scheduler/finance-pipeline-jobs.ts') const financeJobs = source('../scheduler/finance-pipeline-jobs.ts')
@@ -165,6 +166,13 @@ test('热路径数据库优化迁移 187/188 与对应仓储查询守卫生效',
assert.ok(migration188.includes('idx_orders_effective_ordered_at_cover')) assert.ok(migration188.includes('idx_orders_effective_ordered_at_cover'))
assert.ok(migration188.includes('work_order_shop_name_projection')) assert.ok(migration188.includes('work_order_shop_name_projection'))
assert.ok(migration188.includes('eligible.queue_bucket =')) assert.ok(migration188.includes('eligible.queue_bucket ='))
assert.ok(migration189.includes('idx_fulfillments_assigned_carrier_cursor'))
assert.ok(migration189.includes('idx_fulfillments_assigned_manual_cursor'))
assert.ok(
migration189.includes(
"ON fulfillments (order_item_id, created_at)\n WHERE status = 'assigned'",
),
)
const jsonLookup = taskRepo.slice( const jsonLookup = taskRepo.slice(
taskRepo.indexOf('async function findExecutorTaskByJsonKeys'), taskRepo.indexOf('async function findExecutorTaskByJsonKeys'),
@@ -185,6 +193,14 @@ test('热路径数据库优化迁移 187/188 与对应仓储查询守卫生效',
douyuService.indexOf('async function materializeDouyuFulfillmentTasks'), douyuService.indexOf('async function materializeDouyuFulfillmentTasks'),
douyuService.indexOf('async function loadPendingDouyuOrderHints'), douyuService.indexOf('async function loadPendingDouyuOrderHints'),
) )
const douyuCandidateSource = douyuMaterializeBody.slice(
douyuMaterializeBody.indexOf('const candidateSourceSql'),
douyuMaterializeBody.indexOf('const result = await query'),
)
const douyuCandidateQuery = douyuMaterializeBody.slice(
douyuMaterializeBody.indexOf('WITH candidates AS'),
douyuMaterializeBody.indexOf('upserted AS'),
)
const carrierReconciliation = source('./carrier-reconciliation-service.ts') const carrierReconciliation = source('./carrier-reconciliation-service.ts')
assert.ok(carrierDispatchBody.includes('WITH candidate_page AS')) assert.ok(carrierDispatchBody.includes('WITH candidate_page AS'))
assert.ok(carrierDispatchBody.includes('scanned_max_id')) assert.ok(carrierDispatchBody.includes('scanned_max_id'))
@@ -196,6 +212,13 @@ test('热路径数据库优化迁移 187/188 与对应仓储查询守卫生效',
assert.ok(douyuMaterializeBody.includes('CROSS JOIN LATERAL')) assert.ok(douyuMaterializeBody.includes('CROSS JOIN LATERAL'))
assert.ok(douyuMaterializeBody.includes('COALESCE(o.paid_at, o.created_at) DESC')) assert.ok(douyuMaterializeBody.includes('COALESCE(o.paid_at, o.created_at) DESC'))
assert.ok(!douyuMaterializeBody.includes('JOIN manual_fulfillment_configs cfg')) assert.ok(!douyuMaterializeBody.includes('JOIN manual_fulfillment_configs cfg'))
assert.ok(
douyuCandidateSource.includes(
"JOIN fulfillments f\n ON f.order_item_id = oi.id\n AND f.channel = 'manual'",
),
)
assert.ok(!douyuCandidateQuery.includes('f.channel'))
assert.ok(!douyuCandidateQuery.includes('f.status'))
assert.ok(carrierReconciliation.includes('sku.internal_sku_key = oi.internal_sku')) assert.ok(carrierReconciliation.includes('sku.internal_sku_key = oi.internal_sku'))
assert.ok(!carrierReconciliation.includes('resolve_internal_sku(\\n oi.manual_sku_key')) assert.ok(!carrierReconciliation.includes('resolve_internal_sku(\\n oi.manual_sku_key'))
assert.ok( assert.ok(
@@ -11,8 +11,8 @@ updated_at: 2026-11-28
> 状态:**唯一权威文档**。 > 状态:**唯一权威文档**。
> 最后校准:2026-11-28。 > 最后校准:2026-11-28。
> 生产基线:迁移 `187`(2026-11-28 部署验证)。 > 生产基线:迁移 `188`(2026-11-28 部署验证)。
> 开发基线:迁移 `188`(履约/工单热路径二次收敛,未部署)。 > 开发基线:迁移 `189`(履约历史游标索引,未部署)。
> >
> 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现, > 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现,
> 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。 > 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。
@@ -1263,7 +1263,7 @@ docs/archive/
## 十三、当前下一步 ## 十三、当前下一步
截至 2026-11-28,生产基线为 `187`,当前开发基线为 `188`。迁移 `152` 保护订单来源快照, 截至 2026-11-28,生产基线为 `188`,当前开发基线为 `189`。迁移 `152` 保护订单来源快照,
迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置; 迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置;
迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、 迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、
任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。 任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。
@@ -1308,6 +1308,13 @@ pending 角色快照、`role_identity_source` 与 `verification_basis`。
触发器;并重写 `v_fulfillment_queue`,先判桶再对满足条件的 pending 记录探测活跃任务/工单。 触发器;并重写 `v_fulfillment_queue`,先判桶再对满足条件的 pending 记录探测活跃任务/工单。
查询侧同步改为使用 `fulfillments.internal_sku` 权威字段,避免在 500–5000 行候选页上重复调用 查询侧同步改为使用 `fulfillments.internal_sku` 权威字段,避免在 500–5000 行候选页上重复调用
`resolve_internal_sku()`;打手可见工单集合改为数组索引探测,避免先把 `work_orders` 全表哈希。 `resolve_internal_sku()`;打手可见工单集合改为数组索引探测,避免先把 `work_orders` 全表哈希。
生产部署后只读验证确认 `188` 已应用,店铺下拉、打手可见集和 `carrier_dispatch` 新单窗口的
实测延迟均显著下降;同时发现斗鱼“立即同步”宽范围分支在外层引用了 lateral 未投影的
`f.channel / f.status`,以及 `carrier_dispatch` 历史模式同时按 `order_item_id` 游标和
`created_at` 起算时间过滤时无法利用 `created_at` 优先索引。
迁移 `189` 为已分配自动履约和人工履约补充 `(order_item_id, created_at)` 部分索引,使历史游标
可以先按 `order_item_id` 有界推进再过滤起算时间;斗鱼宽范围同步把渠道和状态过滤下沉到
`fulfillments` lateral 内部,外层只引用已投影字段,并由真实 PostgreSQL 集成测试覆盖。
迁移 `169` 增加客户游戏角色资料字段(`customer_game_role_name` / `customer_game_role_id` / 迁移 `169` 增加客户游戏角色资料字段(`customer_game_role_name` / `customer_game_role_id` /
`customer_game_server_zone`),并允许从工单素材回退合并;当前客户资料要求角色名、UID 和区服三项齐全, `customer_game_server_zone`),并允许从工单素材回退合并;当前客户资料要求角色名、UID 和区服三项齐全,
其中 `customer_game_role_id` 只校验非空,不校验格式。客户页流程收敛为 其中 `customer_game_role_id` 只校验非空,不校验格式。客户页流程收敛为