Skip to content

Commit 004940f

Browse files
test(driver-sql): lighten the SQLite bulk-insert bound fixtures off the per-row auto-number reservation (#38734)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9BSi9ocXhcrBSeFbQv8dAV4)_ Fixes #38713 Clause-②: no Metadata-protocol: none ## 维护者速读 用户无感:只改了一个数据库驱动的测试文件,产品行为不变。 数据层测试稳定性:这个测试在繁忙的合并队列上偶尔超时,把无关的改动踢出队列。 测试变轻后耗时约为原来的一半到十五分之一,所有断言保留;若有问题只影响这一个测试文件,可直接撤回。 无。 ## What changes One test file, `packages/drivers/driver-sql/src/sql-driver-38236-sqlite-bulk-insert-bound.test.ts`. No driver source, no config, no timeout added. **Root cause (measured).** Every 1200-row case ran on `bound_ticket`, which has an auto-number field. `bulkCreate` reserves one auto-number per row before it builds any INSERT, at about seven statements per row. A 1200-row batch therefore sent **8,407 statements**, of which 3 were INSERTs. The reservation loop (`fillAutoNumberFields`) took **95–97% of the case's time**; the split INSERTs took 30–60 ms. The case is about the statement split, so most of its time went to something it does not test. **Fix.** - The bound/order case (`inserts every row of a 1200-row batch, in order, …`) now runs the same 1200 rows on `bound_plain`: the same columns without the auto-number. The rows-in-order assertion is kept, and so is 500 + 500 + 200. The transaction assertion is now stronger: it checks the whole statement list (`begin; insert; insert; insert; commit;`), not just the tail. - The cases about the reservation itself (contiguous auto-numbers, burn-once on failure, the caller's transaction, undo inside the caller's transaction) now run on `PAST_ROW_BOUND = SQLITE_MAX_INSERT_ROWS + 1` (501) rows. That is the smallest batch SQLite cannot take as one INSERT, so each case still spans two statements. In the failure cases the bad row is the last one, alone in the second statement, so a failing last statement still rolls back an earlier statement that succeeded. - The pin that "the reservations are all taken before the batch's one transaction opens" moves to the auto-number contiguity case, because that case still has reservations to check. **How the fixtures still cross both bounds** (constants read from `sql-driver-bulk-operations.ts` on origin/main: `SQLITE_MAX_INSERT_ROWS = 500`, `SQLITE_MAX_INSERT_VARIABLES = 32766`): - Row bound: the order case sends 1200 rows, more than 500, as 3 statements. Each reservation case sends 501 rows, more than 500, as 2 statements, and asserts the statement count. - Parameter bound: `splits a wide batch by the parameter bound even under 500 rows` is unchanged. Its 450 rows × 81 bound columns come to more than 36,000 parameters, past 32,766. The `sqliteInsertStatements` unit cases (`[1200, 6], [450, 80], [100, 2000], [501, 1]`) are unchanged too, and check that every statement stays within both bounds. - Every assertion from before is still in the file. ## Tests All runs at `f31d30bd`, on a 4-core shared container. <details><summary>Per-test durations, 5 idle runs each, before (origin/main d2caaec) and after</summary> | case | before (ms) | after (ms) | |:---|:---|:---| | inserts every row of a 1200-row batch (order/bounds) | 1389 · 1592 · 1693 · 1558 · 1448 | 82 · 76 · 97 · 102 · 78 | | deals the batch's auto-numbers contiguously | 1425 · 1285 · 1492 · 1244 · 1398 | 578 · 652 · 784 · 566 · 603 | | leaves nothing stored when the LAST statement fails | 1666 · 1277 · 1454 · 1238 · 1164 | 697 · 668 · 693 · 583 · 560 | | runs inside the caller's transaction | 1390 · 1194 · 1026 · 1039 · 1305 | 573 · 439 · 443 · 628 · 553 | | undoes a failed split batch inside the caller's transaction | 1294 · 1175 · 1141 · 1123 · 1337 | 452 · 568 · 438 · 437 · 410 | | whole file (13 tests) | 8895 · 8477 · 8453 · 7956 · 8474 | 4012 · 3881 · 3937 · 3889 · 4143 | All 5 after-runs: 13/13 passed. </details> <details><summary>Under load: 6 CPU burners on 4 cores, 2 runs each</summary> | case | before (ms) | after (ms) | |:---|:---|:---| | order/bounds (1200 rows) | 2013 · 1956 | 214 · 204 | | auto-number contiguity | 2071 · 2544 | 1414 · 1049 | | whole file | 13971 · 12245 | 6533 · 7961 | On CI the order/bounds case took 5,376 ms against an idle time of about 1.5 s, roughly 3.5×. At that ratio the heaviest case after the change, auto-number contiguity at about 0.6–0.8 s idle, would take about 2.8 s, inside the 5 s default. No per-test timeout is added. </details> <details><summary>Where the time goes: probe of bulkCreate on SQLite in memory, 3 idle runs</summary> | fixture | rows | total | fillAutoNumberFields | rest | statements | INSERTs | |:---|:---|:---|:---|:---|:---|:---| | auto-number | 500 | 566–609 ms | 548–592 ms | 18–34 ms | 3503 | 1 | | auto-number | 501 | 529–595 ms | 513–574 ms | 15–21 ms | 3513 | 2 | | auto-number | 1200 | 1160–1270 ms | 1116–1237 ms | 33–58 ms | 8407 | 3 | | plain | 1200 | 29–33 ms | 1–6 ms | 27–29 ms | 5 | 3 | The probe was a throwaway file. It was deleted and is not in the diff. </details> <details><summary>Package suite and typecheck at f31d30b</summary> `pnpm --filter @objectstack/driver-sql test`: Test Files 274 passed | 14 skipped (288), Tests 4602 passed | 268 skipped (4870). `pnpm --filter @objectstack/driver-sql typecheck`: exit 0. `tsc --listFiles` includes the edited test file. </details> ## Acceptance notes - Driver observation, not filed: `bulkCreate` reserves auto-numbers one row at a time. Each reservation is its own committed transaction of about 7 statements, so on SQLite an N-row batch with one auto-number field sends about 7N statements before its INSERTs (about 1 ms per row idle here). This is how the driver is designed to work, not a defect; it is noted for whoever next looks at seed or import throughput. - No ablation: the diff changes fixtures only, and every assertion it moved has the same form as before. ## Verification Read first: the test file's order/bounds case (the fixture moved to `bound_plain`), then the auto-number contiguity case (where the moved transaction pin now lives). Two-minute check: `pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-38236-sqlite-bulk-insert-bound.test.ts`. Expect 13 passed. The 1200-row order case should take about 0.1 s and the file about 4 s idle. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmTLwBddAv8qQwmLzdk --> Co-authored-by: Claude <noreply@anthropic.com>
1 parent cb8d853 commit 004940f

1 file changed

Lines changed: 45 additions & 22 deletions

File tree

‎packages/drivers/driver-sql/src/sql-driver-38236-sqlite-bulk-insert-bound.test.ts‎

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@
1919
* to the split one: every row lands, a failing statement leaves nothing stored,
2020
* the auto-number reservation is the batch's one reservation dealt in row
2121
* order, and a batch that fits one statement is still exactly one statement.
22+
*
23+
* Fixture cost. A row with an auto-number field takes its own reservation
24+
* (about seven statements each) before any INSERT is built; on a 1200-row batch
25+
* that is about 8,400 statements and some 95% of the case's time, while the
26+
* split INSERTs themselves take tens of milliseconds. So a case whose subject is
27+
* the split alone runs on {@link PLAIN}, which carries no auto-number, and a case
28+
* whose subject is the reservation runs on the smallest batch past the row
29+
* bound, {@link PAST_ROW_BOUND} rows: it still spans two statements.
2230
*/
2331

2432
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
@@ -40,6 +48,15 @@ const TICKET = {
4048
},
4149
} as any;
4250

