Skip to content
Source
Sign inSign up
pingdotgg/t3code

[Bug]: 100 ms idle WAL checkpoint doubles the server's disk writes on macOS (~200 MiB/min while agents run) #38159

Openbaohappy02(GitHub profile, opens in a new tab) opened this issue 4 comments

Before submitting

  • I searched existing issues and did not find a duplicate.
  • I included enough detail to reproduce or investigate the problem.

Area

apps/desktop

Steps to reproduce

Related to #37600 (page fan-out per commit); this one is about when the checkpoint worker runs.

  1. On macOS, run a few agent threads.
  2. Compare the server's disk writes (ri_diskio_byteswritten) with the WAL bytes and WAL resets read from statev2.sqlite-wal / -shm.

Repro (macOS, Python sqlite3): commits 8 updated 3 KB rows at random gaps (mean 160 ms) with T3's pragmas (WAL, synchronous=NORMAL, checkpoint_fullfsync=ON), checkpointing from a second connection like T3's worker (idle: PASSIVE after a 100 ms pause, or at 1000 frames) or only at 1000 frames (frames); prints bytes written per WAL byte.

python3 paced.py /tmp/ck idle 1      # makes the base db once
python3 paced.py /tmp/ck idle 40
python3 paced.py /tmp/ck frames 40
# usage: paced.py DIR idle|frames SECONDS [GAP_MS] [ROWS]
import ctypes, os, random, shutil, sqlite3, struct, sys, time
libc = ctypes.CDLL(None); buf = ctypes.create_string_buffer(512)
def w():
    libc.proc_pid_rusage(os.getpid(), 2, buf); return struct.unpack_from("QQ", buf, 144)[1]
d, pol, S = sys.argv[1], sys.argv[2], float(sys.argv[3])
gap = float(sys.argv[4]) / 1000 if len(sys.argv) > 4 else 0.16; rows = int(sys.argv[5]) if len(sys.argv) > 5 else 8
p = os.path.join(d, f"p-{pol}.sqlite")
base = os.path.join(d, "base.sqlite"); os.makedirs(d, exist_ok=True)
if not os.path.exists(base):
    b = sqlite3.connect(base, isolation_level=None); b.execute("create table t(id integer primary key, k text, v text)"); b.execute("create index ik on t(k)")
    b.execute("begin")
    for i in range(20000): b.execute("insert into t(k,v) values(?,?)", (os.urandom(8).hex(), "x" * 3000))
    b.execute("commit"); b.close(); sys.exit("base made; run again")
for s in ("", "-wal", "-shm"):
    if os.path.exists(p + s): os.remove(p + s)
shutil.copy(base, p); time.sleep(3)
c = sqlite3.connect(p, isolation_level=None); ck = sqlite3.connect(p, isolation_level=None)
for x in (c, ck): x.execute("pragma journal_mode=wal"); x.execute("pragma synchronous=normal"); x.execute("pragma checkpoint_fullfsync=on")
c.execute("pragma wal_autocheckpoint=0")
w0 = w(); frames = commits = ckpts = pending = 0
t0 = time.time()
while time.time() - t0 < S:
    c.execute("begin")
    for _ in range(rows): c.execute("update t set v=?, k=? where id=?", (os.urandom(4).hex() * 375, os.urandom(8).hex(), random.randint(1, 20000)))
    c.execute("commit"); commits += 1
    log = ck.execute("pragma wal_checkpoint(noop)").fetchone()[1]
    frames += max(log - pending, 0) if log >= pending else log; pending = log
    g = random.expovariate(1 / gap); time.sleep(g)
    if (pol == "idle" and g >= 0.1) or log >= 1000:
        ck.execute("pragma wal_checkpoint(passive)"); ckpts += 1
os.sync(); dt = time.time() - t0; b = w() - w0
print(f"{pol}: {ckpts} checkpoints, wrote {b/max(frames*4120,1):.2f}x WAL bytes, {b/2**20*60/dt:.0f} MiB/min")

Expected behavior

While events keep streaming, the WAL is checkpointed in batches (CHECKPOINT_FRAMES = 1000), so disk writes stay near the WAL bytes plus one copy into the database file.

Actual behavior

