perf(finance): 管道增量索引与异常批量入队
生产副本 42 万单压测发现: - carrier_missing 查询在 26 万条上 15s 超时 → 改 anti-join,异常去重改批量 - 缺成本异常逐条 3 条 SQL,12 万人工单会跑几十分钟 → 按 scope 批量入队 - 新增 117/118 部分索引,成本快照/人工挂配置/载体检查走 id 顺序扫描 - 人工挂配置查询改为按配置 SKU 数组过滤,避免全量人工单排序
This commit is contained in:
@@ -76,6 +76,95 @@ export async function upsertAggregatedException(input: UpsertExceptionInput): Pr
|
||||
)
|
||||
}
|
||||
|
||||
export type AggregatedExceptionEntry = {
|
||||
reason: string
|
||||
scopeKey: string
|
||||
orderItemId: number
|
||||
detail?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量入队:同一批内按 scope_key 聚合,避免逐条 3 条 SQL(12 万人工单会跑几十分钟)。
|
||||
*/
|
||||
export async function upsertAggregatedExceptionsBatch(
|
||||
entries: AggregatedExceptionEntry[],
|
||||
): Promise<number> {
|
||||
const unique = new Map<string, AggregatedExceptionEntry>()
|
||||
for (const entry of entries) {
|
||||
if (!Number.isInteger(entry.orderItemId) || entry.orderItemId <= 0) continue
|
||||
unique.set(`${entry.scopeKey}|${entry.orderItemId}`, entry)
|
||||
}
|
||||
const items = [...unique.values()]
|
||||
if (items.length === 0) return 0
|
||||
|
||||
// ON CONFLICT DO UPDATE 不允许同一条语句内出现重复 scope_key,
|
||||
// 聚合异常多个订单项共享一个 scope_key,插入阶段只保留每个 scope 的首条。
|
||||
const scopeFirst = new Map<string, AggregatedExceptionEntry>()
|
||||
for (const entry of items) {
|
||||
if (!scopeFirst.has(entry.scopeKey)) scopeFirst.set(entry.scopeKey, entry)
|
||||
}
|
||||
const heads = [...scopeFirst.values()]
|
||||
|
||||
const now = nowIso()
|
||||
const inserted = await query<{ id: number; scope_key: string }>(
|
||||
`
|
||||
INSERT INTO cost_exceptions (
|
||||
subject_type, subject_id, order_item_id, reason, status, detail_json,
|
||||
scope_key, item_count, first_seen_at, last_seen_at, created_at
|
||||
)
|
||||
SELECT 'order_item', s.order_item_id, s.order_item_id, s.reason, 'open', s.detail::jsonb,
|
||||
s.scope_key, 1, $4, $4, $4
|
||||
FROM unnest($1::bigint[], $2::text[], $3::text[], $5::text[]) AS s(order_item_id, reason, scope_key, detail)
|
||||
ON CONFLICT (scope_key) WHERE status <> 'resolved'
|
||||
DO UPDATE SET
|
||||
last_seen_at = EXCLUDED.last_seen_at,
|
||||
detail_json = EXCLUDED.detail_json
|
||||
RETURNING id, scope_key
|
||||
`,
|
||||
[
|
||||
heads.map((entry) => entry.orderItemId),
|
||||
heads.map((entry) => entry.reason),
|
||||
heads.map((entry) => entry.scopeKey),
|
||||
now,
|
||||
heads.map((entry) => JSON.stringify(entry.detail || {})),
|
||||
],
|
||||
)
|
||||
|
||||
const idByScope = new Map<string, number>()
|
||||
for (const row of inserted.rows) idByScope.set(row.scope_key, Number(row.id))
|
||||
|
||||
const links = items
|
||||
.map((entry) => ({
|
||||
exceptionId: idByScope.get(entry.scopeKey),
|
||||
orderItemId: entry.orderItemId,
|
||||
}))
|
||||
.filter((row): row is { exceptionId: number; orderItemId: number } => Boolean(row.exceptionId))
|
||||
if (links.length === 0) return 0
|
||||
|
||||
await query(
|
||||
`
|
||||
INSERT INTO cost_exception_items (exception_id, order_item_id, created_at)
|
||||
SELECT input.exception_id, input.order_item_id, $3
|
||||
FROM unnest($1::bigint[], $2::bigint[]) AS input(exception_id, order_item_id)
|
||||
ON CONFLICT (exception_id, order_item_id) DO NOTHING
|
||||
`,
|
||||
[links.map((row) => row.exceptionId), links.map((row) => row.orderItemId), now],
|
||||
)
|
||||
|
||||
const exceptionIds = [...new Set(links.map((row) => row.exceptionId))]
|
||||
await query(
|
||||
`
|
||||
UPDATE cost_exceptions ce
|
||||
SET item_count = (
|
||||
SELECT COUNT(*)::int FROM cost_exception_items i WHERE i.exception_id = ce.id
|
||||
)
|
||||
WHERE ce.id = ANY($1::bigint[])
|
||||
`,
|
||||
[exceptionIds],
|
||||
)
|
||||
return links.length
|
||||
}
|
||||
|
||||
/** 问题已解决:关闭问题头并清空明细。 */
|
||||
export async function resolveAggregatedException(scopeKey: string): Promise<number> {
|
||||
const now = nowIso()
|
||||
|
||||
@@ -2,7 +2,11 @@ import { query, withTransaction } from '../../db/client.js'
|
||||
import type { PoolClient } from 'pg'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { GENERIC_COST_MODELS } from './cost-center-constants.js'
|
||||
import { resolveExceptionsForItems, upsertAggregatedException } from './cost-exception-service.js'
|
||||
import {
|
||||
resolveExceptionsForItems,
|
||||
upsertAggregatedExceptionsBatch,
|
||||
type AggregatedExceptionEntry,
|
||||
} from './cost-exception-service.js'
|
||||
import { readWatermarkItemId } from '../watermark-store.js'
|
||||
|
||||
/**
|
||||
@@ -366,6 +370,7 @@ async function processCostRows(
|
||||
const openMissing = await loadOpenMissingItems(rows.map((row) => row.id))
|
||||
const inserts: Array<{ item: CostCandidateItem; resolution: NonNullable<CostResolution> }> = []
|
||||
const supersedeIds: number[] = []
|
||||
const missingEntries: AggregatedExceptionEntry[] = []
|
||||
|
||||
for (const item of rows) {
|
||||
const desired: Array<NonNullable<CostResolution>> = []
|
||||
@@ -379,10 +384,10 @@ async function processCostRows(
|
||||
result.missing += 1
|
||||
// 已在队列里的缺失项不再重复写三条 SQL,等价格补齐后自然收口。
|
||||
if (!openMissing.has(Number(item.id))) {
|
||||
await upsertAggregatedException({
|
||||
missingEntries.push({
|
||||
reason: 'cost_missing',
|
||||
scopeKey: `cost_missing|${item.fulfillment_channel}|${item.canonical_product_id}|${item.work_product_rule_id ?? '-'}`,
|
||||
orderItemId: item.id,
|
||||
orderItemId: Number(item.id),
|
||||
detail: { channel: item.fulfillment_channel },
|
||||
})
|
||||
}
|
||||
@@ -424,6 +429,9 @@ async function processCostRows(
|
||||
}
|
||||
}
|
||||
|
||||
if (missingEntries.length > 0) {
|
||||
await upsertAggregatedExceptionsBatch(missingEntries)
|
||||
}
|
||||
if (supersedeIds.length === 0 && inserts.length === 0) return
|
||||
// 替换与写入放在同一事务里,避免事实任务读到「旧行已过期、新行未写入」的空窗。
|
||||
const created = await withTransaction(async (client) => {
|
||||
|
||||
Reference in New Issue
Block a user