wal-valve.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /**
  2. * WAL checkpoint valve — bounds WAL growth while auto-checkpointing is
  3. * deferred during a bulk index (#1231).
  4. *
  5. * Why deferral: SQLite's default `wal_autocheckpoint` (1000 pages) re-writes
  6. * hot B-tree/FTS pages into the main DB file over and over during a bulk
  7. * index — measured at ~95% of ALL disk I/O, and the difference between 45s
  8. * and 19+ minutes on HDD-class storage (150 random IOPS). Deferring
  9. * checkpoints turns the store into pure sequential WAL appends; each backfill
  10. * pass writes distinct pages once, in page order (≈ sequential).
  11. *
  12. * Why a valve: unbounded deferral is its own failure mode, both measured in
  13. * the #1231 repro. The WAL duplicates hot pages per COMMIT, so it grows far
  14. * faster than the DB (5.9GB WAL for a ~340MB DB on a 3.3k-file index) —
  15. * filling the disk, and poisoning every subsequent read that must page
  16. * through it (the first resolution-phase read blocked the main thread >60s
  17. * and the #850 liveness watchdog killed the healthy index). The valve
  18. * watches WAL growth on a timer and, past a soft threshold, backfills with
  19. * `PRAGMA wal_checkpoint(PASSIVE)` on a worker-thread connection — PASSIVE
  20. * never blocks the writer, and off-thread means the main thread (and the
  21. * watchdog heartbeat) keep turning regardless of how long a backfill takes.
  22. *
  23. * The load-bearing subtlety: a WAL file's SIZE never shrinks. After a full
  24. * backfill, the writer's next commit RESTARTS the WAL from the top and the
  25. * frames recycle inside the same file — so raw size says nothing about the
  26. * un-backfilled backlog, and a size-triggered valve degenerates into firing
  27. * (and pausing the writer) forever once the file passes its threshold
  28. * (measured: guava crawled at ~9min per 160 files). Instead the valve
  29. * tracks `sizeAtLastFullBackfill` — refreshed whenever a checkpoint reports
  30. * `log === checkpointed` (everything backfilled) — and triggers on GROWTH
  31. * beyond that baseline, which only happens when genuinely un-backfilled
  32. * frames push past the file's high-water mark.
  33. *
  34. * Backpressure: if the writer outruns the checkpointer past a hard cap of
  35. * growth (2× soft), {@link backpressure} pauses the writer (at a safe,
  36. * between-transactions boundary) until a FULL backfill lands. One in-flight
  37. * pass is not enough: on a disk saturated by the writer, every concurrent
  38. * PASSIVE pass is already stale by the time it finishes (the writer appended
  39. * past its snapshot), so neither SQLite's WAL wrap nor the baseline ever
  40. * trigger and the WAL grows without bound (measured: 5.9GB on guava at 150
  41. * IOPS, then a >60s read stall and a watchdog kill). With the writer parked,
  42. * the next pass covers everything, the WAL wraps on the following commit,
  43. * and the pause is the disk's honest catch-up cost — the correct terminal
  44. * mode when hardware genuinely can't keep up with the append rate.
  45. */
  46. import type { DatabaseConnection } from './index';
  47. /** Soft WAL-growth threshold (MB) that triggers an off-thread passive checkpoint. */
  48. const DEFAULT_WAL_VALVE_MB = 256;
  49. /** Hard cap = this × soft threshold; past it the writer pauses for a full backfill. */
  50. const HARD_CAP_MULTIPLIER = 2;
  51. /** Passes attempted per writer pause before giving up (a pinned reader could stall forever). */
  52. const MAX_PAUSED_BACKFILL_PASSES = 20;
  53. /** How often the timer looks at the WAL file size. */
  54. const CHECK_INTERVAL_MS = 2000;
  55. /**
  56. * Resolve the valve's soft threshold from the `CODEGRAPH_WAL_VALVE_MB`
  57. * override; non-numeric / non-positive values fall back to the default.
  58. */
  59. export function resolveWalValveMb(envVal: string | undefined): number {
  60. if (envVal !== undefined && envVal !== '') {
  61. const n = Number(envVal);
  62. if (Number.isFinite(n) && n > 0) return Math.floor(n);
  63. }
  64. return DEFAULT_WAL_VALVE_MB;
  65. }
  66. export class WalCheckpointValve {
  67. private timer: ReturnType<typeof setInterval> | null = null;
  68. private inflight: Promise<void> | null = null;
  69. /** Writer pause in progress (hard cap breached): passes loop until a full backfill. */
  70. private pause: Promise<void> | null = null;
  71. /**
  72. * WAL file size observed when a checkpoint last reported the ENTIRE WAL
  73. * backfilled. Growth is measured against this baseline — see the header
  74. * comment for why absolute size cannot be used.
  75. */
  76. private sizeAtLastFullBackfill = 0;
  77. private readonly softBytes: number;
  78. private readonly hardBytes: number;
  79. constructor(
  80. private readonly db: DatabaseConnection,
  81. softMb: number = resolveWalValveMb(process.env.CODEGRAPH_WAL_VALVE_MB),
  82. private readonly intervalMs: number = CHECK_INTERVAL_MS,
  83. private readonly log: (msg: string) => void = () => {}
  84. ) {
  85. this.softBytes = softMb * 1024 * 1024;
  86. this.hardBytes = this.softBytes * HARD_CAP_MULTIPLIER;
  87. }
  88. private mb(n: number): string {
  89. return `${Math.round(n / 1024 / 1024)}MB`;
  90. }
  91. /** Un-backfilled growth estimate: bytes the WAL has grown past the last full backfill. */
  92. private growthBytes(): number {
  93. return this.db.getWalSizeBytes() - this.sizeAtLastFullBackfill;
  94. }
  95. /** Begin watching the WAL. Idempotent; the timer never holds the loop open. */
  96. start(): void {
  97. if (this.timer) return;
  98. this.timer = setInterval(() => this.check(), this.intervalMs);
  99. this.timer.unref?.();
  100. }
  101. /** Stop watching. Any in-flight checkpoint keeps running — await drain(). */
  102. stop(): void {
  103. if (this.timer) {
  104. clearInterval(this.timer);
  105. this.timer = null;
  106. }
  107. }
  108. /** One poll: fire an off-thread passive checkpoint when growth passes the soft threshold. */
  109. check(): void {
  110. if (!this.pause && !this.inflight && this.growthBytes() > this.softBytes) this.fire();
  111. }
  112. /**
  113. * Writer-side backstop, called at a between-transactions boundary. Returns
  114. * null (no wait) while growth is under the hard cap; past it, returns a
  115. * promise that resolves only once a FULL backfill has landed — see the
  116. * header comment for why a single pass is not enough on a saturated disk.
  117. */
  118. backpressure(): Promise<void> | null {
  119. if (this.pause) return this.pause;
  120. if (this.growthBytes() <= this.hardBytes) return null;
  121. this.log(`backpressure: wal=${this.mb(this.db.getWalSizeBytes())} baseline=${this.mb(this.sizeAtLastFullBackfill)} — pausing writer for full backfill`);
  122. const t0 = Date.now();
  123. this.pause = this.backfillFully().finally(() => {
  124. this.pause = null;
  125. this.log(`backpressure released after ${Date.now() - t0}ms: wal=${this.mb(this.db.getWalSizeBytes())} baseline=${this.mb(this.sizeAtLastFullBackfill)}`);
  126. });
  127. return this.pause;
  128. }
  129. /** Await any in-flight checkpoint and writer pause. */
  130. async drain(): Promise<void> {
  131. while (this.pause || this.inflight) {
  132. if (this.pause) await this.pause;
  133. if (this.inflight) await this.inflight;
  134. }
  135. }
  136. /**
  137. * Phase-boundary fold: backfill the ENTIRE WAL now (off-thread, awaited).
  138. * Called between bulk phases — e.g. after parsing, before resolution's
  139. * first reads — so the next phase never pages a bulk-write-sized WAL on
  140. * the main thread (the post-parse read against a multi-GB WAL is what
  141. * blew the #850 watchdog's 60s window in the #1231 repro). The await
  142. * keeps the event loop (and the watchdog heartbeat) turning.
  143. */
  144. async foldNow(): Promise<void> {
  145. await this.drain();
  146. if (this.growthBytes() <= 0) return;
  147. this.log(`foldNow: wal=${this.mb(this.db.getWalSizeBytes())} baseline=${this.mb(this.sizeAtLastFullBackfill)}`);
  148. this.pause = this.backfillFully().finally(() => { this.pause = null; });
  149. await this.pause;
  150. }
  151. /**
  152. * With the writer parked on the returned promise, loop passive passes until
  153. * one reports the entire WAL backfilled (typically the second: the first
  154. * drains the pass that was already running against a stale snapshot). Gives
  155. * up after a bounded number of passes — e.g. a reader pinning the WAL —
  156. * because unbounded WAL growth degrades; a wedged writer never recovers.
  157. */
  158. private async backfillFully(): Promise<void> {
  159. for (let i = 0; i < MAX_PAUSED_BACKFILL_PASSES; i++) {
  160. if (this.inflight) await this.inflight; // fold in the stale in-flight pass first
  161. const res = await this.db.checkpointWalPassive();
  162. if (!res) return; // checkpoint machinery unavailable — don't spin
  163. this.log(`backfill pass ${i + 1}: busy=${res.busy} log=${res.log} checkpointed=${res.checkpointed} wal=${this.mb(this.db.getWalSizeBytes())}`);
  164. if (res.busy === 0 && res.log === res.checkpointed) {
  165. this.sizeAtLastFullBackfill = this.db.getWalSizeBytes();
  166. return;
  167. }
  168. }
  169. this.log(`backfill gave up after ${MAX_PAUSED_BACKFILL_PASSES} passes — WAL stays unbounded this cycle`);
  170. }
  171. private fire(): void {
  172. const p = this.db
  173. .checkpointWalPassive()
  174. .then((res) => {
  175. // Full backfill (busy 0, every log frame checkpointed) ⇒ the writer's
  176. // next commit wraps the WAL; the file's current size becomes the new
  177. // growth baseline. A partial pass (writer appended during it, or a
  178. // read transaction pinned frames) leaves the baseline alone, so the
  179. // next tick fires again and copies the remainder. In non-WAL mode
  180. // SQLite reports log = checkpointed = -1, which is harmless here.
  181. if (res && res.busy === 0 && res.log === res.checkpointed) {
  182. this.sizeAtLastFullBackfill = this.db.getWalSizeBytes();
  183. }
  184. })
  185. .catch(() => { /* best-effort */ })
  186. .finally(() => {
  187. if (this.inflight === p) this.inflight = null;
  188. });
  189. this.inflight = p;
  190. }
  191. }