index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /**
  2. * Database Layer
  3. *
  4. * Handles SQLite database initialization and connection management.
  5. */
  6. import { SqliteDatabase, SqliteBackend, createDatabase } from './sqlite-adapter';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import { SchemaVersion } from '../types';
  10. import { runMigrations, getCurrentVersion, CURRENT_SCHEMA_VERSION } from './migrations';
  11. import { getCodeGraphDir } from '../directory';
  12. export { SqliteDatabase, SqliteBackend } from './sqlite-adapter';
  13. /**
  14. * Apply connection-level PRAGMAs. Shared by `initialize` and `open` so the two
  15. * paths can't drift.
  16. *
  17. * `busy_timeout` is set FIRST, before any pragma that might touch the database
  18. * file (notably `journal_mode`). If another process holds a write lock at open
  19. * time, the later pragmas — and the connection's first query — then wait out
  20. * the lock instead of throwing "database is locked" immediately. See issue #238.
  21. *
  22. * The 5s window (was 120s) rides out a normal incremental sync; the old
  23. * 2-minute wait presented as a frozen, hung agent. With WAL, reads never block
  24. * on a writer, so this timeout only governs cross-process write contention
  25. * (e.g. the git-hook `codegraph sync` running while the MCP server writes).
  26. */
  27. function configureConnection(db: SqliteDatabase): void {
  28. db.pragma('busy_timeout = 5000'); // MUST be first — see above
  29. db.pragma('foreign_keys = ON');
  30. db.pragma('journal_mode = WAL'); // node:sqlite supports WAL on every platform
  31. db.pragma('synchronous = NORMAL'); // safe with WAL mode
  32. db.pragma('cache_size = -64000'); // 64 MB page cache
  33. db.pragma('temp_store = MEMORY'); // temp tables in memory
  34. db.pragma('mmap_size = 268435456'); // 256 MB memory-mapped I/O
  35. }
  36. /**
  37. * Database connection wrapper with lifecycle management
  38. */
  39. export class DatabaseConnection {
  40. private db: SqliteDatabase;
  41. private dbPath: string;
  42. private backend: SqliteBackend;
  43. /**
  44. * `dev:ino` of the DB file at the moment we opened it (or null when the
  45. * platform/filesystem reports no usable inode). Lets us notice when the file
  46. * we hold open has been unlinked and REPLACED by a new file at the same path
  47. * — a git worktree removed and re-added, or `.codegraph/` deleted and
  48. * re-`init`ed under a long-lived server — at which point our fd reads a now
  49. * dead inode forever (#925). See `isReplacedOnDisk`.
  50. */
  51. private openedInode: string | null;
  52. private constructor(db: SqliteDatabase, dbPath: string, backend: SqliteBackend) {
  53. this.db = db;
  54. this.dbPath = dbPath;
  55. this.backend = backend;
  56. this.openedInode = statInode(dbPath);
  57. }
  58. /**
  59. * Initialize a new database at the given path
  60. */
  61. static initialize(dbPath: string): DatabaseConnection {
  62. // Ensure parent directory exists
  63. const dir = path.dirname(dbPath);
  64. if (!fs.existsSync(dir)) {
  65. fs.mkdirSync(dir, { recursive: true });
  66. }
  67. // Create and configure database
  68. const { db, backend } = createDatabase(dbPath);
  69. configureConnection(db);
  70. // Run schema initialization
  71. const schemaPath = path.join(__dirname, 'schema.sql');
  72. const schema = fs.readFileSync(schemaPath, 'utf-8');
  73. db.exec(schema);
  74. // Record current schema version so migrations aren't re-applied on open
  75. const currentVersion = getCurrentVersion(db);
  76. if (currentVersion < CURRENT_SCHEMA_VERSION) {
  77. db.prepare(
  78. 'INSERT OR IGNORE INTO schema_versions (version, applied_at, description) VALUES (?, ?, ?)'
  79. ).run(CURRENT_SCHEMA_VERSION, Date.now(), 'Initial schema includes all migrations');
  80. }
  81. return new DatabaseConnection(db, dbPath, backend);
  82. }
  83. /**
  84. * Open an existing database
  85. */
  86. static open(dbPath: string): DatabaseConnection {
  87. if (!fs.existsSync(dbPath)) {
  88. throw new Error(`Database not found: ${dbPath}`);
  89. }
  90. const { db, backend } = createDatabase(dbPath);
  91. configureConnection(db);
  92. // Check and run migrations if needed
  93. const conn = new DatabaseConnection(db, dbPath, backend);
  94. const currentVersion = getCurrentVersion(db);
  95. if (currentVersion < CURRENT_SCHEMA_VERSION) {
  96. runMigrations(db, currentVersion);
  97. }
  98. return conn;
  99. }
  100. /**
  101. * Get the underlying database instance
  102. */
  103. getDb(): SqliteDatabase {
  104. return this.db;
  105. }
  106. /**
  107. * Get the SQLite backend serving this connection. Per-instance so
  108. * MCP cross-project queries report the right backend even when
  109. * multiple project DBs are open in the same process.
  110. */
  111. getBackend(): SqliteBackend {
  112. return this.backend;
  113. }
  114. /**
  115. * Get database file path
  116. */
  117. getPath(): string {
  118. return this.dbPath;
  119. }
  120. /**
  121. * The journal mode actually in effect (e.g. 'wal', 'delete').
  122. *
  123. * SQLite silently keeps the prior mode if WAL can't be enabled — e.g. on
  124. * filesystems without shared-memory support (some network/virtualized mounts,
  125. * WSL2 /mnt). So the effective mode can differ
  126. * from what `configureConnection` requested. Surfaced in `codegraph status` so
  127. * a "database is locked" report is triageable: 'wal' ⇒ readers never block on a
  128. * writer; anything else ⇒ they can. See issue #238.
  129. */
  130. getJournalMode(): string {
  131. const raw = this.db.pragma('journal_mode');
  132. const row = Array.isArray(raw) ? raw[0] : raw;
  133. const mode = row && typeof row === 'object'
  134. ? (row as Record<string, unknown>).journal_mode
  135. : row;
  136. return String(mode ?? '').toLowerCase();
  137. }
  138. /**
  139. * Get current schema version
  140. */
  141. getSchemaVersion(): SchemaVersion | null {
  142. const row = this.db
  143. .prepare('SELECT version, applied_at, description FROM schema_versions ORDER BY version DESC LIMIT 1')
  144. .get() as { version: number; applied_at: number; description: string | null } | undefined;
  145. if (!row) return null;
  146. return {
  147. version: row.version,
  148. appliedAt: row.applied_at,
  149. description: row.description ?? undefined,
  150. };
  151. }
  152. /**
  153. * Execute a function within a transaction
  154. */
  155. transaction<T>(fn: () => T): T {
  156. return this.db.transaction(fn)();
  157. }
  158. /**
  159. * Get database file size in bytes
  160. */
  161. getSize(): number {
  162. const stats = fs.statSync(this.dbPath);
  163. return stats.size;
  164. }
  165. /**
  166. * Size of the `-wal` sidecar file in bytes. 0 when it doesn't exist (non-WAL
  167. * journal mode, in-memory DB, or no write since the last checkpoint+reset).
  168. */
  169. getWalSizeBytes(): number {
  170. if (!this.dbPath || this.dbPath === ':memory:') return 0;
  171. try {
  172. return fs.statSync(`${this.dbPath}-wal`).size;
  173. } catch {
  174. return 0;
  175. }
  176. }
  177. /** Current `wal_autocheckpoint` interval in pages (0 = disabled). */
  178. getWalAutocheckpoint(): number {
  179. const v = this.db.pragma('wal_autocheckpoint', { simple: true });
  180. const n = Number(v);
  181. return Number.isFinite(n) ? n : 0;
  182. }
  183. /**
  184. * Set the connection's `wal_autocheckpoint` interval (pages; 0 disables).
  185. * Bulk indexing defers checkpoints entirely (#1231): the default 1000-page
  186. * auto-checkpoint re-writes hot B-tree/FTS pages into the main DB file over
  187. * and over — measured at ~95% of ALL disk I/O during a bulk index, and the
  188. * difference between 45s and 19+ minutes on HDD-class storage. During
  189. * deferral a {@link WalCheckpointValve} bounds WAL growth off-thread.
  190. */
  191. setWalAutocheckpoint(pages: number): void {
  192. this.db.pragma(`wal_autocheckpoint = ${Math.max(0, Math.floor(pages))}`);
  193. }
  194. /**
  195. * `PRAGMA wal_checkpoint(PASSIVE)` on a worker thread with its own
  196. * connection. PASSIVE never blocks the writer, and running it off-thread
  197. * means the main thread — and the #850 watchdog heartbeat — keep turning
  198. * even when the backfill is minutes of I/O on slow storage (a synchronous
  199. * checkpoint that exceeds the watchdog's 60s window gets a healthy index
  200. * SIGKILLed — observed in the #1231 repro).
  201. *
  202. * Returns SQLite's checkpoint result row — `log === checkpointed` with
  203. * `busy === 0` means the ENTIRE WAL was backfilled, so the writer's next
  204. * commit restarts the WAL from the top and the file stops growing. The
  205. * WAL valve needs that signal because a WAL file's SIZE never shrinks:
  206. * after the first wrap, raw file size says nothing about the un-backfilled
  207. * backlog. Best-effort: returns null on any failure (including worker
  208. * threads being unavailable — a potentially minutes-long checkpoint must
  209. * never run inline on the main thread).
  210. */
  211. async checkpointWalPassive(): Promise<{ busy: number; log: number; checkpointed: number } | null> {
  212. if (!this.dbPath || this.dbPath === ':memory:') {
  213. try {
  214. const row = this.db.prepare('PRAGMA wal_checkpoint(PASSIVE)').get() as Record<string, number> | undefined;
  215. return row ? { busy: Number(row.busy), log: Number(row.log), checkpointed: Number(row.checkpointed) } : null;
  216. } catch {
  217. return null;
  218. }
  219. }
  220. try {
  221. const { Worker } = await import('node:worker_threads');
  222. const workerSource = `
  223. const { workerData, parentPort } = require('node:worker_threads');
  224. let row = null;
  225. try {
  226. const { DatabaseSync } = require('node:sqlite');
  227. const db = new DatabaseSync(workerData.dbPath);
  228. try { row = db.prepare('PRAGMA wal_checkpoint(PASSIVE)').get(); } catch {}
  229. try { db.close(); } catch {}
  230. } catch {}
  231. parentPort.postMessage({ row });
  232. `;
  233. return await new Promise((resolve) => {
  234. let settled = false;
  235. const finish = (row?: Record<string, number> | null): void => {
  236. if (settled) return;
  237. settled = true;
  238. resolve(row ? { busy: Number(row.busy), log: Number(row.log), checkpointed: Number(row.checkpointed) } : null);
  239. };
  240. try {
  241. const worker = new Worker(workerSource, { eval: true, workerData: { dbPath: this.dbPath } });
  242. worker.once('message', (m: { row?: Record<string, number> | null }) => { void worker.terminate(); finish(m?.row ?? null); });
  243. worker.once('error', () => { void worker.terminate(); finish(null); });
  244. worker.once('exit', () => finish(null));
  245. } catch {
  246. finish(null);
  247. }
  248. });
  249. } catch {
  250. return null;
  251. }
  252. }
  253. /**
  254. * Optimize database (vacuum and analyze)
  255. */
  256. optimize(): void {
  257. this.db.exec('VACUUM');
  258. this.db.exec('ANALYZE');
  259. }
  260. /**
  261. * Lightweight maintenance to run after bulk writes (indexAll, sync).
  262. * Two operations:
  263. *
  264. * - `PRAGMA optimize` — incremental ANALYZE; SQLite only re-analyzes
  265. * tables whose row counts changed materially since the last
  266. * ANALYZE. Without it, the query planner has no statistics on the
  267. * freshly-bulk-loaded tables and can pick suboptimal indexes.
  268. *
  269. * - `PRAGMA wal_checkpoint(PASSIVE)` — fold pending WAL pages back
  270. * into the main database file so the WAL file doesn't grow
  271. * unboundedly between automatic checkpoints (auto-fires at 1000
  272. * pages by default; large indexAll runs blow past that).
  273. *
  274. * Runs on a WORKER THREAD with its own connection: on a multi-GB index
  275. * these pragmas are minutes of synchronous IO (a 95k-file kernel index
  276. * left a 593MB WAL whose checkpoint alone blew the #850 watchdog's 60s
  277. * window and got a COMPLETED index SIGKILLed at the finish line). WAL
  278. * checkpointing from a second connection is standard SQLite; `PRAGMA
  279. * optimize` persists its statistics in sqlite_stat tables, so the main
  280. * connection benefits the same. The main thread just awaits a message,
  281. * so the event loop — and the watchdog heartbeat — keep turning.
  282. *
  283. * Everything is silently swallowed on failure — best-effort
  284. * optimization, never load-bearing for correctness. If worker threads
  285. * are unavailable, falls back to a bounded in-line `PRAGMA optimize`
  286. * and SKIPS the checkpoint (the final close() checkpoints after the
  287. * CLI has already disarmed its watchdog).
  288. */
  289. async runMaintenance(): Promise<void> {
  290. // In-memory / test databases: nothing worth a worker round-trip.
  291. if (!this.dbPath || this.dbPath === ':memory:') {
  292. try { this.db.exec('PRAGMA optimize'); } catch { /* ignore */ }
  293. try { this.db.exec('PRAGMA wal_checkpoint(PASSIVE)'); } catch { /* ignore */ }
  294. return;
  295. }
  296. await this.runPragmasOffThread(
  297. ['PRAGMA analysis_limit=1000', 'PRAGMA optimize', 'PRAGMA wal_checkpoint(PASSIVE)'],
  298. // Worker threads unavailable — bounded in-line fallback, no checkpoint.
  299. ['PRAGMA analysis_limit=1000', 'PRAGMA optimize']
  300. );
  301. }
  302. /**
  303. * Run pragmas on a worker thread against its own connection to this DB
  304. * (shared machinery for {@link runMaintenance} and
  305. * {@link checkpointWalPassive}). Each pragma is individually best-effort;
  306. * the whole call is best-effort. `inlineFallback` (if any) runs on THIS
  307. * connection only when worker threads are unavailable — keep it to pragmas
  308. * that are safe to run synchronously on the main thread.
  309. */
  310. private async runPragmasOffThread(pragmas: string[], inlineFallback: string[] = []): Promise<void> {
  311. try {
  312. const { Worker } = await import('node:worker_threads');
  313. const workerSource = `
  314. const { workerData, parentPort } = require('node:worker_threads');
  315. try {
  316. const { DatabaseSync } = require('node:sqlite');
  317. const db = new DatabaseSync(workerData.dbPath);
  318. for (const p of workerData.pragmas) { try { db.exec(p); } catch {} }
  319. try { db.close(); } catch {}
  320. } catch {}
  321. parentPort.postMessage('done');
  322. `;
  323. await new Promise<void>((resolve) => {
  324. let settled = false;
  325. const finish = (): void => {
  326. if (!settled) { settled = true; resolve(); }
  327. };
  328. try {
  329. const worker = new Worker(workerSource, { eval: true, workerData: { dbPath: this.dbPath, pragmas } });
  330. worker.once('message', () => { void worker.terminate(); finish(); });
  331. worker.once('error', () => { void worker.terminate(); finish(); });
  332. worker.once('exit', finish);
  333. } catch {
  334. finish();
  335. }
  336. });
  337. } catch {
  338. for (const p of inlineFallback) {
  339. try { this.db.exec(p); } catch { /* ignore */ }
  340. }
  341. }
  342. }
  343. /**
  344. * Close the database connection
  345. */
  346. close(): void {
  347. this.db.close();
  348. }
  349. /**
  350. * Check if the database connection is open
  351. */
  352. isOpen(): boolean {
  353. return this.db.open;
  354. }
  355. /**
  356. * True when the DB file at our path has been REPLACED on disk since we opened
  357. * it — a different inode now lives at the same path, so the fd we still hold
  358. * points at a now-unlinked inode that can never receive new writes (#925).
  359. * The trigger is removing and recreating `.codegraph/` at the same path under
  360. * a long-lived process (`git worktree remove` + re-add, or `rm -rf
  361. * .codegraph` + `codegraph init`). Returns false when the inode is unchanged,
  362. * when the file is momentarily absent (mid-recreate — nothing to reopen onto
  363. * yet), or when the platform doesn't report a usable inode (Windows can't
  364. * unlink an open file and its st_ino is unreliable, so this never fires there).
  365. */
  366. isReplacedOnDisk(): boolean {
  367. if (this.openedInode === null) return false;
  368. const current = statInode(this.dbPath);
  369. return current !== null && current !== this.openedInode;
  370. }
  371. }
  372. /**
  373. * `dev:ino` for a path, or null if it can't be stat'd or the platform doesn't
  374. * report a usable inode. Windows st_ino is unreliable across handle reopens, so
  375. * we deliberately return null there — the deleted-but-open-inode hazard this
  376. * guards (#925) is a POSIX file-semantics issue that doesn't arise on Windows
  377. * (an open file can't be unlinked).
  378. */
  379. function statInode(p: string): string | null {
  380. if (process.platform === 'win32') return null;
  381. try {
  382. const s = fs.statSync(p);
  383. return `${s.dev}:${s.ino}`;
  384. } catch {
  385. return null;
  386. }
  387. }
  388. /**
  389. * Default database filename
  390. */
  391. export const DATABASE_FILENAME = 'codegraph.db';
  392. /**
  393. * SQLite's sidecar files in WAL mode — the write-ahead log and its shared-memory
  394. * index. They sit beside the main DB file and are removed alongside it when the
  395. * database is discarded (see `removeDatabaseFiles`).
  396. */
  397. const WAL_SIDECAR_SUFFIXES = ['-wal', '-shm'] as const;
  398. /**
  399. * Get the default database path for a project
  400. */
  401. export function getDatabasePath(projectRoot: string): string {
  402. return path.join(getCodeGraphDir(projectRoot), DATABASE_FILENAME);
  403. }
  404. /**
  405. * Delete a database file and its WAL sidecars (`-wal`/`-shm`).
  406. *
  407. * This is how a FULL re-index discards an existing database — rather than
  408. * opening the old graph and DELETE-ing every row. On a large or pre-fix
  409. * poisoned index (e.g. an old graph that scanned an ignored gitlink corpus into
  410. * ~1.6M nodes with a multi-GB WAL, #1065) the per-row `nodes_fts` delete-trigger
  411. * churn blocks the main thread long enough to trip the #850 liveness watchdog
  412. * before indexing even starts, so the rebuild could never recover the bad state
  413. * (#1067). Unlinking is O(1) regardless of DB size and also reclaims the disk
  414. * the bloated WAL would otherwise keep.
  415. *
  416. * POSIX removes the directory entry even while another process (a daemon/MCP
  417. * server) still holds the file open; that holder heals via `reopenIfReplaced`
  418. * (#925). On Windows a live holder can make the unlink fail with EBUSY/EPERM —
  419. * that is thrown for the caller to surface ("stop the other process and retry").
  420. * The `-wal`/`-shm` sidecars are best-effort: SQLite recreates them on the next
  421. * open, so a leftover sidecar is harmless.
  422. */
  423. export function removeDatabaseFiles(dbPath: string): void {
  424. // The main DB file first — its removal is the operation that must succeed (or
  425. // report why it couldn't). force:true treats an already-missing file as done.
  426. fs.rmSync(dbPath, { force: true });
  427. for (const suffix of WAL_SIDECAR_SUFFIXES) {
  428. try {
  429. fs.rmSync(dbPath + suffix, { force: true });
  430. } catch {
  431. // A sidecar still held/locked is harmless — SQLite rebuilds it on open.
  432. }
  433. }
  434. }