mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 07:49:45 +08:00
- ErrorItem 增加 (userId,subjectId/paperLevel/questionType,createdAt) 联合索引 - KnowledgeTag 增加 name 索引 - 迁移测试校验新索引 - 新增 bench-error-list.mjs 与性能文档,1k/5k p75 与 EXPLAIN 可复现 Refs: https://github.com/margrop/wrong-notebook/issues/64
195 lines
8.2 KiB
JavaScript
195 lines
8.2 KiB
JavaScript
/**
|
||
* 错题列表千级数据基准:在临时 SQLite 库中按真实 schema 建库,写入 1k/5k 合成错题,
|
||
* 测量列表接口的「count + 分页查询」耗时,并输出 EXPLAIN QUERY PLAN 证明筛选走索引。
|
||
*
|
||
* 用法:node scripts/bench-error-list.mjs [--rounds 25] [--counts 1000,5000]
|
||
* 临时库在系统临时目录,结束后删除,不写入仓库。
|
||
*/
|
||
import { execFileSync } from 'node:child_process';
|
||
import { cpSync, mkdtempSync, rmSync } from 'node:fs';
|
||
import { tmpdir } from 'node:os';
|
||
import { join, resolve } from 'node:path';
|
||
import { PrismaClient } from '@prisma/client';
|
||
|
||
const PRISMA_CLI = resolve('node_modules/prisma/build/index.js');
|
||
const SCHEMA = resolve('prisma/schema.prisma');
|
||
const PAGE_SIZE = 20;
|
||
const CHUNK = 500;
|
||
const QUESTION_TYPES = ['single_choice', 'fill_blank', 'solution', 'reading'];
|
||
|
||
function parseArgs() {
|
||
const args = process.argv.slice(2);
|
||
const rounds = Number(args[args.indexOf('--rounds') + 1] || 25);
|
||
const counts = (args[args.indexOf('--counts') + 1] || '1000,5000').split(',').map(Number);
|
||
return { rounds: Number.isFinite(rounds) && rounds > 0 ? rounds : 25, counts };
|
||
}
|
||
|
||
/** 用 prisma db push 按当前 schema 建临时库,保证索引与迁移后的生产库一致 */
|
||
function createDatabase(directory) {
|
||
const databasePath = join(directory, 'bench.db');
|
||
const schemaPath = join(directory, 'schema.prisma');
|
||
cpSync(SCHEMA, schemaPath);
|
||
execFileSync(process.execPath, [PRISMA_CLI, 'db', 'push', '--schema', schemaPath, '--skip-generate'], {
|
||
env: { ...process.env, DATABASE_URL: 'file:' + databasePath },
|
||
encoding: 'utf8',
|
||
stdio: 'pipe',
|
||
timeout: 120_000,
|
||
});
|
||
return databasePath;
|
||
}
|
||
|
||
function percentile(values, ratio) {
|
||
const sorted = [...values].sort((left, right) => left - right);
|
||
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1));
|
||
return sorted[index];
|
||
}
|
||
|
||
async function seed(prisma, total) {
|
||
const existing = await prisma.errorItem.count();
|
||
if (existing >= total) return;
|
||
const data = [];
|
||
const base = Date.parse('2026-01-01T00:00:00Z');
|
||
for (let index = existing; index < total; index++) {
|
||
data.push({
|
||
id: `bench-item-${index}`,
|
||
userId: 'bench-user',
|
||
subjectId: 'bench-subject',
|
||
paperLevel: `bench-paper-${index % 3}`,
|
||
originalImageUrl: 'bench-image',
|
||
questionText: `基准题目 ${index}`,
|
||
questionType: QUESTION_TYPES[index % QUESTION_TYPES.length],
|
||
gradeSemester: index % 2 === 0 ? '七年级上' : '八年级下',
|
||
createdAt: new Date(base + index * 60_000),
|
||
});
|
||
}
|
||
for (let start = 0; start < data.length; start += CHUNK) {
|
||
await prisma.errorItem.createMany({ data: data.slice(start, start + CHUNK) });
|
||
}
|
||
}
|
||
|
||
const SCENARIOS = {
|
||
default: (userId) => ({ where: { userId } }),
|
||
subject: (userId) => ({ where: { userId, subjectId: 'bench-subject' } }),
|
||
paperLevel: (userId) => ({ where: { userId, paperLevel: 'bench-paper-1' } }),
|
||
questionType: (userId) => ({ where: { userId, questionType: 'single_choice' } }),
|
||
questionTypes: (userId) => ({ where: { userId, questionType: { in: ['single_choice', 'fill_blank'] } } }),
|
||
search: (userId) => ({
|
||
where: {
|
||
userId,
|
||
OR: [
|
||
{ questionText: { contains: '基准题目 4999' } },
|
||
{ analysis: { contains: '基准题目 4999' } },
|
||
{ wrongAnswerText: { contains: '基准题目 4999' } },
|
||
{ mistakeAnalysis: { contains: '基准题目 4999' } },
|
||
],
|
||
},
|
||
}),
|
||
deepPage: (userId) => ({ where: { userId }, skip: 4000 }),
|
||
};
|
||
|
||
async function measure(prisma, name, rounds) {
|
||
const scenario = SCENARIOS[name];
|
||
const timings = [];
|
||
for (let round = 0; round < rounds; round++) {
|
||
const args = scenario('bench-user');
|
||
const startedAt = process.hrtime.bigint();
|
||
await prisma.errorItem.count({ where: args.where });
|
||
await prisma.errorItem.findMany({
|
||
...args,
|
||
orderBy: { createdAt: 'desc' },
|
||
skip: args.skip ?? 0,
|
||
take: PAGE_SIZE,
|
||
select: { id: true, questionText: true, masteryProbability: true },
|
||
});
|
||
timings.push(Number(process.hrtime.bigint() - startedAt) / 1e6);
|
||
}
|
||
return {
|
||
p50: percentile(timings, 0.5),
|
||
p75: percentile(timings, 0.75),
|
||
p95: percentile(timings, 0.95),
|
||
};
|
||
}
|
||
|
||
/** 与列表接口等价的 SQL;EXPLAIN 只用于证明索引覆盖,不计入耗时 */
|
||
const EXPLAIN_SQL = {
|
||
default: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', PAGE_SIZE, 0],
|
||
},
|
||
subject: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "subjectId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', 'bench-subject', PAGE_SIZE, 0],
|
||
},
|
||
paperLevel: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "paperLevel" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', 'bench-paper-1', PAGE_SIZE, 0],
|
||
},
|
||
questionType: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "questionType" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', 'single_choice', PAGE_SIZE, 0],
|
||
},
|
||
questionTypes: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "questionType" IN (?,?) ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', 'single_choice', 'fill_blank', PAGE_SIZE, 0],
|
||
},
|
||
search: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND ("questionText" LIKE ? OR "analysis" LIKE ? OR "wrongAnswerText" LIKE ? OR "mistakeAnalysis" LIKE ?) ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', '%基准题目 4999%', '%基准题目 4999%', '%基准题目 4999%', '%基准题目 4999%', PAGE_SIZE, 0],
|
||
},
|
||
deepPage: {
|
||
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
|
||
params: ['bench-user', PAGE_SIZE, 4000],
|
||
},
|
||
};
|
||
|
||
async function explain(prisma, name) {
|
||
const { sql, params } = EXPLAIN_SQL[name];
|
||
const plan = await prisma.$queryRawUnsafe('EXPLAIN QUERY PLAN ' + sql, ...params);
|
||
return plan.map((row) => row.detail);
|
||
}
|
||
|
||
async function main() {
|
||
const { rounds, counts } = parseArgs();
|
||
const directory = mkdtempSync(join(tmpdir(), 'wrong-notebook-bench-'));
|
||
const databasePath = createDatabase(directory);
|
||
const prisma = new PrismaClient({ datasources: { db: { url: 'file:' + databasePath } } });
|
||
try {
|
||
await prisma.user.create({ data: { id: 'bench-user', email: 'bench@example.com', password: 'bench-only' } });
|
||
await prisma.subject.create({ data: { id: 'bench-subject', name: '基准数学', userId: 'bench-user', subjectKey: 'math' } });
|
||
for (let index = 0; index < 3; index++) {
|
||
await prisma.paperGroup.create({
|
||
data: { id: `bench-paper-${index}`, userId: 'bench-user', key: ['a', 'b', 'other'][index], name: `基准卷 ${index}` },
|
||
});
|
||
}
|
||
|
||
const results = [];
|
||
let seeded = 0;
|
||
for (const total of counts) {
|
||
await seed(prisma, total);
|
||
seeded = total;
|
||
const row = { count: total, scenarios: {} };
|
||
for (const name of Object.keys(SCENARIOS)) {
|
||
if (name === 'deepPage' && total < 4000) continue;
|
||
row.scenarios[name] = await measure(prisma, name, rounds);
|
||
}
|
||
results.push(row);
|
||
}
|
||
console.log(JSON.stringify({ rounds, seeded, results }, null, 2));
|
||
|
||
console.log('\nEXPLAIN QUERY PLAN(5k 数据)');
|
||
for (const name of Object.keys(SCENARIOS)) {
|
||
if (name === 'deepPage' && seeded < 4000) continue;
|
||
console.log(`\n${name}:`);
|
||
for (const line of await explain(prisma, name)) console.log(' ' + line);
|
||
}
|
||
} finally {
|
||
await prisma.$disconnect();
|
||
rmSync(directory, { recursive: true, force: true });
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|