Skip to content

fix(state): pace the recovery snapshot behind live commits - #2099

Merged
frahlg merged 1 commit into
masterfrom
state-snapshot-yields
Nov 28, 2026
Merged

frahlg merged 1 commit into
masterfrom
state-snapshot-yields

Conversation

@frahlg

@frahlg frahlg commented Nov 28, 2026

Copy link
Copy Markdown
Member

Refs #1554

Problem

Field support files from two ARM64 sites show most history commit failures in the minute the state snapshot runs: two minutes after boot and at each 24 h tick. Each failure passed on retry and no tick was lost, but #1554 holds stable until the cause is found and fixed.

SnapshotState copied state.db with one INSERT ... SELECT per table into an attached file. Each table went over in one transaction, so a whole table stayed dirty until one fsync at commit. On a slow card, live history commits (synchronous FULL) and config writes waited behind that fsync. The backup path already avoids this: short synced batches and a pause between them.

Change

  • SnapshotTo now uses the live backup's state copy (copyStateForBackup, split into copyStateTables so each caller names its own excluded tables). It copies from one read transaction on state.db, writes rows in batches of at most 1,024 rows or 256 KiB, commits and syncs each batch, checks every table against the source by row count and hash, and calls backupCopyYield between batches. That pause is pauseMaintenance, the same 100 ms yield backups and archives use. It comes about once per second of copying, and after every batch while 16 or more history ticks wait.
  • The snapshot keeps the same table set (snapshotExcludedTables) and the same quick_check before the rename.
  • Two guarantees are new. The copy is one point in time across all tables; before, each table was its own transaction. And it keeps sqlite_sequence, so a restored control journal no longer hands out an id a deleted row had (the old copy set it to the highest id still present).
  • quick_check stays. It reads only the new file and holds no lock on state.db or history.db. In the rig, commits that started while it ran took at most 565 ms.
  • SnapshotState also removes a -journal, -wal or -shm left beside the temp file by an interrupted copy.
  • The ATTACH helpers (snapshotTableCopyOrder, rewriteCreateForAttachedDB) go. The destination has foreign keys off, as in the backup, so copy order no longer matters.

Evidence

Slow-storage rig

TestStateSnapshotLiveHistoryLatency (new, skipped unless FTW_SNAPSHOT_LATENCY_DIR is set) builds a state.db with a 150 MiB snapshot: the forecast tables about halfway to their retention budgets, plus events and the control journal. It also builds a 267 MiB history.db with five days of 10 s buckets for 60 series. It then runs the real history writer with its real 5 s deadline. One tick of 60 samples comes every 2 s, Core's default control interval, and each tick is committed on its own so every interval gives a sample. A config write runs every second. Between 20 s quiet windows the test copies the snapshot and runs quick_check.

The rig is arm64 Linux 7.2 in a privileged Docker container on an Apple-silicon Mac (--cpus=2, the python:3.12-slim-bookworm image because it has mkfs.ext4): ext4 on a loop device backed by tmpfs. Between the phases the test remounts the file system to drop its page cache. It then throttles the loop device through the container's cgroup v2 io.max. A 16 MiB dd conv=fsync takes 2.0 s at the 8 MiB/s setting and 4.0 s at 4 MiB/s, as set.

GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go test -c -o state.test ./internal/state
docker run --rm --privileged --cgroupns=host --cpus=2 --tmpfs /ram:size=3500m -v "$PWD":/h:ro \
  python:3.12-slim-bookworm sh -c '
  truncate -s 3G /ram/sd.img; dev=$(losetup -f --show /ram/sd.img); mkfs.ext4 -q $dev
  mkdir /sd; mount -o noatime $dev /sd
  FTW_SNAPSHOT_LATENCY_DIR=/sd/data FTW_SNAPSHOT_LATENCY_PHASE=prepare /h/state.test -test.run LiveHistoryLatency -test.v
  umount /sd; mount -o noatime $dev /sd
  echo "$(cat /sys/block/${dev#/dev/}/dev) rbps=41943040 wbps=8388608 riops=1500 wiops=400" \
    > /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/io.max
  FTW_SNAPSHOT_LATENCY_DIR=/sd/data FTW_SNAPSHOT_LATENCY_PHASE=measure /h/state.test -test.run LiveHistoryLatency -test.v
  umount /sd; losetup -d $dev'

These are commits and writes that started during the snapshot copy. Before is master at 97c2d34 with the new test file; after is this branch.

