Skip to content

perf(sync): count sync.status in SQL and read only the refusals that stand - #238

Merged
bketelsen merged 1 commit into
mainfrom
bk/next-priority-gap-733f93
Nov 14, 2026
Merged

bketelsen merged 1 commit into
mainfrom
bk/next-priority-gap-733f93

Conversation

@bketelsen

Copy link
Copy Markdown
Contributor

Summary

refreshStatus (internal/syncer/loop.go) runs after every sync cycle, an idle one too. To fill 3 numbers of sync.status it read every pending change, every pending conflict version, every unanswered push and every agreed row, only to take their lengths. It listed the refusals from every answered push the device ever made (sync_pushes is never trimmed), with 1 FileByID for each refused one. So the cost of an idle cycle grew with the vault's whole push history.

Now:

  • store.DB.SyncCounts returns the 4 counts from 1 statement, so they share a read snapshot.
  • store.DB.Refusals selects only the refusals that still stand: a file's newest answered push, when it was refused and the file still has its path and hash (or is gone, for a refused delete). This is the same rule refusals applied in Go.
  • Migration 0007_sync_pushes_refused.sql adds a partial index of the refused pushes, so that read touches only refused rows.
  • Pending and PendingConflicts now take their SQL from the same constants as the counts, so a count cannot drift from its list.

sync.status reports the same numbers and refusals as before.

On a vault of 2,000 synced files with 50,000 answered pushes, 5 of them refused (a throwaway benchmark of the old reads against the new, not committed; AMD Ryzen AI MAX+ 395), a status refresh went from about 113 ms and 65 MB allocated to 5.4 ms and 8.7 KB.

Closes #209. Whether sync_pushes should drop answered rows that a newer push of the same file supersedes is the retention question the issue leaves to docs/specs/sync-protocol.md; this PR does not answer it.

Risk tier

