`codegraph sync` is slow on HDD — the #1231 WAL-defer fix was never wired into the sync path
Follow-up to #1231 (fixed in PR #1242, shipped in v1.4.0). The full-index codegraph index path is now fast (~1 min on the same HDD where it previously took ~50 min). The incremental codegraph sync path is not — it reproduces the exact same symptom signature, because the fix lives only on the indexAll code path.
Environment
@colbymchenry/codegraphv1.4.0 (the release that fixed #1231)- Windows, 12-core CPU, project on a mechanical HDD (high random-I/O latency) — the same hardware as #1231
- AV: Huorong —
.codegraph/and the source tree both in its trust zone (no effect, same as #1231) - Project: Java, ~3,010 indexed files / 88k nodes / 166k edges (same index as #1231, now rebuilt cleanly in ~1 min)
Summary
codegraph sync on a tiny change set collapses to the same I/O-bound stall #1231 described, because the WAL autocheckpoint deferral that fixed indexAll (setWalAutocheckpoint(0) + WalCheckpointValve) was applied only to indexAll — the sync path never touches wal_autocheckpoint, so it stays at the default 1000 pages and re-triggers the same per-page checkpoint thrash that was ~95% of all disk I/O in #1231.
The smoking gun
Syncing 7 changed files (616 nodes) takes 2m 2s:
┌ Syncing CodeGraph
| * Scanning files
| * Parsing code - done
| * Resolving refs - done
│
◆ Synced 7 changed files
│
● Modified: 7 - 616 nodes in 2m 2s
│
└ Done
The symptom signature is identical to #1231: CPU 0–2% on 12 cores (not computing — waiting on I/O) and heavy random disk writes, decelerating over the run. A 616-node change cannot consume 2 minutes of CPU; it is the same main-thread I/O stall, just on the incremental path.
Note on attribution: the terminal output above reports a single total (
2m 2s); it does not break the time down per phase. Both write-bearing phases — the store loop (Parsing code) and reference resolution (Resolving refs, see below) — churn the same FTS5 index and the same 12 secondary indexes, so either (or both) can carry the bulk of the cost. The symptom and the fix do not depend on which one dominates: WAL-deferral helps both phases equally.
Root cause (verified against v1.4.0 source)
The #1242 fix is wired into indexAll and nowhere else. A repo-wide search for setWalAutocheckpoint / new WalCheckpointValve returns matches only in the indexAll body and its finally restore:
-
src/index.ts:448-461—indexAll:const deferWal = process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal'; if (deferWal) { priorAutocheckpoint = this.db.getWalAutocheckpoint(); this.db.setWalAutocheckpoint(0); // ← the #1231 win: disable autocheckpoint walValve = new WalCheckpointValve(...); walValve.start(); }(
src/db/index.ts:212-222documents the rationale: the default 1000-page autocheckpoint "re-writes hot B-tree/FTS pages into the main DB file over and over — measured at ~95% of ALL disk I/O during a bulk index, and the difference between 45s and 19+ minutes on HDD-class storage.") -
src/index.ts:643-659—CodeGraph.sync: nodeferWal, nosetWalAutocheckpoint, no valve. It calls straight through tothis.orchestrator.sync(...). -
src/extraction/index.ts:2255—orchestrator.sync: likewise never toucheswal_autocheckpoint.
So during sync, wal_autocheckpoint remains at 1000 pages (~4MB), and the #1231 thrash returns.
Why a 7-file change can take 2 minutes (cost is not proportional to the change size)
The cost here is not proportional to how much changed — it is proportional to how many times the checkpoint rewrites hot pages scattered across the large existing DB file. Two write-bearing phases both contribute:
- Store loop — for each modified file,
storeExtractionResult(src/extraction/index.ts:2120-2245) does a delete-then-insert, which is heavier than a fresh insert:deleteFile(:2165) cascadesON DELETE CASCADEthrough every edge, and the FTS5nodes_adtrigger fires for every deleted node (an external-content FTS5'delete',schema.sql:114-117);insertNodes(:2175) then fires the FTS5nodes_aitrigger + maintains 7 node indexes (schema.sql:89-95: kind / name / qualified_name / file_path / language / file_line / lower_name) per node;insertEdges(:2186) maintains 5 edge indexes (schema.sql:151-164,175: kind / (source,kind) / (target,kind) / identity-UNIQUE / provenance) per edge;- plus
getCrossFileIncomingEdgesWithTarget(:2160) — a query against the full graph per changed file. So a modified file churns the FTS5 index and the 7+5 indexes twice (delete + insert). - (Correction to an earlier reading: this does not include
name_segment_vocabcleanup. Perschema.sql:135-138, deletions leavename_segment_vocaborphans on purpose — rows are proposals, re-verified before use, and the table is cleared only at the start of a full index. There is no per-delete vocab maintenance.)
- Reference resolution —
CodeGraph.syncthen callsresolveAndPersist(src/index.ts:684) on the changed files' unresolved refs, which also writes edges (and thus maintains the 5 edge indexes). For a 616-node change set this can be a large ref volume, so resolution is a co-contributor to the same write churn — not a separate, negligible phase. - With
wal_autocheckpoint = 1000, that combined write volume crosses the checkpoint threshold repeatedly. Each RESTART checkpoint rewrites the hot B-tree/FTS pages back into the now-111 MB+ main DB file — scattered across the file, so on an HDD each checkpoint is hundreds of random seeks (~150 IOPS). syncparses serially on a single thread —src/extraction/index.ts:2382is a plainforloop withawait this.indexFile(filePath), not the 8-worker parse pool used byindexAll(src/extraction/index.ts:1553-1563). There is zero parse/store overlap, so the checkpoint stall is never hidden.
The terminal runMaintenance() call at src/index.ts:753 is fine — it is an off-thread wal_checkpoint(PASSIVE) (src/db/index.ts:321-333) and writes each page once, in order. The slow part is the N inline auto-checkpoints during the write phases themselves, not the final fold.
This is exactly the "throughput collapses regardless of how trivial the parse work is" behavior #1231 measured (0-byte files timing out); here the small change set just makes the non-proportionality obvious.
Why it wasn't caught internally
Same reason as #1231: the dev/test target is macOS on NVMe (CLAUDE.md). Random-I/O latency is ~50µs, so even with autocheckpoint left at the default the per-checkpoint stall never becomes visible. The architecture is only exposed on high-latency random-I/O storage (HDD, network/synced folders).
User-side mitigations (no code change)
- Move
.codegraph/to an SSD (mklink /J .codegraph D:\...\codegraph) — removes the random DB writes from the HDD entirely. Most effective;syncruns on every change, so the benefit is recurring. - Note:
CODEGRAPH_NO_WAL_DEFER/CODEGRAPH_WAL_VALVE_MBare indexAll-only knobs — there is no env lever for the sync path today.
Suggested fix
Wire the same full machinery indexAll uses into the sync path. WAL checkpointing is never load-bearing for correctness (SQLite replays the WAL on the next open; the fold is best-effort), so this is low-risk — but the machinery must be complete, not a stripped-down version.
Wire it in CodeGraph.sync (src/index.ts:643), not orchestrator.sync. WAL policy belongs in the layer that owns the db connection and already owns it for indexAll; the orchestrator should not know about checkpoint strategy. Mirror the indexAll lifecycle exactly:
- Setup — before the store+resolution work, capture the interval, defer, and start the valve (mirror
src/index.ts:448-461):const deferWal = process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal'; if (deferWal) { priorAutocheckpoint = this.db.getWalAutocheckpoint(); this.db.setWalAutocheckpoint(0); walValve = new WalCheckpointValve(this.db, undefined, undefined, options.verbose ? (m)=>console.log(`[wal-valve] ${m}`) : undefined); walValve.start(); } - Fold before the resolution reads — call
await walValve.foldNow()between the store loop and the first resolution read (mirrorsrc/index.ts:485). Resolution reads page the WAL; an unfolded bulk-write WAL is exactly what blew the #850 watchdog's 60s window in the #1231 repro. - Backpressure into the store loop — pass
() => walValve!.backpressure()intoorchestrator.sync(mirrorsrc/index.ts:477) so a saturated disk can park the writer between transactions instead of growing the WAL without bound. - Final fold — before the existing
runMaintenance()call,walValve.stop(); await walValve.drain()(mirrorsrc/index.ts:543), otherwise the valve's in-flight checkpoint and the maintenance checkpoint contend for the checkpointer lock and one silently no-ops, leaving the WAL unfolded. The already-calledrunMaintenance()(src/index.ts:753) then performs the single sequentialwal_checkpoint(PASSIVE)fold-back. - Restore in
finally—setWalAutocheckpoint(priorAutocheckpoint)(mirrorsrc/index.ts:609-612) so the next ordinary write doesn't inherit a deferred interval. - Env parity — extend
CODEGRAPH_NO_WAL_DEFER/CODEGRAPH_WAL_VALVE_MBto the sync path so it has the same knobsindexAlldoes. - Scope — the deferral must bracket both write phases (store loop + resolution), since both write and both benefit.
Why the valve IS needed (do not skip it)
A tempting simplification is to defer wal_autocheckpoint to 0 and rely on runMaintenance() alone, arguing that a 7-file / 616-node sync is tiny so the valve's 256 MB soft threshold "would almost never trigger." That holds only for tiny syncs. sync is the general incremental path — it also handles large change sets (a git pull touching hundreds of files, a vendored-dependency update, a fresh checkout), and it runs on every change via the daemon's liveness-watchdog thread. Skipping the valve reintroduces precisely the failure mode the valve was built to prevent (src/db/wal-valve.ts:12-44): unbounded deferral is its own failure mode — the WAL duplicates hot pages per COMMIT and grows far faster than the DB (measured: a 5.9 GB WAL for a ~340 MB DB at 150 IOPS), filling the disk and poisoning every subsequent read until the #850 watchdog kills a healthy process. Reuse the full indexAll machinery; do not ship a valve-less deferral.
Invariants preserved: STORE_CHUNK=2000 store-yield (#850), deterministic per-file store order, no correctness change, and no retrieval-latency change beyond the already-expected fold.
Repro
On a Windows machine with the project on an HDD (the same setup as #1231), with an already-built index:
codegraph sync
after touching a handful of files. Watch: CPU stays 0–2%, heavy random disk writes during the Parsing code / Resolving refs steps, and a multi-second-per-file cost that is wildly out of proportion to the change size.
Fixed in #1312 (merged to main, ships in the next release).
Your source-level diagnosis was exactly right — the deferral existed only in indexAll. sync now mirrors it completely: autocheckpoint deferred for the whole incremental run (store loop and both resolution passes, per your note that either can carry the cost), the store phase's WAL folded off-thread before post-store reads, and the interval restored at the end. Same CODEGRAPH_NO_WAL_DEFER=1 kill switch, and an idle valve costs one timer so watcher-driven syncs stay cheap.
Regression tests sample the autocheckpoint interval from inside the sync's own progress callback (mid-store-loop, where the thrash lived) and pin 0-during / 1000-after on both the changed-files and no-change paths.
I don't have HDD hardware to re-time it, but the mechanism is identical to the #1242 fix you measured at ~50 min → ~1 min — if you can spot-check a codegraph sync on the same Java index once the release lands, I'd love the number for the record.