Write limit Run Code Snapshot copy History commits: p50 / max (over 1 s) Config writes: max
8 MiB/s 1 before 22.9 s 2.68 s / 5.32 s (3 of 5) 5.60 s
8 MiB/s 1 after 26.9 s 97 ms / 481 ms (0 of 9) 66 ms
8 MiB/s 2 before 22.7 s 3.14 s / 5.31 s (3 of 4) 5.42 s
8 MiB/s 2 after 27.0 s 125 ms / 302 ms (0 of 8) 113 ms
4 MiB/s 1 before 46.6 s 7.63 s / 12.68 s (5 of 6) 11.67 s
4 MiB/s 1 after 51.9 s 185 ms / 893 ms (0 of 14) 123 ms

Outside the snapshot, the median commit took 10–40 ms in every run, before and after. No commit failed in any run: on this rig a late commit still lands once its fsync returns. In the field, some ran out the deadline and were retried.

quick_check took 83–127 ms in five of the six runs. In the slow-card run on old code it took 21 s, and the five commits that started in that window took at most 565 ms.

Suite

New tests in snapshot_pace_test.go, all failing on origin/master and passing here:

  • TestSnapshotYieldsBetweenShortSyncedBatches: copying 4 MiB yields at least 8 times, with at most 1 MiB written between yields. Old code: "snapshot yielded 0 times".
  • TestSnapshotCopiesOnePointInTime: writes made during a pause, to a table copied earlier and to one copied later, are both absent from the snapshot. Old code: "snapshot never yielded".
  • TestSnapshotKeepsAutoincrementHighWaterMark: old code: "sequence = 2 ... want 3".

Runs:

  • go test ./internal/state/ -count=1: ok (49 s)
  • go test -race ./internal/state/ -run 'Snapshot|Backup|Recover|Marker' -count=2: ok
  • make verify (rebased on d43e80d): ok, "verify: vet + test + build clean"

Not tested

  • A real ARM64 board and SD card. The rig throttles one loop device with io.max; it does not show SD card firmware stalls, reads and writes sharing one budget (blk-throttle keeps them apart), or jbd2 journal writes (they run in the root cgroup and are not throttled). It also runs on Apple-silicon cores that are faster than a Pi's.
  • Native beta: trace recurring history write deadlines before stable #1554 asks for a fresh field trial on the next beta, and this PR does not close it.
  • The other failures in the field data, a 5 s writer_lock wait just after the hour and a forecast-archive write timeout, are not addressed here.

For Fredrik

  • Whether this goes into the next beta, which then needs the fresh ARM64 field trial Native beta: trace recurring history write deadlines before stable #1554 asks for before the blocker can clear.
  • The snapshot copies more slowly: 26.9 s against 22.9 s at 8 MiB/s and 51.9 s against 46.6 s at 4 MiB/s, for 150 MiB. The shutdown snapshot is still best-effort and still races with Close. If cut short, it leaves the previous snapshot in place.
  • The snapshot still copies everything in state.db except snapshotExcludedTables, as before. The backup also leaves out the history tables when history.db exists; the snapshot does not. I left that as it was.

🤖 Generated with Claude Code

SnapshotState copied state.db with one INSERT ... SELECT per table. Each
table went over in one transaction, so tens of megabytes stayed dirty
until a single fsync at commit. On an SD card, live history commits and
config writes waited behind that fsync for seconds, past the five-second
history deadline. This is the snapshot at boot plus two minutes and at
each 24 h tick (#1554).

SnapshotTo now uses the live backup's state copy: one read transaction
on state.db, rows in short synced batches checked against the source,
and the backup's pause between batches. The snapshot therefore reads
one point in time across all tables, and it keeps sqlite_sequence, so a
restored control journal no longer reuses an id. quick_check reads only
the new file and holds no lock on state.db or history.db; it stays.
SnapshotState also removes a journal left by an interrupted copy.

On ext4 over a loop device throttled to 8 MiB/s writes, history commits
during a 150 MiB snapshot fell from p50 2.7 s / max 5.3 s to p50 97 ms /
max 481 ms; config writes from max 5.6 s to 66 ms.

Refs #1554

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Fredrik Ahlgren <[email protected]>
@frahlg
frahlg marked this pull request as ready for review November 28, 2026 06:03
@frahlg
frahlg merged commit 4fd1d43 into master Nov 28, 2026
21 checks passed
@frahlg
frahlg deleted the state-snapshot-yields branch November 28, 2026 06:03
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-28T06:07:11.433708Z e4b262c Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant