Repository navigation
perf(sync): count sync.status in SQL and read only the refusals that stand - #238
Merged
Merged
Conversation
…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
frostyard-machines
left a comment
Contributor
There was a problem hiding this comment.
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
SyncCountscount uses the same predicate as the list it replaces.Changesuses thependingCTE thatPendingnow uses. The final LEFT JOIN inPendingcannot add rows, becausesync_files_fileis unique onfile_id, soCOUNT(*) FROM pendingequalslen(Pending).Lostuses the FROM and WHERE thatPendingConflictsnow uses.UnansweredConflictsequals the conflict pushes inUnanswered(status IS NULL, andconflictis 0 or 1 by a CHECK).Conflictedequals the conflictedAgreedRows.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 newNOT EXISTS ... newer.status IS NOT NULLkeeps 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, thencollision), 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, thenpush_id. The old sort was by path only, and it was unstable, so ties had no fixed order before. - Error order.
refreshStatusstill readsRemote, then the counts, then the refusals, thenSyncHub. A read error now fails the refresh. Before, aFileByIDerror other thanErrNotFoundhid that refusal without a report. I think this is better. - Indexes.
EXPLAIN QUERY PLANforrefusalsQuerystarts withSEARCH p USING INDEX sync_pushes_refused (vault_id=?), then readssync_pushes_file (file_id=? AND push_id>?)and the primary key offiles. ThependingCTE now also usessync_pushes_refusedfor its refused-push check. - Risk path (risk:high, L1). The PR matches 1 path:
internal/store/migrations/**("destructive operations: schema migrations"). The new file is0007_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.migrateapplies it in the sameDB.Txas itsschema_migrationsrow. Migrations 0001 to 0006 keep their checksums, and the checksum of 0007 is pinned inTestReleasedMigrationsKeepTheirText. 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.mdlists 0007. Line 297 ("A push the hub refused is not sent again until the file changes ...sync.statuslists it.") still describes the behavior.sync.statusdoes not change indocs/specs/rpc-api.md(a generated file, not changed here) or indocs/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 removingAND conflict = 1failsTestSyncCountsAreTheListsLengths.
Findings
- 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 tonewer.status = 'accepted'inrefusalsQuerystill 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. - 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 bystatus IS NULL AND conflict = 1). This is only a count, with no allocation, and the oldUnansweredread the same rows. But part of an idle refresh still grows with the push history. A follow-up could add a partial indexWHERE status IS NULLwith a query-plan test, or this can go with thesync_pushesretention question in #209.
Checks at 4f6e5e9
make checkon a checkout of the head (temporary worktree): exit 0.go test -race -count=1 -timeout 25m ./...(the race part ofmake 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
refreshStatus(internal/syncer/loop.go) runs after every sync cycle, an idle one too. To fill 3 numbers ofsync.statusit 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_pushesis never trimmed), with 1FileByIDfor each refused one. So the cost of an idle cycle grew with the vault's whole push history.Now:
store.DB.SyncCountsreturns the 4 counts from 1 statement, so they share a read snapshot.store.DB.Refusalsselects 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 rulerefusalsapplied in Go.0007_sync_pushes_refused.sqladds a partial index of the refused pushes, so that read touches only refused rows.PendingandPendingConflictsnow take their SQL from the same constants as the counts, so a count cannot drift from its list.sync.statusreports 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_pushesshould drop answered rows that a newer push of the same file supersedes is the retention question the issue leaves todocs/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 file0007_sync_pushes_refused.sqlis 1CREATE INDEX ... WHERE status = 'refused'on the existing tablesync_pushes. It changes no row and drops nothing; notesd applies it in 1 transaction with itsschema_migrationsrow, so a failure leaves the database as it was. The released migrations 0001 to 0006 are unchanged (TestReleasedMigrationsKeepTheirTextchecks 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 checkgreen (host)make sync-simgreen, for a change to sync: a shortened run,SIM_SEEDS=4 SIM_STEPS=2000 make sync-sim(stepwise and concurrent, plusTestRegressions), not the default 10 seeds of 10,000 steps. The simulation waits for each device'ssync.statuspending count to reach 0, so it exercisesSyncCountsthrough the loop.go test -race -count=1 ./internal/store ./internal/syncergreeninternal/store/syncstatus_test.go):TestSyncCountsAreTheListsLengthspins each count to the length of the list it replaces, on a fixture where each is non-zero;TestRefusalsStandUntilTheFileChangescovers 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);TestRefusalsReadOnlyRefusedPusheschecks withEXPLAIN QUERY PLANthat the query starts fromsync_pushes_refused. Mutation checks: droppingnewer.status IS NOT NULLfrom the query fails the refusals test, and making the status not a literal fails the index test.