51+
/** {@link TICKET} without its auto-number: a batch of it takes no reservation. */
52+
const PLAIN = {
53+
name: 'bound_plain',
54+
fields: Object.fromEntries(Object.entries(TICKET.fields).filter(([field]) => field !== 'ticket_number')),
55+
} as any;
56+
57+
/** The smallest batch SQLite cannot take as one INSERT: two statements, the second one row. */
58+
const PAST_ROW_BOUND = SQLITE_MAX_INSERT_ROWS + 1;
59+
4360
/** 80 declared columns: a batch of 450 binds 36000+ parameters, past 32766, while under 500 rows. */
4461
const WIDE = {
4562
name: 'bound_wide',
@@ -71,7 +88,7 @@ describe('[#38236] bulkCreate on SQLite past one INSERT statement\'s bounds', ()
7188

7289
beforeEach(async () => {
7390
driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
74-
await driver.initObjects([TICKET, WIDE]);
91+
await driver.initObjects([TICKET, PLAIN, WIDE]);
7592
sent = [];
7693
knex().on('query', (q: { sql: string }) => sent.push(q.sql.trim().toLowerCase()));
7794
});
@@ -82,18 +99,16 @@ describe('[#38236] bulkCreate on SQLite past one INSERT statement\'s bounds', ()
8299

83100
it('inserts every row of a 1200-row batch, in order, as statements within both bounds', async () => {
84101
const rows = ticketRows(1200);
85-
const result = await driver.bulkCreate(TICKET.name, rows);
102+
const result = await driver.bulkCreate(PLAIN.name, rows);
86103
const statements = [...sent];
87104

88105
expect(result).toHaveLength(1200);
89106
expect(result.map((r) => r.id)).toEqual(rows.map((r) => r.id));
90-
expect(await rowCount(TICKET.name)).toBe(1200);
107+
expect(await rowCount(PLAIN.name)).toBe(1200);
91108
// 500 + 500 + 200: the compound-SELECT bound is the one that binds here.
92-
expect(insertsInto(TICKET.name)).toHaveLength(3);
93-
// All three inside ONE transaction: the reservations are all taken before
94-
// it opens, so it holds the three INSERTs and nothing else.
95-
const first = statements.findIndex((sql) => sql.startsWith(`insert into \`${TICKET.name}\``));
96-
expect(statements.slice(first - 1)).toEqual(['begin;', ...insertsInto(TICKET.name), 'commit;']);
109+
expect(insertsInto(PLAIN.name)).toHaveLength(3);
110+
// All three inside ONE transaction, which holds the three INSERTs and nothing else.
111+
expect(statements).toEqual(['begin;', ...insertsInto(PLAIN.name), 'commit;']);
97112
});
98113

99114
it('splits a wide batch by the parameter bound even under 500 rows', async () => {
@@ -110,13 +125,19 @@ describe('[#38236] bulkCreate on SQLite past one INSERT statement\'s bounds', ()
110125
});
111126

112127
it('deals the batch\'s auto-numbers contiguously and in row order across statements', async () => {
113-
const result = await driver.bulkCreate(TICKET.name, ticketRows(1200));
128+
const result = await driver.bulkCreate(TICKET.name, ticketRows(PAST_ROW_BOUND));
129+
const statements = [...sent];
114130

115-
const expected = Array.from({ length: 1200 }, (_, i) => `T-${String(i + 1).padStart(5, '0')}`);
131+
const expected = Array.from({ length: PAST_ROW_BOUND }, (_, i) => `T-${String(i + 1).padStart(5, '0')}`);
116132
expect(result.map((r) => r.ticket_number)).toEqual(expected);
117133
const stored = await knex()(TICKET.name).select('id', 'ticket_number').orderBy('id');
118134
expect(stored.map((r: any) => r.ticket_number)).toEqual(expected);
119-
expect(await lastValue()).toBe(1200);
135+
expect(await lastValue()).toBe(PAST_ROW_BOUND);
136+
// The reservations are all taken before the batch's ONE transaction opens,
137+
// so it holds the two INSERTs and nothing else.
138+
expect(insertsInto(TICKET.name)).toHaveLength(2);
139+
const first = statements.findIndex((sql) => sql.startsWith(`insert into \`${TICKET.name}\``));
140+
expect(statements.slice(first - 1)).toEqual(['begin;', ...insertsInto(TICKET.name), 'commit;']);
120141
});
121142

122143
it('leaves nothing stored when the LAST statement fails, and burns the reservation once, as one statement does', async () => {
@@ -128,34 +149,36 @@ describe('[#38236] bulkCreate on SQLite past one INSERT statement\'s bounds', ()
128149
expect(await rowCount(TICKET.name)).toBe(0);
129150
expect(await lastValue()).toBe(3);
130151

131-
// A 1200-row batch whose row 1150 (in the third statement) repeats row 5's id.
132-
const rows = ticketRows(1200);
133-
rows[1150].id = rows[5].id;
152+
// A batch whose last row (alone in the second statement) repeats row 5's id.
153+
const rows = ticketRows(PAST_ROW_BOUND);
154+
rows[PAST_ROW_BOUND - 1].id = rows[5].id;
134155
await expect(driver.bulkCreate(TICKET.name, rows)).rejects.toThrow(/UNIQUE constraint failed: bound_ticket\.id/);
135-
expect(insertsInto(TICKET.name).length).toBeGreaterThanOrEqual(4); // the control's one, then the split batch's three
156+
expect(insertsInto(TICKET.name).length).toBeGreaterThanOrEqual(3); // the control's one, then the split batch's two
136157
expect(await rowCount(TICKET.name)).toBe(0);
137158
// Burned once for the whole batch, exactly as the control burned its three.
138-
expect(await lastValue()).toBe(3 + 1200);
159+
expect(await lastValue()).toBe(3 + PAST_ROW_BOUND);
139160

140161
// The next batch continues above the burned range, with no duplicate.
141162
const next = await driver.bulkCreate(TICKET.name, ticketRows(2, 9500));
142-
expect(next.map((r) => r.ticket_number)).toEqual(['T-01204', 'T-01205']);
163+
const above = 3 + PAST_ROW_BOUND;
164+
expect(next.map((r) => r.ticket_number)).toEqual([above + 1, above + 2].map((n) => `T-${String(n).padStart(5, '0')}`));
143165
});
144166

145167
it('runs inside the caller\'s transaction: the caller\'s rollback removes every statement\'s rows', async () => {
146168
const trx = await knex().transaction();
147-
const result = await driver.bulkCreate(TICKET.name, ticketRows(1200), { transaction: trx } as any);
148-
expect(result).toHaveLength(1200);
149-
expect(Number((await trx(TICKET.name).count({ c: '*' }).first()).c)).toBe(1200);
169+
const result = await driver.bulkCreate(TICKET.name, ticketRows(PAST_ROW_BOUND), { transaction: trx } as any);
170+
expect(result).toHaveLength(PAST_ROW_BOUND);
171+
expect(insertsInto(TICKET.name)).toHaveLength(2);
172+
expect(Number((await trx(TICKET.name).count({ c: '*' }).first()).c)).toBe(PAST_ROW_BOUND);
150173
await trx.rollback();
151174
expect(await rowCount(TICKET.name)).toBe(0);
152175
});
153176

154177
it('undoes a failed split batch inside the caller\'s transaction and keeps the caller\'s own writes', async () => {
155178
const trx = await knex().transaction();
156179
await driver.bulkCreate(TICKET.name, ticketRows(1, 7000), { transaction: trx } as any);
157-
const rows = ticketRows(1200);
158-
rows[1150].id = rows[5].id;
180+
const rows = ticketRows(PAST_ROW_BOUND);
181+
rows[PAST_ROW_BOUND - 1].id = rows[5].id;
159182
await expect(driver.bulkCreate(TICKET.name, rows, { transaction: trx } as any)).rejects.toThrow(/UNIQUE constraint failed/);
160183
expect(Number((await trx(TICKET.name).count({ c: '*' }).first()).c)).toBe(1);
161184
await trx.commit();

0 commit comments

Comments
 (0)