perf(order): current 分表 wave_id 前导索引与模型预期定义同步

This commit is contained in:
liufumingren 2026-08-30 07:28:21 +08:00
parent 3442ed5243
commit 7b0004a7e3
3 changed files with 292 additions and 0 deletions

View File

@ -568,6 +568,17 @@ function buildIndexOptions(warehouseId, type) {
name: `idx_${prefix}_hash_crc`,
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
},
// wave_id 前导索引仅 current 分表需要:dispatch 通过 baseIndexes 自动继承;
// history/outsourced 分表未在迁移中加该索引,模型不得生成预期定义,
// 否则运行时 drift 同步会向其自动补建索引,造成模型与实际库不一致。
...(modelType === MANAGED_TYPES.CURRENT
? [
{
name: `idx_${prefix}_wave_id`,
fields: [ 'wave_id' ],
},
]
: []),
{
name: `idx_${prefix}_wave`,
fields: [ 'status', 'wave_id' ],

View File

@ -0,0 +1,133 @@
'use strict';
/**
* queryOrder 波次计数性能优化:为 current/dispatch 分表增加 wave_id 前导索引。
*
* 背景:
* - app/service/systems/workbench.js 的 _countWaveOrders 会对 current + dispatch 两族分表执行
* `SELECT COUNT(*) FROM ... WHERE wave_id=? AND warehouse_id=?`;
* - 现有索引 `idx_{wh}_current_wave` 为 (status, wave_id),前导列 status 不在谓词中,
* 生产 dispatch 分表(约 25.38 万行 / 524MB)需全表扫描约 12.69 万行;
* - 本迁移动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`,
* 为每张分表新增二级索引 `idx_{wh}_current_wave_id (wave_id)`。
*
* 设计说明:
* - 分表按仓库隔离,warehouse_id 在单张分表内为常量,索引无需包含 warehouse_id;
* - 使用 ALGORITHM=INPLACE, LOCK=NONE(MySQL 5.6+ 支持在线加二级索引),
* 不重建表、不锁写,适合低峰期执行;
* - 幂等:索引已存在则跳过;索引命名与 app/model/order_delivery_table_schema.js
* 的 buildIndexOptions 即将补充的定义一致,避免应用运行时 drift 同步重复建索引。
*
* ⚠️ 本文件为「未执行」草案,仅在用户完成风险确认后,通过迁移流程执行。
*/
const SHARD_PATTERNS = [
{ type: 'current', pattern: /^wms_order_delivery_(\d+)$/ },
{ type: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ },
];
/**
* 解析分表名。
* @param {string} tableName 表名。
* @return {{ type: string, warehouseId: string }|null} 解析结果。
*/
function parseShardTableName(tableName) {
for (const item of SHARD_PATTERNS) {
const match = item.pattern.exec(tableName);
if (match) {
return { type: item.type, warehouseId: match[1] };
}
}
return null;
}
/**
* 构建 wave_id 前导索引名(与 buildIndexOptions 命名一致)。
* @param {string} warehouseId 仓库ID。
* @return {string} 索引名。
*/
function buildWaveIdIndexName(warehouseId) {
return `idx_${warehouseId}_current_wave_id`;
}
/**
* 列举库内所有 current/dispatch 分表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<Array<string>>} 分表名列表。
*/
async function listManagedShards(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
+ 'ORDER BY TABLE_NAME'
);
return (rows || [])
.map(row => String(row.tableName || row.TABLE_NAME || ''))
.filter(name => parseShardTableName(name));
}
/**
* 判断索引是否已存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} indexName 索引名。
* @return {Promise<boolean>} 是否存在。
*/
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(index => {
const name = String(index && (index.name || index.Key_name || index.key_name) || '');
return name.toLowerCase() === String(indexName).toLowerCase();
});
}
module.exports = {
/**
* 执行迁移:为 current/dispatch 分表增加 wave_id 前导索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const shards = await listManagedShards(queryInterface);
const results = [];
for (const tableName of shards) {
const parsed = parseShardTableName(tableName);
const indexName = buildWaveIdIndexName(parsed.warehouseId);
if (await indexExists(queryInterface, tableName, indexName)) {
results.push({ tableName, action: 'skip', reason: 'exists' });
continue;
}
await queryInterface.sequelize.query(
`ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`wave_id\`), ALGORITHM=INPLACE, LOCK=NONE`
);
results.push({ tableName, action: 'added', indexName });
}
console.log('[20260830100000-add-wave-id-index] up results:', JSON.stringify(results));
},
/**
* 回滚迁移:移除 wave_id 前导索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const shards = await listManagedShards(queryInterface);
for (const tableName of shards) {
const parsed = parseShardTableName(tableName);
const indexName = buildWaveIdIndexName(parsed.warehouseId);
if (!(await indexExists(queryInterface, tableName, indexName))) {
continue;
}
await queryInterface.sequelize.query(
`ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE`
);
}
},
};

View File

@ -0,0 +1,148 @@
# queryOrder 波次计数性能优化方案(只读评估 + 方案文件,未执行)
> 状态:**待用户风险确认**。本方案全程只读评估,未执行任何 DDL / 数据变更。
> 编制:wms-db-agent|日期:2026-08-30
## 1. 背景与瓶颈定位
- 业务链路:工作台 queryOrder → `app/service/systems/workbench.js`
- `_countWaveOrders()`:对 current + dispatch 两族分表执行 `SELECT COUNT(*) WHERE wave_id=? AND warehouse_id=?`
- `_getWaveOrderIds()`:同谓词取订单 id 列表
- 现状瓶颈(上一轮 DB agent 已定位 + 用户提供生产数据):
- 现有索引 `idx_{wh}_current_wave` 为 `(status, wave_id)`,前导列 `status` 不在谓词中;
- 生产 dispatch 分表约 **25.38 万行 / 524MB**,单次 COUNT 全表扫描约 **12.69 万行**;生产 MySQL **5.7.44**。
- 关联问题:序列表 `wms_order_id_location_{wh}` 缺约 **12.4 万**存量订单 id 记录 → queryOrder 定位回退为分表遍历(见 §5)。
## 2. 分表索引生成机制
### 2.1 模型层定义
- `app/model/order_delivery_table_schema.js`:
- `buildIndexOptions(warehouseId, type)` 生成每张分表的索引列表;
- current 类型共 8 个索引,其中 `idx_{wh}_current_wave = (status, wave_id)`(瓶颈索引);
- dispatch 类型复用 current 的基础索引:`baseIndexes[0..2] + idx_dispatch_{wh}_dispatch_lane (dispatch_lane, status) + baseIndexes.slice(3)`,即 dispatch 分表同样继承 `idx_{wh}_current_wave`;
- `buildIndexLines()` 用于建表 DDL;`buildTableOptions()` 供动态模型 define。
- 基表模型 `app/model/order_delivery.js` 自带索引列表(`wave_id = (status, wave_id)` 等)——基表 `wms_order_delivery` 非分表,**不在本次范围**(可选加,默认不加)。
### 2.2 运行时 drift 同步(⚠️ 关键风险)
- `app/model/order_delivery_factory.js`:`getOrCreateModel` → `ensureManagedTableSchema` → `needsTableSchemaSync`(比对期望索引)→ `alterManagedTableSchema`(**只补缺失索引、不删已有索引**)。
- 每次进程首次使用某分表模型时触发(模型有内存缓存)。
- 结论:**若先改 schema 文件再部署代码,应用会在首个请求时自动对 524MB 大表执行建索引 DDL(无 ALGORITHM/LOCK 控制、无法择时)**。
- 因此正确顺序必须是:**先执行迁移(低峰期)→ 再落盘 schema 代码变更 → 再部署**;这样应用运行时 drift 检查发现索引已存在,不会重复建。
### 2.3 现有索引核对(开发环境,只读 SHOW INDEX)
开发环境(config.local.js,客户端 wms)确认 current/dispatch 分表现有索引与模型一致,瓶颈索引为:
| 表(开发环境示例) | 瓶颈索引 | 列 |
|---|---|---|
| wms_order_delivery_1000028_dispatch | idx_1000028_current_wave | status, wave_id |
| wms_order_delivery_1000028 | idx_1000028_current_wave | status, wave_id |
开发环境分表规模(只读 information_schema):`wms_order_delivery_100000` 66,976 行 / 41.6MB;`wms_order_delivery_100000_dispatch` 2,488 行。生产分表规模以用户提供数据为准(dispatch 25.38 万行 / 524MB),执行前需实测。
## 3. 修改点清单
### 3.1 模型 schema(本次仅书面标注,未改文件)
> 为避免与 wms-dev-agent 的修复冲突,本 agent **不直接修改 schema 代码**,待用户确认后由 wms-dev-agent 落盘;或在用户授权后由本 agent 改。
- 文件:`app/model/order_delivery_table_schema.js`
- 函数:`buildIndexOptions`,current 分支共享 `indexes` 数组内、`idx_${prefix}_wave` 之前插入:
```js
{
name: `idx_${prefix}_wave_id`,
fields: [ 'wave_id' ],
},
```
- dispatch 分支**无需修改**(通过 `baseIndexes` 自动继承)。
- 索引名与迁移草案一致:`idx_{wh}_current_wave_id`(dispatch 表沿用 `_current_` 前缀,与既有继承索引命名习惯一致)。
### 3.2 迁移文件(已创建,未执行)
- 路径:`database/migrations/20260830100000-add-wave-id-index-to-order-delivery-shards.js`
- 要点:
- 动态枚举 `wms_order_delivery_{wh}` 与 `wms_order_delivery_{wh}_dispatch`(information_schema,不写死仓库 id);
- 幂等:`SHOW INDEX` 已存在则跳过;
- 使用原生 `ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE`(Sequelize `addIndex` 不支持传算法/锁参数,故用原生 SQL);
- `down` 为 `DROP INDEX`(同样 INPLACE/LOCK=NONE);
- 语法已通过 `node --check`;**未对任何环境执行**。
## 4. 生产执行风险评估与建议
### 4.1 MySQL 5.7.44 在线 DDL 支持
- InnoDB 添加二级索引支持 `ALGORITHM=INPLACE, LOCK=NONE`(MySQL 5.6+,5.7 完整支持):不重建表、不锁写、并发 DML 允许。
- 前置检查项:
1. `SHOW VARIABLES LIKE 'old_alter_table'` 应为 `OFF`(默认);
2. 确认表引擎 InnoDB(本项目分表均为 InnoDB);
3. 执行前实测各分表行数与大小。
### 4.2 预估耗时与索引体积
- 索引体积:`wave_id BIGINT(20)`(8 字节)+ 主键 8 字节,25.38 万行约 **4–6 MB**,几乎不增加磁盘压力;
- 建索引耗时:全表扫描 524MB + 排序 25 万行键值,低负载 SSD 上单个 dispatch 分表约 **数十秒–5 分钟**;current 分表按行数同比。多仓多表总窗口建议预留 **15–30 分钟**。
- 副作用:每个分表多一个二级索引,INSERT 时多写约 20 字节/行,可忽略。
### 4.3 建议执行窗口
- 低峰期:**凌晨 02:00–05:00** 或周末低峰;避开波次扫描定时任务(`app/schedule/sync_finished_wave_batch.js`)、批量导入与大促。
- 逐表执行并监控:`SHOW PROCESSLIST`、`INFORMATION_SCHEMA.INNODB_TRX`(确认无长事务)。
### 4.4 执行方式(红线)
- ❌ 禁止对生产库直接执行裸 `ALTER TABLE`;❌ 禁止用 `script/db-query.ps1` 查/改生产(它永远是开发环境)。
- ✅ 生产必须走迁移流程:
- 全量:`$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production`
- 或单条:`node script/run-single-migration.cjs 20260830100000-add-wave-id-index-to-order-delivery-shards.js`(内部连 `database/config.js` 的 production)
- ⚠️ **生产当前有 4 条 pending 迁移**(只读 `db:migrate:status --env production` 结果):`20260829120000` / `20260829160000` / `20260829170000` / `20260829180000`(report-delivery 相关)。`run-single-migration.cjs` 会拒绝跨序执行 → **先跑完这 4 条**再跑本条;用 `db:migrate` 则按序自动全部执行。
- 开发环境基线:迁移全部 up(最新 `20260829180000`);本条迁移在开发/生产两边均显示 `down`(未执行,符合"草案"状态)。
### 4.5 回滚
- `down`:`DROP INDEX`(INPLACE/LOCK=NONE,秒级完成),不重建表、不影响数据。
## 5. 存量回填评估(script/backfill-order-id-location.cjs)
### 5.1 适用性
- 目标:将分表存量 id 补入 `wms_order_id_location_{wh}`(id → location 映射),修复 queryOrder 定位回退(约 12.4 万行缺失)。
- 脚本能力:`--dry-run`、`--warehouse-id=`、`--batch-size=`(100–50000,默认 1000)、`--db-client=`、`--config-path=`。
- ⚠️ 默认连开发库(config.local.js);**生产必须** `--config-path=script/db-query-prod-config.js --db-client=wms`。
- 流程:枚举分表 → 确保序列表存在(缺失时 CREATE TABLE)→ 分批 LEFT JOIN(PK 序)找缺失 id → 多行 `INSERT ... ON DUPLICATE KEY UPDATE` → 每仓结束抬 `AUTO_INCREMENT = MAX(id)+50`。
### 5.2 数据量与分批建议
- 约 12.4 万行;默认 batch=1000 约 124 批。每批重新执行 LEFT JOIN(无物化),最大分表 25 万行 × 124 批 ≈ 3 千万次 PK 探测,低峰可接受;建议 `--batch-size=5000` 减少轮次。
- 建议顺序:`--dry-run` 全量预演 → 核对输出 → 按仓库逐个 `--warehouse-id=` 执行 → 前后核对 `COUNT(*)`。
### 5.3 风险点
1. **id 碰撞(最高风险)**:回填期间若序列表 AUTO_INCREMENT 仍低于缺失 id 区间,新订单可能分配到相同 id,`ON DUPLICATE KEY UPDATE` 会把新订单的 location 覆盖为来源表 location。执行前必须核对:`AUTO_INCREMENT` vs 缺失 id 最大值;务必在**最低写入时段**执行。
2. **DDL**:`ensureSequenceTable` 可能 CREATE TABLE;结束会 `ALTER TABLE ... AUTO_INCREMENT`(小表、秒级)——均属 DDL/写操作,需用户确认。
3. **location 覆盖**:id 已存在于序列表时会被覆盖(脚本语义如此)。
4. **无断点续跑**:中断后重跑安全(幂等 upsert),但需重新扫描。
5. **与加索引互补**:索引修波次计数,回填修订单定位,两者独立、可分开执行。
## 6. 需要用户确认的风险问题清单(交 Dispatcher 转达)
1. 是否允许在**生产**执行加索引 DDL?(未确认前不执行)
2. 执行方式:全量 `db:migrate`(会自动先执行生产 pending 的 4 条 20260829* 迁移)还是单条 `run-single-migration.cjs`(需先补跑那 4 条)?是否同意先执行那 4 条?
3. 执行窗口:请指定具体时间(建议凌晨 02:00–05:00);期间可接受轻微 I/O 压力?
4. 索引范围:确认 current + dispatch 两族分表、**全部仓库**都加?
5. 是否允许对 `wms_order_id_location_{wh}` 回填写数据(约 12.4 万行)?是否先 `--dry-run` 预演?
6. 回填窗口与 id 碰撞:是否可安排在最低写入时段?是否同意先核对序列表 AUTO_INCREMENT 区间?
7. schema 代码变更(`buildIndexOptions` 新增 `idx_{prefix}_wave_id`):是否由 wms-dev-agent 落盘?确认部署顺序 = **先迁移、后代码**。
8. 回滚授权:若上线后异常,是否允许执行 down(DROP INDEX)?
## 7. 建议执行顺序
1. 用户完成 §6 风险确认;
2. 生产低峰期执行迁移(含前置 4 条 pending);
3. 生产 `SHOW INDEX` + `EXPLAIN` 验证新索引生效;
4. wms-dev-agent 落盘 `buildIndexOptions` 变更并部署(避免运行时 drift 重复建索引);
5. (可选)序列表回填(先 dry-run);
6. 观察 queryOrder 链路耗时与错误率。