Risk tier: 3 — the PR touches 1 path in .github/risk-paths.json:

  • internal/store/migrations/** (L1, destructive operations): the new file 0007_sync_pushes_refused.sql is 1 CREATE INDEX ... WHERE status = 'refused' on the existing table sync_pushes. It changes no row and drops nothing; notesd applies it in 1 transaction with its schema_migrations row, so a failure leaves the database as it was. The released migrations 0001 to 0006 are unchanged (TestReleasedMigrationsKeepTheirText checks their checksums), and 0007's checksum is pinned there. As with every migration, a database that applied it is refused by an older notesd ("database schema 7 is newer than this notesd (6)").

The rest is a behavior-preserving change in code: internal/store/remotes.go, internal/syncer/loop.go, tests, and 1 line of the spec's derived-artifacts table.

Docs housekeeping

  • docs/specs/sync-protocol.md's derived artifacts list the new migration. No new doc, decision or ADR.

Verification

  • make check green (host)
  • make sync-sim green, for a change to sync: a shortened run, SIM_SEEDS=4 SIM_STEPS=2000 make sync-sim (stepwise and concurrent, plus TestRegressions), not the default 10 seeds of 10,000 steps. The simulation waits for each device's sync.status pending count to reach 0, so it exercises SyncCounts through the loop.
  • go test -race -count=1 ./internal/store ./internal/syncer green
  • New tests (internal/store/syncstatus_test.go): TestSyncCountsAreTheListsLengths pins each count to the length of the list it replaces, on a fixture where each is non-zero; TestRefusalsStandUntilTheFileChanges covers a standing refusal, a refusal followed by an unanswered push, a refused delete of a gone file, and the cases that must not list (content changed, file moved, a newer accepted push, a refused delete of a file still there, another vault's refusal); TestRefusalsReadOnlyRefusedPushes checks with EXPLAIN QUERY PLAN that the query starts from sync_pushes_refused. Mutation checks: dropping newer.status IS NOT NULL from the query fails the refusals test, and making the status not a literal fails the index test.

…stand

refreshStatus runs after every sync cycle, an idle one too. To fill 3
numbers it read every pending change, every pending conflict version,
every unanswered push and every agreed row, only to count them, and
listed the refusals from every answered push the device ever made
(sync_pushes is never trimmed), with 1 FileByID for each refused one.

store.DB.SyncCounts now returns the 4 counts from 1 statement, so they
share a read snapshot, and store.DB.Refusals selects only the newest
answered push of each file that was refused and still matches its file.
Migration 0007 adds a partial index of the refused pushes, so that read
no longer grows with the push history. Pending and PendingConflicts
share their SQL with the counts, so the two cannot drift apart.

sync.status reports the same numbers and refusals as before; the new
tests pin the counts to the lists' lengths, each refusal case, and that
the refusals query uses the partial index. On a vault of 2,000 synced
files with 50,000 answered pushes (a throwaway benchmark, AMD Ryzen AI
MAX+ 395), a status refresh went from about 113 ms and 65 MB allocated
to 5.4 ms and 8.7 KB.

Closes #209
@github-actions github-actions Bot added level:L1 Read every line risk:high Touches a path in .github/risk-paths.json labels Nov 14, 2026

@frostyard-machines frostyard-machines left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Owner review at 4f6e5e9: OK, with 2 low, non-blocking findings.

Verdict: The change is correct. sync.status reports the same numbers and the same refusals as before.

What I checked

  • Counts. Each SyncCounts count uses the same predicate as the list it replaces. Changes uses the pending CTE that Pending now uses. The final LEFT JOIN in Pending cannot add rows, because sync_files_file is unique on file_id, so COUNT(*) FROM pending equals len(Pending). Lost uses the FROM and WHERE that PendingConflicts now uses. UnansweredConflicts equals the conflict pushes in Unanswered (status IS NULL, and conflict is 0 or 1 by a CHECK). Conflicted equals the conflicted AgreedRows. COUNT(*) gives 0 on an empty vault. The test pins all 4 counts to the list lengths on an empty vault and on a mixed one. The 4 counts come from 1 statement, so they share 1 read snapshot.
  • Refusals that still stand. The rule is the same as before. The old code took each file's newest push from DB.Pushes, which returns only answered pushes. The new NOT EXISTS ... newer.status IS NOT NULL keeps the same rule. A later accepted, merged, conflicted or refused push clears an older refusal. A later unanswered push does not. The path and hash check is the same, and so is the refused delete of a file that is gone (hash = ''). Another vault's pushes do not count. I ran a scratch test that refuses the same file 2 times (missing, then collision), and refuses another file and then merges it. The query lists only the newest refusal, as the old code did. The order is now by path, then push_id. The old sort was by path only, and it was unstable, so ties had no fixed order before.
  • Error order. refreshStatus still reads Remote, then the counts, then the refusals, then SyncHub. A read error now fails the refresh. Before, a FileByID error other than ErrNotFound hid that refusal without a report. I think this is better.
  • Indexes. EXPLAIN QUERY PLAN for refusalsQuery starts with SEARCH p USING INDEX sync_pushes_refused (vault_id=?), then reads sync_pushes_file (file_id=? AND push_id>?) and the primary key of files. The pending CTE now also uses sync_pushes_refused for its refused-push check.
  • Risk path (risk:high, L1). The PR matches 1 path: internal/store/migrations/** ("destructive operations: schema migrations"). The new file is 0007_sync_pushes_refused.sql. The PR body names this path and explains why it is safe: the migration adds 1 partial index, changes no rows and drops nothing. migrate applies it in the same DB.Tx as its schema_migrations row. Migrations 0001 to 0006 keep their checksums, and the checksum of 0007 is pinned in TestReleasedMigrationsKeepTheirText. The body also names the usual downgrade refusal ("schema 7 is newer than this notesd (6)"). This explanation is enough.
  • Docs and specs. The derived-artifacts table in docs/specs/sync-protocol.md lists 0007. Line 297 ("A push the hub refused is not sent again until the file changes ... sync.status lists it.") still describes the behavior. sync.status does not change in docs/specs/rpc-api.md (a generated file, not changed here) or in docs/specs/rpc-protocol.md, which does not describe it. No ADR is necessary.
  • Tests. The new tests make real assertions. Mutations that I ran in a scratch worktree: removing the refused-delete branch fails TestRefusalsStandUntilTheFileChanges, and removing AND conflict = 1 fails TestSyncCountsAreTheListsLengths.

Findings

  1. Low, non-blocking. internal/store/syncstatus_test.go:117 (TestRefusalsStandUntilTheFileChanges) has no case where the same file is refused 2 times, or refused and then merged or conflicted. A mutation to newer.status = 'accepted' in refusalsQuery still passes all the tests. The query is correct (see the scratch test above), but this part of the rule has no direct guard. Suggestion: add 2 refused pushes of 1 file with different reasons, and 1 file that is refused and then merged. Assert that only the newest refusal is listed.
  2. Low, non-blocking. internal/store/remotes.go:421: the unanswered-conflict count still reads every push of the vault (SEARCH sync_pushes USING INDEX sqlite_autoindex_sync_pushes_1 (vault_id=?), filtered by status IS NULL AND conflict = 1). This is only a count, with no allocation, and the old Unanswered read the same rows. But part of an idle refresh still grows with the push history. A follow-up could add a partial index WHERE status IS NULL with a query-plan test, or this can go with the sync_pushes retention question in #209.

Checks at 4f6e5e9

  • make check on a checkout of the head (temporary worktree): exit 0.
  • go test -race -count=1 -timeout 25m ./... (the race part of make ci): exit 0, 51 packages ok, no data race.
  • CI at the head: green (Verify, Race detector, App UI, desktop-smoke, Flatpak, .deb, vulncheck, pr-triage).

Cross-review (openai/gpt-6.1-sol, read-only, base 11700d2, head 4f6e5e9, all 6 files): Ready, Blocking: none. It reported the same 2 low findings as above. It found that the counts, the Pending/PendingConflicts membership, the semantics of Refusals and the migration are correct. I agree with both of its findings.

@bketelsen
bketelsen merged commit bd37fdf into main Nov 14, 2026
10 checks passed
@bketelsen
bketelsen deleted the bk/next-priority-gap-733f93 branch November 14, 2026 02:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

level:L1 Read every line risk:high Touches a path in .github/risk-paths.json

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sync: the status refresh reads every answered push and agreed row on each cycle

2 participants