packages/shared/src/nodeSqliteClient.ts:641 (tag v0.1.11-nightly.20261117.4825) sets CHECKPOINT_IDLE_MS = 100: the checkpoint worker runs a PASSIVE checkpoint after any 100 ms pause in writes. A streaming turn pauses that long between events many times a minute, so the worker checkpoints ~134 times a minute, each with checkpoint_fullfsync = ON (F_FULLFSYNC on macOS), and the WAL restarts each time.

Live server, macOS, APFS, a few agent threads streaming:

measurevalue
server process disk writes181-233 MiB/min (3 windows of 1-3.5 min); ~280 GiB/day at 200 MiB/min
WAL bytes appended49-65 MiB/min
commits372-551/min, ~30 frames each
WAL resets (full checkpoints)~134/min
event payload + metadata stored1.17 MiB/min (557 events/min)

Process writes are ~4x the WAL bytes. The repro above, 40 s runs:

policyprocess writes / WAL bytesMiB/mincheckpoints
idle (T3's: 100 ms pause or 1000 frames)5.68x, 6.22x, 6.26x, 6.51x154-165123-149
frames only (1000 frames)2.72x, 2.74x, 2.75x, 2.93x84-985-6

Same commits, about half the bytes once the 100 ms idle checkpoint is gone. (One more frames run, the first right after copying the base file, read 26.88x; left out as the copy's writeback counted to the process.)

The same constant and worker are in v0.1.9-nightly.20261110.4452 and v0.1.10-nightly.20261116.4774.

Possible fix: while writes keep coming, checkpoint only at CHECKPOINT_FRAMES; run the idle catch-up checkpoint only after a long quiet (seconds, e.g. 5-30 s) or on close. Cost: up to ~4 MB more WAL between checkpoints, and under synchronous = NORMAL a longer window of commits an OS crash or power loss can roll back (no corruption).

Impact

Blocks work completely

Version or commit

v0.1.11-nightly.20261117.4825 (desktop, Nightly)

Environment

macOS 26.5.1, Apple Silicon (arm64), APFS internal SSD

Logs or stack traces

Screenshots, recordings, or supporting files

No response

Workaround

None found from outside the app.

  1. baohappy02(GitHub profile, opens in a new tab) added labelsneeds-triage

  2. Note

    🤖 GPT-6.1 Sol on behalf of JarenKempton

    Frequent WAL restarts also occur on Linux with a NOCOW database directory; this is not limited to macOS/APFS.

    On 0.1.11-nightly.20261118.4903, a 180-second read-only capture recorded 117 WAL restarts, with 3–190 frames per generation. The database was approximately 13.3 GB, using 4 KiB pages.

    A replay model of the captured page sequence estimated the following checkpoint-copy volume:

    Modeled policyPages copiedApproximate bytes
    Current 100 ms idle policy7,48630.7 MB
    Every 1,000 frames, without idle checkpoints4,11616.9 MB
    Every 4,000 frames, without idle checkpoints2,76211.3 MB

    These are simulation estimates, not before/after measurements of a patched server. They do not measure filesystem amplification or establish crash-durability behavior.

    The result supports testing a longer idle interval independently of changes to per-event writes. Any change should explicitly evaluate the power-loss durability trade-off under synchronous=NORMAL, alongside WAL bounds and checkpoint latency.

  3. Same mechanism on Linux, where the cost shows up as fsyncs more than bytes.

    Setup: T3 Code 0.1.11 desktop (AppImage), btrfs root with zstd compression, NVMe. A 300 s bpftrace on btrfs_sync_file found 454 fsyncs on statev2.sqlite and statev2.sqlite-wal (about 1.5 a second), all from the server's WorkerThread, with 127.7 MiB written inside those fsyncs. The agents' own processes made none.

    Why btrfs cares: each fsync on btrfs commits a log tree, so the cost is the forced metadata write per fsync, on top of the data. Under synchronous = NORMAL commits are free; the checkpoint worker's 100 ms idle catch-up (CHECKPOINT_IDLE_MS in packages/shared/src/nodeSqliteClient.ts) turns almost every provider commit batch into a full PASSIVE checkpoint: WAL fsync, database fsync, then a WAL-header fsync when the next write restarts the log.

    Replay on Linux: the paced.py repro from this issue, ported to node:sqlite and run in the app's own Electron runtime (SQLite 3.53.4), 60 s per policy, 8 × 3 KB row updates per commit at a 160 ms mean gap:

    checkpoint policycommitscheckpointsprocess write_bytes
    1000 frames or 100 ms idle (current)351189118 MiB
    1000 frames only363897 MiB

    That is 24 times fewer checkpoints, so at least 24 times fewer fsyncs, and 18 % fewer bytes at the page-cache level before counting btrfs metadata.

    Asks, in order of preference:

    1. Drop the 100 ms idle catch-up, or raise it to tens of seconds. The 1000-frame threshold and the 10000-frame writer backstop already bound the WAL, and journal_size_limit (128 MiB) already caps the file. If the catch-up exists to let the WAL restart, a TRUNCATE or RESTART checkpoint on a long idle (for example 30 to 60 s with no writes) gets that without one checkpoint per batch.
    2. Whatever the default, expose the two knobs, for example T3CODE_SQLITE_CHECKPOINT_FRAMES and T3CODE_SQLITE_CHECKPOINT_IDLE_MS, so people on write-sensitive disks can tune them without patching the bundle.

    Happy to run a patched build and report btrfs fsync counts before and after.


    Written by Claude Opus 5.5 (high effort) from our measurements; reviewed and approved for posting by Micah.

  4. We observed frequent WAL restarts on macOS with 0.1.12-nightly.20261125.5230. #38170 notes the fix was not measured on macOS, so here are read-only numbers from a live desktop server (macOS 27.0.1, Apple Silicon, internal APFS SSD):

    • The bundled nodeSqliteClient still has CHECKPOINT_IDLE_MS = 100, CHECKPOINT_FRAMES = 1e3 and checkpoint_fullfsync = ON in the checkpoint worker.
    • statev2.sqlite is 16.1 GB (4 KiB pages, WAL mode).
    • In a 540 s read-only sample of statev2.sqlite-wal/-shm, the sampler observed 745 WAL restarts (WAL-index salt changes, 83 per minute) and estimated 70,393 appended frames (290 MB of WAL frames, 0.54 MB/s).
    • The server process (ri_diskio_byteswritten) had accumulated about 124 GB after 13 h 20 min and added 3.54 GB over the next 26 minutes (2.27 MB/s, about 196 GB/day at that rate). Over the same window, the block-device counter for the internal SSD (disk0) rose by 20.45 GB. The increase in the server's process counter was about 17% of that amount.

    We have not run a patched build, so there are no before/after numbers here.


    🤖 Agent:66a37f4f on behalf of @mikeqwe

  5. Note

    Measured and written by Claude Opus 5.5 via Claude Code in T3 Code (t3 triage playbook); reviewed and approved for posting by @WavJaby.

    Same checkpoint pattern on Windows. Read-only measurements of a live server; no patched build was run.

    Environment: Windows 11 x64 (10.0.26300), desktop-app server 0.1.12-nightly.20261124.5191, statev2.sqlite 7.2 GB, 4 KiB pages. CHECKPOINT_IDLE_MS is 100 in that build and on main today.

    Four windows while agents ran (Windows process I/O counters, which include pipes and OS-cache hits; WAL frames and salt changes from -shm, polled every 250 ms, so WAL bytes and resets are lower bounds):

    windowprocess writesWAL bytesWAL resetsresets/min
    100 s43.1 MB19.6 MB6338
    110 s156.1 MB75.6 MB16288
    150 s318.3 MB107.5 MB264106
    270 s169.6 MB77.6 MB25156

    Estimated copy-back, same 270 s window (WAL frames polled every 30 ms: 19,278 frames, 79.4 MB; distinct pages per checkpoint, replayed over the recorded page sequence):

    policypages copied backMBWAL + copy-back
    observed WAL resets (259)15,85264.9144.4 MB
    every 1,000 frames7,55430.9110.4 MB
    every 10,000 frames3,93616.195.5 MB

    Checkpointing only at 1,000 frames would cut copy-back by 52% and the SQLite total by about 24% in this replay. SQLite (144.4 MB) is about 85% of the process writes in that window; the rest is not attributed.

    Over 6.2 days the same process wrote 190.7 GB (30.7 GB/day), by the same counters.

Sign in to join this conversation.