wal-deferral.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /**
  2. * WAL checkpoint deferral during bulk indexing (#1231).
  3. *
  4. * The default 1000-page wal_autocheckpoint re-writes hot pages into the main
  5. * DB over and over during a bulk index (~95% of all disk I/O on slow
  6. * storage). indexAll defers auto-checkpointing for the whole run, a
  7. * WalCheckpointValve bounds WAL growth via off-thread PASSIVE checkpoints,
  8. * and the interval is restored afterwards. These tests pin the DB helpers,
  9. * the valve's trigger/dedupe/backpressure logic, and the end-to-end indexAll
  10. * behavior (identical graph with and without deferral; interval restored).
  11. */
  12. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  13. import * as fs from 'fs';
  14. import * as os from 'os';
  15. import * as path from 'path';
  16. import { DatabaseConnection } from '../src/db';
  17. import { WalCheckpointValve, resolveWalValveMb } from '../src/db/wal-valve';
  18. import CodeGraph from '../src/index';
  19. let tmpDir: string;
  20. beforeEach(() => {
  21. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-wal-deferral-'));
  22. });
  23. afterEach(() => {
  24. fs.rmSync(tmpDir, { recursive: true, force: true });
  25. });
  26. function openDb(): DatabaseConnection {
  27. return DatabaseConnection.initialize(path.join(tmpDir, 'test.db'));
  28. }
  29. /** Grow the WAL: with autocheckpoint off, every commit appends and nothing folds back. */
  30. function writeRows(db: DatabaseConnection, rows: number): void {
  31. const raw = db.getDb();
  32. raw.exec('CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, blob TEXT)');
  33. const stmt = raw.prepare('INSERT INTO t (blob) VALUES (?)');
  34. for (let i = 0; i < rows; i++) stmt.run('x'.repeat(4096));
  35. }
  36. describe('resolveWalValveMb', () => {
  37. it('honors a positive numeric override and falls back otherwise', () => {
  38. expect(resolveWalValveMb('64')).toBe(64);
  39. expect(resolveWalValveMb('64.9')).toBe(64);
  40. expect(resolveWalValveMb(undefined)).toBe(256);
  41. expect(resolveWalValveMb('')).toBe(256);
  42. expect(resolveWalValveMb('abc')).toBe(256);
  43. expect(resolveWalValveMb('0')).toBe(256);
  44. expect(resolveWalValveMb('-5')).toBe(256);
  45. });
  46. });
  47. describe('DatabaseConnection WAL helpers', () => {
  48. it('reads and writes the wal_autocheckpoint interval', () => {
  49. const db = openDb();
  50. expect(db.getWalAutocheckpoint()).toBe(1000); // SQLite default
  51. db.setWalAutocheckpoint(0);
  52. expect(db.getWalAutocheckpoint()).toBe(0);
  53. db.setWalAutocheckpoint(1000);
  54. expect(db.getWalAutocheckpoint()).toBe(1000);
  55. db.close();
  56. });
  57. it('reports WAL size that grows with deferred commits', () => {
  58. const db = openDb();
  59. db.setWalAutocheckpoint(0);
  60. const before = db.getWalSizeBytes();
  61. writeRows(db, 200);
  62. expect(db.getWalSizeBytes()).toBeGreaterThan(before);
  63. db.close();
  64. });
  65. it('checkpointWalPassive backfills the WAL from a worker connection and reports the result', async () => {
  66. const db = openDb();
  67. db.setWalAutocheckpoint(0);
  68. writeRows(db, 500);
  69. const dbFile = path.join(tmpDir, 'test.db');
  70. const mainSizeBefore = fs.statSync(dbFile).size;
  71. const res = await db.checkpointWalPassive();
  72. // Backfill moves the committed pages into the main DB file…
  73. expect(fs.statSync(dbFile).size).toBeGreaterThan(mainSizeBefore);
  74. // …and reports a full backfill (idle DB: every WAL frame checkpointed).
  75. expect(res).not.toBeNull();
  76. expect(res!.busy).toBe(0);
  77. expect(res!.log).toBeGreaterThan(0);
  78. expect(res!.checkpointed).toBe(res!.log);
  79. db.close();
  80. });
  81. });
  82. describe('WalCheckpointValve', () => {
  83. it('check() fires an off-thread checkpoint once growth passes the soft threshold', async () => {
  84. const db = openDb();
  85. db.setWalAutocheckpoint(0);
  86. writeRows(db, 500); // WAL well past a ~10-byte threshold
  87. const valve = new WalCheckpointValve(db, 0.00001); // ~10 bytes soft
  88. const dbFile = path.join(tmpDir, 'test.db');
  89. const mainSizeBefore = fs.statSync(dbFile).size;
  90. valve.check();
  91. await valve.drain();
  92. expect(fs.statSync(dbFile).size).toBeGreaterThan(mainSizeBefore);
  93. db.close();
  94. });
  95. it('advances its baseline on a full backfill — a wrapped WAL does not retrigger it', async () => {
  96. const db = openDb();
  97. db.setWalAutocheckpoint(0);
  98. writeRows(db, 500);
  99. const valve = new WalCheckpointValve(db, 0.00001);
  100. valve.check();
  101. await valve.drain(); // full backfill on an idle DB → baseline = current file size
  102. // The WAL file keeps its high-water size, but growth is now 0: neither
  103. // the timer path nor backpressure may fire again (the pre-fix bug fired
  104. // on raw size forever and serialized every store behind a checkpoint).
  105. expect(valve.backpressure()).toBeNull();
  106. valve.check();
  107. await valve.drain(); // no-op drain: nothing in flight
  108. // New commits recycle wrapped frames — file size is flat, still no trigger.
  109. writeRows(db, 5);
  110. expect(valve.backpressure()).toBeNull();
  111. db.close();
  112. });
  113. it('does not fire below the soft threshold', async () => {
  114. const db = openDb();
  115. db.setWalAutocheckpoint(0);
  116. writeRows(db, 5);
  117. const valve = new WalCheckpointValve(db, 1024); // 1GB soft — never reached
  118. const dbFile = path.join(tmpDir, 'test.db');
  119. const mainSizeBefore = fs.statSync(dbFile).size;
  120. valve.check();
  121. await valve.drain();
  122. expect(fs.statSync(dbFile).size).toBe(mainSizeBefore);
  123. db.close();
  124. });
  125. it('backpressure() is null under the hard cap and a promise above it', async () => {
  126. const db = openDb();
  127. db.setWalAutocheckpoint(0);
  128. writeRows(db, 500);
  129. const relaxed = new WalCheckpointValve(db, 1024);
  130. expect(relaxed.backpressure()).toBeNull();
  131. const strict = new WalCheckpointValve(db, 0.0000001); // hard cap ~0.4 bytes
  132. const bp = strict.backpressure();
  133. expect(bp).toBeInstanceOf(Promise);
  134. await bp;
  135. await strict.drain();
  136. db.close();
  137. });
  138. it('foldNow() backfills everything at a phase boundary and resets growth', async () => {
  139. const db = openDb();
  140. db.setWalAutocheckpoint(0);
  141. writeRows(db, 500);
  142. const valve = new WalCheckpointValve(db, 1024); // thresholds never reached on their own
  143. const dbFile = path.join(tmpDir, 'test.db');
  144. const mainSizeBefore = fs.statSync(dbFile).size;
  145. await valve.foldNow();
  146. expect(fs.statSync(dbFile).size).toBeGreaterThan(mainSizeBefore); // pages backfilled
  147. expect(valve.backpressure()).toBeNull(); // baseline advanced — growth is zero
  148. await valve.foldNow(); // second fold is a no-op (growth 0), must not spin
  149. db.close();
  150. });
  151. it('dedupes concurrent fires into one in-flight checkpoint', () => {
  152. const db = openDb();
  153. db.setWalAutocheckpoint(0);
  154. writeRows(db, 500);
  155. const valve = new WalCheckpointValve(db, 0.00001);
  156. valve.check();
  157. const first = valve.backpressure();
  158. const second = valve.backpressure();
  159. expect(second).toBe(first); // same in-flight promise, not a second worker
  160. db.close();
  161. return first ?? undefined;
  162. });
  163. });
  164. function writeFixtureProject(): void {
  165. fs.mkdirSync(path.join(tmpDir, 'src'), { recursive: true });
  166. for (let i = 0; i < 8; i++) {
  167. fs.writeFileSync(
  168. path.join(tmpDir, 'src', `mod${i}.ts`),
  169. `export function fn${i}(x: number): number { return helper${i}(x) + ${i}; }\n` +
  170. `function helper${i}(x: number): number { return x * ${i}; }\n`
  171. );
  172. }
  173. }
  174. describe('indexAll WAL deferral end-to-end', () => {
  175. it('produces the same graph with and without deferral, and restores the interval', async () => {
  176. writeFixtureProject();
  177. const cg1 = CodeGraph.initSync(tmpDir);
  178. const r1 = await cg1.indexAll();
  179. expect(r1.success).toBe(true);
  180. // Deferral is scoped to the run: the connection is back on the default.
  181. const conn1 = (cg1 as unknown as { db: DatabaseConnection }).db;
  182. expect(conn1.getWalAutocheckpoint()).toBe(1000);
  183. const counts1 = { nodes: r1.nodesCreated, edges: r1.edgesCreated };
  184. await cg1.close();
  185. fs.rmSync(path.join(tmpDir, '.codegraph'), { recursive: true, force: true });
  186. process.env.CODEGRAPH_NO_WAL_DEFER = '1';
  187. try {
  188. const cg2 = CodeGraph.initSync(tmpDir);
  189. const r2 = await cg2.indexAll();
  190. expect(r2.success).toBe(true);
  191. expect({ nodes: r2.nodesCreated, edges: r2.edgesCreated }).toEqual(counts1);
  192. await cg2.close();
  193. } finally {
  194. delete process.env.CODEGRAPH_NO_WAL_DEFER;
  195. }
  196. });
  197. });
  198. describe('sync WAL deferral end-to-end (#1248)', () => {
  199. // The #1242 fix originally landed only on indexAll; sync stayed at the
  200. // default 1000-page autocheckpoint and reproduced the #1231 HDD thrash on
  201. // every incremental run (2 minutes for a 7-file sync). These pin that sync
  202. // defers during the run, restores after — success AND no-change paths —
  203. // and that a deferred sync produces the same graph as an undeferred one.
  204. it('defers the autocheckpoint interval DURING sync and restores it after', async () => {
  205. writeFixtureProject();
  206. const cg = CodeGraph.initSync(tmpDir);
  207. await cg.indexAll();
  208. const conn = (cg as unknown as { db: DatabaseConnection }).db;
  209. fs.writeFileSync(
  210. path.join(tmpDir, 'src', 'mod0.ts'),
  211. `export function fn0(x: number): number { return helper0(x) + 100; }\n` +
  212. `function helper0(x: number): number { return x * 100; }\n`
  213. );
  214. // Sample the interval mid-run from inside the progress callback — the
  215. // store loop is exactly where the #1248 thrash happened.
  216. const midRunIntervals: number[] = [];
  217. const result = await cg.sync({
  218. onProgress: () => {
  219. try { midRunIntervals.push(conn.getWalAutocheckpoint()); } catch { /* ignore */ }
  220. },
  221. });
  222. expect(result.filesModified).toBe(1);
  223. expect(midRunIntervals.length).toBeGreaterThan(0);
  224. expect(midRunIntervals.every((v) => v === 0)).toBe(true);
  225. // Scoped to the run: back on the default afterwards.
  226. expect(conn.getWalAutocheckpoint()).toBe(1000);
  227. await cg.close();
  228. });
  229. it('restores the interval on a no-change sync too', async () => {
  230. writeFixtureProject();
  231. const cg = CodeGraph.initSync(tmpDir);
  232. await cg.indexAll();
  233. const conn = (cg as unknown as { db: DatabaseConnection }).db;
  234. const result = await cg.sync();
  235. expect(result.filesAdded + result.filesModified + result.filesRemoved).toBe(0);
  236. expect(conn.getWalAutocheckpoint()).toBe(1000);
  237. await cg.close();
  238. });
  239. it('produces the same sync result with and without deferral', async () => {
  240. writeFixtureProject();
  241. const cg1 = CodeGraph.initSync(tmpDir);
  242. await cg1.indexAll();
  243. fs.writeFileSync(
  244. path.join(tmpDir, 'src', 'mod1.ts'),
  245. `export function fn1(x: number): number { return helper1(x) + 111; }\n` +
  246. `function helper1(x: number): number { return x * 111; }\n`
  247. );
  248. const r1 = await cg1.sync();
  249. const counts1 = { modified: r1.filesModified, nodes: r1.nodesUpdated };
  250. await cg1.close();
  251. fs.rmSync(path.join(tmpDir, '.codegraph'), { recursive: true, force: true });
  252. process.env.CODEGRAPH_NO_WAL_DEFER = '1';
  253. try {
  254. const cg2 = CodeGraph.initSync(tmpDir);
  255. await cg2.indexAll();
  256. fs.writeFileSync(
  257. path.join(tmpDir, 'src', 'mod1.ts'),
  258. `export function fn1(x: number): number { return helper1(x) + 222; }\n` +
  259. `function helper1(x: number): number { return x * 222; }\n`
  260. );
  261. const r2 = await cg2.sync();
  262. expect({ modified: r2.filesModified, nodes: r2.nodesUpdated }).toEqual(counts1);
  263. await cg2.close();
  264. } finally {
  265. delete process.env.CODEGRAPH_NO_WAL_DEFER;
  266. }
  267. });
  268. });
  269. describe('resolution-phase WAL backpressure plumbing (§7a.1)', () => {
  270. // The valve's timer-driven passive checkpoints stay perpetually partial
  271. // against the resolver pool's continuous reads, so during resolution the
  272. // writer-side backpressure() hook is the ONLY mechanism that can complete
  273. // a backfill and let the WAL wrap — a kernel-scale run without it grew a
  274. // 22GB WAL on a 4.6GB DB. These pin that the batch loop (a) calls the hook
  275. // at the pool-idle boundary and (b) actually parks on a returned promise.
  276. async function seedPendingRefs(cg: CodeGraph): Promise<void> {
  277. const raw = (cg as unknown as { db: DatabaseConnection }).db.getDb();
  278. const node = raw.prepare("SELECT id, file_path FROM nodes WHERE kind = 'function' LIMIT 1").get() as
  279. | { id: string; file_path: string }
  280. | undefined;
  281. expect(node).toBeDefined();
  282. const ins = raw.prepare(
  283. "INSERT INTO unresolved_refs (from_node_id, reference_name, reference_kind, line, col, file_path, language, status) VALUES (?, ?, 'calls', 1, 0, ?, 'typescript', 'pending')"
  284. );
  285. ins.run(node!.id, 'helper0', node!.file_path);
  286. ins.run(node!.id, 'helper1', node!.file_path);
  287. }
  288. it('calls the backpressure hook once per settled batch', async () => {
  289. writeFixtureProject();
  290. const cg = CodeGraph.initSync(tmpDir);
  291. await cg.indexAll();
  292. await seedPendingRefs(cg);
  293. let calls = 0;
  294. const result = await cg.resolveReferencesBatched(undefined, undefined, () => {
  295. calls++;
  296. return null; // under the hard cap — loop must proceed without waiting
  297. });
  298. expect(result.stats.total).toBeGreaterThan(0);
  299. expect(calls).toBeGreaterThanOrEqual(1);
  300. await cg.close();
  301. });
  302. it('parks the batch loop on a backpressure promise until it resolves', async () => {
  303. writeFixtureProject();
  304. const cg = CodeGraph.initSync(tmpDir);
  305. await cg.indexAll();
  306. await seedPendingRefs(cg);
  307. let release!: () => void;
  308. const gate = new Promise<void>((r) => { release = r; });
  309. let hookHit = false;
  310. const done = cg
  311. .resolveReferencesBatched(undefined, undefined, () => {
  312. if (hookHit) return null; // park only on the first boundary
  313. hookHit = true;
  314. return gate;
  315. })
  316. .then(() => true);
  317. // Give the loop ample turns: it must reach the hook and then be parked.
  318. for (let i = 0; i < 50; i++) await new Promise((r) => setImmediate(r));
  319. expect(hookHit).toBe(true);
  320. const settledEarly = await Promise.race([done, Promise.resolve(false)]);
  321. expect(settledEarly).toBe(false); // still parked on the gate
  322. release();
  323. expect(await done).toBe(true);
  324. await cg.close();
  325. });
  326. });