diff --git a/app/schedule/sync_finished_wave_batch.js b/app/schedule/sync_finished_wave_batch.js index 724c65f..0723abd 100644 --- a/app/schedule/sync_finished_wave_batch.js +++ b/app/schedule/sync_finished_wave_batch.js @@ -107,6 +107,9 @@ module.exports = { empty_count: result ? result.empty_count : 0, closed_count: result ? result.closed_count : 0, pending_confirm_count: result ? result.pending_confirm_count : 0, + unbound_count: result ? result.unbound_count : 0, + misread_count: result ? result.misread_count : 0, + probe_failed_count: result ? result.probe_failed_count : 0, warehouse_ids: result ? result.warehouse_ids : [], closed_waves: result ? result.closed_waves : [], }; @@ -115,7 +118,10 @@ module.exports = { ctx.logger.info( `[sync-finished-wave-batch] 本轮完成 closed=${result ? result.closed_count : 0} candidate=${result ? result.candidate_count : 0}` - + ` pendingConfirm=${result ? result.pending_confirm_count : 0} warehouses=${result ? result.warehouse_ids.length : 0}` + + ` pendingConfirm=${result ? result.pending_confirm_count : 0}` + + ` unbound=${result ? result.unbound_count : 0} misread=${result ? result.misread_count : 0}` + + ` probeFailed=${result ? result.probe_failed_count : 0}` + + ` warehouses=${result ? result.warehouse_ids.length : 0}` ); }, }; diff --git a/app/service/systems/wave_batch_closure.js b/app/service/systems/wave_batch_closure.js index 2ff5bed..0ac0a47 100644 --- a/app/service/systems/wave_batch_closure.js +++ b/app/service/systems/wave_batch_closure.js @@ -7,8 +7,14 @@ const MainService = require('../main'); const ACTIVE_WAVE_STATUSES = [ 0, 1 ]; // 终结态:复核完成(与 recheckOrder 复核完成路径一致,使波次从 batchList 中自然消失) const CLOSED_WAVE_STATUS = 5; -// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判 -const WAVE_MIN_AGE_MINUTES = 5; +// 创建不足该分钟数的波次不参与自动终结,避免与创建事务并发误判。 +// 2026-10-09 事故:PDA 策略抓取建波(B2026100900660,07:04:04)后订单绑定延迟至 07:16:37 +// (窗口约 12 分钟),5 分钟门槛不够,波次在建波与订单绑定之间被误判为空而终结。 +// 提至 30 分钟,覆盖正常建波+绑定流程(含慢事务、请求重试、流程中断后补做)的窗口。 +const WAVE_MIN_AGE_MINUTES = 30; +// 判空抽样核对条数:订单表判空但索引表仍有行的波次,按索引指向的订单抽样核对订单表 +// 是否存在这些行,用于识别「读偏」(分表重建/复制期间订单表读到半成品空表)。 +const WAVE_INDEX_PROBE_LIMIT = 50; // 单次 SQL IN 列表的波次数量上限 const WAVE_ID_BATCH_SIZE = 500; // 判空二次确认:同一波次需连续两轮(间隔不小于该毫秒数)都判定为空,才允许终结。 @@ -92,7 +98,7 @@ class WaveBatchClosureService extends MainService { FROM wms_wave_batch WHERE wave_status IN (:waveStatuses) AND total_orders > 0 - AND create_time < (NOW() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`, + AND create_time < (UTC_TIMESTAMP() - INTERVAL ${WAVE_MIN_AGE_MINUTES} MINUTE)`, { replacements: { waveStatuses: ACTIVE_WAVE_STATUSES }, type: ctx.model.QueryTypes.SELECT, @@ -121,6 +127,9 @@ class WaveBatchClosureService extends MainService { const warehouseIds = Array.from(warehouseWaveMap.keys()); const emptyWaves = []; + const unboundWaves = []; + const misreadWaves = []; + const probeFailedWaves = []; for (const warehouseId of warehouseIds) { const waves = warehouseWaveMap.get(warehouseId); @@ -170,9 +179,91 @@ class WaveBatchClosureService extends MainService { continue; } - const finishedWaves = waves.filter(item => !existingWaveIds.has(item.waveId)); - if (finishedWaves.length > 0) { - emptyWaves.push(...finishedWaves); + // 交叉校验波次索引表:订单绑定与索引重建同事务,索引行是「订单曾绑定过」的强信号。 + // 订单表判空但索引非空 → 可能是正常离表(发货迁移不删索引),也可能是读偏, + // 由后续抽样核对区分;订单表与索引表双空 → 订单从未绑定(建波中间态)或全量清空异常。 + const indexedWaveIds = new Set(); + let indexQueryFailed = false; + for (let offset = 0; offset < waves.length; offset += WAVE_ID_BATCH_SIZE) { + const batchWaves = waves.slice(offset, offset + WAVE_ID_BATCH_SIZE); + const batchWaveIds = batchWaves.map(item => item.waveId); + try { + const indexRows = await ctx.model.query( + `SELECT DISTINCT wave_id + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds)`, + { + replacements: { + warehouseId, + waveIds: batchWaveIds, + }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + for (const row of (Array.isArray(indexRows) ? indexRows : [])) { + const waveId = Number(row && row.wave_id || 0); + if (Number.isInteger(waveId) && waveId > 0) { + indexedWaveIds.add(waveId); + } + } + } catch (error) { + indexQueryFailed = true; + ctx.logger.warn(`[wave-batch-closure] 查询仓库 ${warehouseId} 波次索引表失败,跳过该仓库: ${error.message}`); + break; + } + } + + if (indexQueryFailed) { + continue; + } + + // 分类判定 + for (const item of waves) { + const { waveId } = item; + if (existingWaveIds.has(waveId)) { + continue; // 待处理表仍有订单,正常活动波次 + } + if (!indexedWaveIds.has(waveId)) { + // 订单表与索引表双空:订单从未绑定(建波与绑定之间的中间态)或全量清空异常, + // 一律不自动终结(宁可漏关,不可误关),交由人工/后续流程处理。 + unboundWaves.push(item); + continue; + } + + // 订单表空但索引仍有行:抽样核对索引指向的订单是否真的已离开订单表。 + // 注意 MySQL 不支持 IN (SELECT ... LIMIT n),此处用 JOIN 派生表(FROM 子句 LIMIT 合法)。 + let probeCount = null; + try { + const probeRows = await ctx.model.query( + `SELECT COUNT(*) AS probe_count + FROM ${currentTableName} o + INNER JOIN ( + SELECT order_id + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id = :waveId + LIMIT ${WAVE_INDEX_PROBE_LIMIT} + ) idx ON idx.order_id = o.id`, + { + replacements: { warehouseId, waveId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + probeCount = Number(Array.isArray(probeRows) && probeRows[0] && probeRows[0].probe_count || 0); + } catch (error) { + probeFailedWaves.push(item); + ctx.logger.warn(`[wave-batch-closure] 仓库 ${warehouseId} 波次 ${waveId} 索引抽样核对失败,本轮不终结: ${error.message}`); + continue; + } + + if (Number.isFinite(probeCount) && probeCount > 0) { + // 索引指向的订单仍存在于待处理表:判空属于读偏(分表重建/复制等),不终结 + misreadWaves.push(item); + } else { + emptyWaves.push(item); + } } } @@ -219,8 +310,8 @@ class WaveBatchClosureService extends MainService { `UPDATE wms_wave_batch SET wave_status = :closedStatus, processed_orders = total_orders, - check_time = NOW(), - update_time = NOW() + check_time = UTC_TIMESTAMP(), + update_time = UTC_TIMESTAMP() WHERE wave_id IN (:waveIds) AND wave_status IN (:waveStatuses) AND total_orders > 0`, @@ -247,22 +338,52 @@ class WaveBatchClosureService extends MainService { pending_confirm_count: pendingConfirmWaves.length, pending_confirm_wave_ids: pendingConfirmWaves.map(item => item.waveId), empty_wave_ids: emptyWaves.map(item => item.waveId), + unbound_count: unboundWaves.length, + unbound_wave_ids: unboundWaves.map(item => item.waveId), + misread_count: misreadWaves.length, + misread_wave_ids: misreadWaves.map(item => item.waveId), + probe_failed_count: probeFailedWaves.length, + probe_failed_wave_ids: probeFailedWaves.map(item => item.waveId), warehouse_ids: warehouseIds, closed_waves: confirmedWaves, duration_ms: Date.now() - startedAt, }; - if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0) { + if (unboundWaves.length > 0) { + ctx.logger.warn( + `[wave-batch-closure] ${unboundWaves.length} 个波次订单表与索引表双空(疑似建波未完成或全量清空异常),` + + `不自动终结: ${formatWaveIdListForLog(unboundWaves.map(item => item.waveId))}` + ); + } + if (misreadWaves.length > 0) { + ctx.logger.warn( + `[wave-batch-closure] ${misreadWaves.length} 个波次判空与索引抽样核对不一致(疑似读偏),` + + `不自动终结: ${formatWaveIdListForLog(misreadWaves.map(item => item.waveId))}` + ); + } + + if (confirmedWaves.length > 0 || pendingConfirmWaves.length > 0 + || unboundWaves.length > 0 || misreadWaves.length > 0 || probeFailedWaves.length > 0) { const pendingSuffix = pendingConfirmWaves.length > 0 ? ` pendingWaves=${formatWaveIdListForLog(result.pending_confirm_wave_ids)}` : ''; const confirmedSuffix = confirmedWaveIds.length > 0 ? ` waves=${formatWaveIdListForLog(confirmedWaveIds)}` : ''; + const unboundSuffix = unboundWaves.length > 0 + ? ` unbound=${unboundWaves.length}` + : ''; + const misreadSuffix = misreadWaves.length > 0 + ? ` misread=${misreadWaves.length}` + : ''; + const probeFailedSuffix = probeFailedWaves.length > 0 + ? ` probeFailed=${probeFailedWaves.length}` + : ''; ctx.logger.info( `[wave-batch-closure] 波次终结结果 dryRun=${dryRun} candidate=${candidateCount}` + ` confirmed=${confirmedWaves.length} closedRows=${result.closed_count}` + ` pendingConfirm=${pendingConfirmWaves.length}${pendingSuffix}${confirmedSuffix}` + + `${unboundSuffix}${misreadSuffix}${probeFailedSuffix}` ); } diff --git a/test/app/service/systems/wave_batch_closure.test.js b/test/app/service/systems/wave_batch_closure.test.js new file mode 100644 index 0000000..018e023 --- /dev/null +++ b/test/app/service/systems/wave_batch_closure.test.js @@ -0,0 +1,399 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveBatchClosureService = require('../../../../app/service/systems/wave_batch_closure'); + +const CACHE_KEY = 'schedule:sync_finished_wave_batch:empty_confirm'; + +/** + * 构造波次自动终结测试上下文。 + * + * @param {Object} [options={}] 测试选项。 + * @param {Array} [options.candidateRows] 候选波次行。 + * @param {Array} [options.wavesWithOrders] 待处理表里仍有订单的波次ID。 + * @param {boolean} [options.queryShouldFail] 待处理表查询是否抛错。 + * @param {boolean} [options.cacheUnavailable] 是否禁用缓存(模拟 Redis 不可用)。 + * @param {Array} [options.wavesWithIndex] 波次索引表里有行的波次ID(默认全部候选, + * 模拟"订单离表但索引残留"的正常清理目标形态)。 + * @param {boolean} [options.indexQueryShouldFail] 波次索引表查询是否抛错。 + * @param {number} [options.probeCount] 索引抽样核对返回的订单表命中数(默认 0)。 + * @param {boolean} [options.probeShouldFail] 索引抽样核对查询是否抛错。 + * @return {{ service: Object, captures: Object, cacheStore: Map }} 测试对象。 + */ +function createHarness(options = {}) { + const { + candidateRows = [], + wavesWithOrders = [], + queryShouldFail = false, + cacheUnavailable = false, + wavesWithIndex = candidateRows.map(row => Number(row && row.wave_id || 0)).filter(waveId => waveId > 0), + indexQueryShouldFail = false, + probeCount = 0, + probeShouldFail = false, + } = options; + + const captures = { + sqlList: [], + updateWaveIdList: [], + updateReplacementList: [], + infoLogList: [], + warnLogList: [], + }; + const cacheStore = new Map(); + const wavesWithOrdersSet = new Set(wavesWithOrders); + const wavesWithIndexSet = new Set(wavesWithIndex); + + const app = { config: {} }; + if (!cacheUnavailable) { + app.getCacheAsync = async cacheKey => (cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null); + app.setCacheAsync = async (cacheKey, data) => { + cacheStore.set(cacheKey, data); + }; + } + + const ctx = { + app, + model: { + QueryTypes: { SELECT: 'SELECT', UPDATE: 'UPDATE' }, + OrderDeliveryFactory: { + generateTableName(warehouseId) { + return `wms_order_delivery_${warehouseId}`; + }, + }, + async query(sql, queryOptions = {}) { + const normalizedSql = String(sql || '').replace(/\s+/g, ' ').trim(); + const replacements = queryOptions.replacements || {}; + captures.sqlList.push(normalizedSql); + + if (/^UPDATE\s+wms_wave_batch/i.test(normalizedSql)) { + const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : []; + captures.updateWaveIdList.push(...waveIds); + captures.updateReplacementList.push(replacements); + // 真实 SQL 带 wave_status IN (0,1) 守卫:这里按"全部命中"模拟最理想情况 + return [ undefined, { affectedRows: waveIds.length }]; + } + + if (/SELECT DISTINCT wave_id[\s\S]*FROM\s+wms_order_wave_index/i.test(normalizedSql)) { + if (indexQueryShouldFail) { + throw new Error('mock wave index query failed'); + } + const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : []; + return waveIds + .filter(waveId => wavesWithIndexSet.has(waveId)) + .map(waveId => ({ wave_id: waveId })); + } + + if (/SELECT DISTINCT wave_id/i.test(normalizedSql)) { + if (queryShouldFail) { + throw new Error('mock order table query failed'); + } + const waveIds = Array.isArray(replacements.waveIds) ? replacements.waveIds : []; + return waveIds + .filter(waveId => wavesWithOrdersSet.has(waveId)) + .map(waveId => ({ wave_id: waveId })); + } + + if (/SELECT COUNT\(\*\) AS probe_count/i.test(normalizedSql)) { + if (probeShouldFail) { + throw new Error('mock probe query failed'); + } + return [{ probe_count: probeCount }]; + } + + if (/FROM\s+wms_wave_batch/i.test(normalizedSql)) { + return candidateRows; + } + + return []; + }, + }, + logger: { + info(message) { + captures.infoLogList.push(String(message)); + }, + warn(message) { + captures.warnLogList.push(String(message)); + }, + error() {}, + }, + }; + + return { + service: new WaveBatchClosureService(ctx), + captures, + cacheStore, + }; +} + +/** + * 生成候选波次行。 + * + * @param {number} waveId 波次ID。 + * @param {number} [warehouseId=1000028] 仓库ID。 + * @return {Object} 候选行。 + */ +function buildCandidate(waveId, warehouseId = 1000028) { + return { + wave_id: waveId, + wave_no: `B${waveId}`, + warehouse_id: warehouseId, + wave_status: 1, + total_orders: 20, + }; +} + +describe('test/app/service/systems/wave_batch_closure.test.js', () => { + it('首轮判空不终结,只登记待确认(避免瞬时空表误关)', async () => { + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(1777888535813505) ], + }); + + const result = await service.closeFinishedWaves(); + + assert.equal(result.empty_count, 1); + assert.equal(result.confirmed_count, 0); + assert.equal(result.closed_count, 0); + assert.equal(result.pending_confirm_count, 1); + assert.deepEqual(result.pending_confirm_wave_ids, [ 1777888535813505 ]); + assert.equal(captures.updateWaveIdList.length, 0); + assert.deepEqual(cacheStore.get(CACHE_KEY).waveIds, [ 1777888535813505 ]); + }); + + it('连续两轮判空且间隔达标后才终结(受 wave_status/total_orders 守卫)', async () => { + const waveId = 1777888535813505; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + }); + // 预置上一轮判空结果(轮次时间早于确认间隔) + cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] }); + + const result = await service.closeFinishedWaves(); + + assert.equal(result.confirmed_count, 1); + assert.equal(result.closed_count, 1); + assert.equal(result.pending_confirm_count, 0); + assert.deepEqual(captures.updateWaveIdList, [ waveId ]); + assert.deepEqual(result.closed_waves, [{ + waveId, + waveNo: `B${waveId}`, + warehouseId: 1000028, + }]); + + const updateSql = captures.sqlList.find(sql => /^UPDATE\s+wms_wave_batch/i.test(sql)); + assert.ok(updateSql, '应执行终结 UPDATE'); + assert.ok(/wave_status IN \(:waveStatuses\)/i.test(updateSql), '终结 UPDATE 需带 wave_status 守卫'); + assert.ok(/total_orders > 0/i.test(updateSql), '终结 UPDATE 需带 total_orders > 0 守卫'); + assert.deepEqual(captures.updateReplacementList[0].waveStatuses, [ 0, 1 ]); + assert.equal(captures.updateReplacementList[0].closedStatus, 5); + }); + + it('上一轮判空但本轮订单已回来时不终结', async () => { + const waveId = 1777888535813505; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithOrders: [ waveId ], + }); + cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] }); + + const result = await service.closeFinishedWaves(); + + assert.equal(result.empty_count, 0); + assert.equal(result.confirmed_count, 0); + assert.equal(captures.updateWaveIdList.length, 0); + }); + + it('两次判空间隔不足时不终结,且不刷新首轮时间(避免调度过密饿死确认)', async () => { + const waveId = 1777888535813505; + const staleRoundAt = Date.now() - 5000; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + }); + cacheStore.set(CACHE_KEY, { roundAt: staleRoundAt, waveIds: [ waveId ] }); + + const result = await service.closeFinishedWaves(); + + assert.equal(result.confirmed_count, 0); + assert.equal(result.pending_confirm_count, 1); + assert.equal(captures.updateWaveIdList.length, 0); + assert.equal(cacheStore.get(CACHE_KEY).roundAt, staleRoundAt); + }); + + it('confirmMinIntervalMs=0 时跳过二次确认、首轮即终结(兼容/手动强制口径)', async () => { + const waveId = 1777888535813505; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.confirmed_count, 1); + assert.equal(result.closed_count, 1); + assert.deepEqual(captures.updateWaveIdList, [ waveId ]); + }); + + it('dryRun 只盘点不写库、不读写确认状态', async () => { + const waveId = 1777888535813505; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + }); + + const result = await service.closeFinishedWaves({ dryRun: true }); + + assert.equal(result.dryRun, true); + assert.equal(result.empty_count, 1); + assert.equal(result.confirmed_count, 1); + assert.equal(result.closed_count, 0); + assert.equal(captures.updateWaveIdList.length, 0); + assert.equal(cacheStore.size, 0); + }); + + it('待处理表查询失败时跳过该仓库,不产生误关', async () => { + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(1777888535813505) ], + queryShouldFail: true, + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 0); + assert.equal(result.confirmed_count, 0); + assert.equal(captures.updateWaveIdList.length, 0); + assert.ok(captures.warnLogList.some(message => /查询仓库 1000028 待处理表失败/.test(message))); + }); + + it('缓存不可用时本轮不终结任何波次(宁可漏关,不可误关)', async () => { + const waveId = 1777888535813505; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + cacheUnavailable: true, + }); + + const result = await service.closeFinishedWaves(); + + assert.equal(result.empty_count, 1); + assert.equal(result.confirmed_count, 0); + assert.equal(result.pending_confirm_count, 1); + assert.equal(captures.updateWaveIdList.length, 0); + assert.ok(captures.warnLogList.some(message => /二次确认状态缓存不可用/.test(message))); + }); + + it('多仓库分别按各自待处理表判定,只终结确认过的仓库波次', async () => { + const waveIdA = 1777888535813505; + const waveIdB = 1777888535764266; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveIdA, 1000028), buildCandidate(waveIdB, 100000) ], + // 仓库 100000 的波次仍有订单 + wavesWithOrders: [ waveIdB ], + }); + cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveIdA, waveIdB ] }); + + const result = await service.closeFinishedWaves(); + + assert.deepEqual(result.warehouse_ids.sort(), [ 100000, 1000028 ]); + assert.equal(result.empty_count, 1); + assert.deepEqual(captures.updateWaveIdList, [ waveIdA ]); + }); + + it('订单表与索引表双空(建波未完成中间态)时不终结', async () => { + const waveId = 1777888535853195; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithIndex: [], + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 0); + assert.equal(result.unbound_count, 1); + assert.deepEqual(result.unbound_wave_ids, [ waveId ]); + assert.equal(result.confirmed_count, 0); + assert.equal(captures.updateWaveIdList.length, 0); + // 双空形态不做抽样核对 + assert.equal(captures.sqlList.some(sql => /probe_count/i.test(sql)), false); + assert.ok(captures.warnLogList.some(message => /双空/.test(message))); + }); + + it('索引有行但抽样核对命中订单(读偏)时不终结', async () => { + const waveId = 1777888535813505; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithIndex: [ waveId ], + probeCount: 3, + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 0); + assert.equal(result.misread_count, 1); + assert.deepEqual(result.misread_wave_ids, [ waveId ]); + assert.equal(captures.updateWaveIdList.length, 0); + assert.ok(captures.warnLogList.some(message => /读偏/.test(message))); + }); + + it('索引有行且抽样为 0(订单真离表)按正常清理口径终结', async () => { + const waveId = 1777888535813505; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithIndex: [ waveId ], + probeCount: 0, + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 1); + assert.equal(result.unbound_count, 0); + assert.equal(result.misread_count, 0); + assert.equal(result.confirmed_count, 1); + assert.deepEqual(captures.updateWaveIdList, [ waveId ]); + }); + + it('波次索引表查询失败时跳过该仓库,不产生误关', async () => { + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(1777888535813505) ], + indexQueryShouldFail: true, + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 0); + assert.equal(captures.updateWaveIdList.length, 0); + assert.ok(captures.warnLogList.some(message => /波次索引表失败/.test(message))); + }); + + it('索引抽样核对失败时本轮不终结该波次(宁可漏关)', async () => { + const waveId = 1777888535813505; + const { service, captures } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithIndex: [ waveId ], + probeShouldFail: true, + }); + + const result = await service.closeFinishedWaves({ confirmMinIntervalMs: 0 }); + + assert.equal(result.empty_count, 0); + assert.equal(result.probe_failed_count, 1); + assert.deepEqual(result.probe_failed_wave_ids, [ waveId ]); + assert.equal(captures.updateWaveIdList.length, 0); + }); + + it('候选查询与终结 UPDATE 使用 UTC_TIMESTAMP 口径(与 create_time UTC 存储一致)', async () => { + const waveId = 1777888535813505; + const { service, captures, cacheStore } = createHarness({ + candidateRows: [ buildCandidate(waveId) ], + wavesWithIndex: [ waveId ], + }); + cacheStore.set(CACHE_KEY, { roundAt: Date.now() - 60000, waveIds: [ waveId ] }); + + await service.closeFinishedWaves(); + + const candidateSql = captures.sqlList.find(sql => /FROM\s+wms_wave_batch/i.test(sql)); + assert.ok(candidateSql, '应执行候选查询'); + assert.ok(/UTC_TIMESTAMP\(\)/i.test(candidateSql), '候选查询需使用 UTC_TIMESTAMP'); + assert.ok(!/NOW\(\)/i.test(candidateSql), '候选查询不应再使用 NOW()'); + + const updateSql = captures.sqlList.find(sql => /^UPDATE\s+wms_wave_batch/i.test(sql)); + assert.ok(updateSql, '应执行终结 UPDATE'); + assert.ok(/UTC_TIMESTAMP\(\)/i.test(updateSql), '终结 UPDATE 需使用 UTC_TIMESTAMP'); + }); +});