Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Sync: a change is stamped after everything its copy has seen, so a phone whose clock runs behind keeps its edits and deletes

Duarte Santos28c94bd915ba
diff --git a/frontend/src/lib/sync-fuzz.test.js b/frontend/src/lib/sync-fuzz.test.js
index 1a2b3963a..e1d9fa9de 100644
--- a/frontend/src/lib/sync-fuzz.test.js
+++ b/frontend/src/lib/sync-fuzz.test.js
@@ -10,7 +10,7 @@ import { describe, expect, it } from 'vitest'
import * as M from './sync-merge.js'
import * as U from './units.js'
-const { mergeStates, stampRoutines, stampCustomEx, stampWorkout, keepReset, stampDeletions, stampEdits } = M
+const { mergeStates, stampWorkout, keepReset } = M
const unitOps = []
const clone = o => (o === undefined ? undefined : JSON.parse(JSON.stringify(o)))
const DEL = '__DELETED__'
@@ -47,7 +47,7 @@ function run(seed, opts = {}) {
// ---- store model -----------------------------------------------------------------------
function persist(r, S, stamp = true) {
- if (stamp) S._ts = Math.max(nowOf(r), (r.base?.ts || 0) + 1)
+ if (stamp) S._ts = Math.max(nowOf(r), (r.base?.ts || 0) + 1, Number(S._ts) || 0)
r.S = S
}
function update(r, mut) {
@@ -55,11 +55,7 @@ function run(seed, opts = {}) {
const S = clone(prev)
const ok = mut(S, nowOf(r))
if (ok === false) return false
- const now = nowOf(r)
- stampRoutines(prev.routines, S.routines, now)
- stampCustomEx(prev.customEx, S.customEx, now)
- stampDeletions(prev, S, now)
- stampEdits(prev, S, now)
+ S._ts = M.stampChange(prev, S, nowOf(r))
persist(r, S)
r.pushTm = true
return true
@@ -350,6 +346,20 @@ const CASES = [
{ name: 'with unit switches', seeds: 150, opts: { units: true, ops: 80 } },
]
+describe('sync fuzz: clocks up to a day apart still converge, with nothing duplicated', () => {
+ it('three devices, skewed clocks', () => {
+ const bad = []
+ for (let s = 1; s <= 200; s++) {
+ const { problems } = run(s, { skew: 86400000, ops: 80, replicas: 3 })
+ // which of two changes neither device had seen comes last is the clocks' call; only
+ // convergence and duplicates are checked here (the ordering is checked without skew)
+ const hard = problems.filter(p => p.startsWith('no-converge') || p.startsWith('dup'))
+ if (hard.length) bad.push(`seed ${s}: ${hard.join('; ')}`)
+ }
+ expect(bad.slice(0, 5)).toEqual([])
+ })
+})
+
describe('sync fuzz: every device converges on every last change', () => {
for (const c of CASES) {
it(c.name, () => {
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 636467216..fca32afdc 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -347,10 +347,13 @@ export function stampDeletions(prev, next, now = Date.now()) {
const have = new Set(after.filter(x => x != null).map(x => String(key(x))))
const m = isMap(del[f]) ? del[f] : {}
let changed = false
+ const time = DEL_TIME[f] || (() => 0)
for (const x of before) {
if (x == null) continue
const k = String(key(x))
- if (!have.has(k)) { m[k] = now; changed = true }
+ // Never stamped before the entry's own time: a removal is always after what it removed,
+ // whatever this device's clock says (stampChange).
+ if (!have.has(k)) { m[k] = Math.max(now, time(x) + 1); changed = true }
}
// Added back: only a key this change brought in, not every key the copy merely still holds.
// A copy keeps an entry whose removal it has on record when that entry was edited after the
@@ -652,6 +655,65 @@ export function keepReset(cur, next) {
return next
}
+// ---- One causal time per change ---------------------------------------------------------------
+//
+// Every stamp above is a wall-clock time, compared between devices. A phone whose clock runs
+// behind stamped its later change before the change it had already seen, and lost to it on the
+// next merge: its setting, its routine edit, its delete reverted, silently, on every device. So a
+// change is stamped after every stamp the copy it was made on carries (stampChange): a change
+// made after seeing another always wins over it, whatever either clock says. Only changes neither
+// device had seen are still ordered by their clocks.
+
+/** The latest stamp a copy carries: its `_ts`, every setting, removal and entry stamp. */
+export function highestStamp(S) {
+ let m = 0
+ const see = v => { const n = Math.abs(Number(v) || 0); if (n > m) m = n }
+ if (!S || typeof S !== 'object') return 0
+ see(S._ts)
+ see(S.unitSet?.at)
+ see(S.resetAt)
+ if (isMap(S.edited)) for (const v of Object.values(S.edited)) see(v)
+ if (isMap(S.deleted)) for (const f of Object.values(S.deleted)) if (isMap(f)) for (const v of Object.values(f)) see(v)
+ for (const f of ['workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards']) {
+ for (const x of list(S[f])) {
+ if (!x || typeof x !== 'object') continue
+ see(x._ts)
+ if (isMap(x._f)) for (const v of Object.values(x._f)) see(v)
+ }
+ }
+ for (const f of ['balanceOverrides', 'loadKind', 'plates']) if (isMap(S[f])) for (const v of Object.values(S[f])) see(stampOf(v))
+ return m
+}
+
+/**
+ * Stamps everything the change from `prev` to `next` touched, at one time that comes after every
+ * stamp `prev` carries (and `wall`, this device's clock): routines, custom exercises, workouts a
+ * screen re-stamped (stampWorkout), removals, settings and plan days. Mutates `next`; returns
+ * the time used, for the copy's own `_ts`.
+ */
+export function stampChange(prev, next, wall = Date.now()) {
+ const now = Math.max(Number(wall) || 0, highestStamp(prev) + 1)
+ if (!next || typeof next !== 'object') return now
+ const before = new Map(list(prev?.workouts).filter(w => w && w.id != null).map(w => [w.id, w]))
+ for (const w of list(next.workouts)) {
+ if (!w || typeof w !== 'object' || w.id == null || w._ts == null) continue
+ const old = before.get(w.id)
+ if (old && w._ts !== old._ts) w._ts = now
+ }
+ // Settings maps whose entries carry their own stamp (mergeStampedMap): an entry the change
+ // re-stamped takes the change's time.
+ for (const f of ['balanceOverrides', 'loadKind', 'plates']) {
+ const p = isMap(prev?.[f]) ? prev[f] : {}, n = isMap(next[f]) ? next[f] : null
+ if (!n) continue
+ for (const [k, v] of Object.entries(n)) if (isMap(v) && v._ts != null && stampOf(v) !== stampOf(p[k])) v._ts = now
+ }
+ stampRoutines(prev?.routines, next.routines, now)
+ stampCustomEx(prev?.customEx, next.customEx, now)
+ stampDeletions(prev, next, now)
+ stampEdits(prev, next, now)
+ return now
+}
+
const sameRoutine = (a, b) => JSON.stringify({ ...a, _ts: 0 }) === JSON.stringify({ ...b, _ts: 0 })
/**
diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.js
index 688f6e625..00ad7f11c 100644
--- a/frontend/src/lib/sync-merge.test.js
+++ b/frontend/src/lib/sync-merge.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { keepReset, localExtras, mergeDeletions, stampDeletions, stampEdits, mergeBodyweight, mergeResetIds, mergeStampedMap, mergeStates, newerOf, resetIdsOf, RESET_ID_MAX, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'
+import { highestStamp, stampChange, keepReset, localExtras, mergeDeletions, stampDeletions, stampEdits, mergeBodyweight, mergeResetIds, mergeStampedMap, mergeStates, newerOf, resetIdsOf, RESET_ID_MAX, sinceReset, stampCustomEx, stampRoutines, stampWorkout, unionById } from './sync-merge.js'
import { mergeImport } from './import-csv.js'
import { convertBodyWeight, convertStateUnit, convertWeight } from './units.js'
import { retimeWorkout } from './workout-date.js'
@@ -760,6 +760,50 @@ describe('added back means brought back by this change', () => {
})
})
+
+describe('a change is stamped after everything the copy it was made on carries (stampChange)', () => {
+ const T = Date.UTC(2026, 9, 6, 12), DAY = 86400000
+ const change = (prev, wall, mut) => { const n = clone(prev); mut(n); n._ts = stampChange(prev, n, wall); return n }
+
+ it('a phone a day behind keeps the setting, rename and delete it made after the web change it saw', () => {
+ const b0 = { _ts: T - 3600000, restSec: 90, routines: [{ id: 'r1', name: 'Pull', ex: [], _ts: T - 7200000 }],
+ workouts: [{ id: 'w1', d: '2026-10-06', start: T - 7200000, end: T - 3600000, entries: [] }] }
+ const web = change(b0, T, S => { S.restSec = 180; S.routines[0].name = 'Push A'; S.workouts[0].note = 'x'; stampWorkout(S.workouts[0], T) })
+ // the phone pulled the web's copy, then (a minute later, its clock a day behind) changes all three
+ const phone = change(web, T + 60000 - DAY, S => { S.restSec = 95; S.routines[0].name = 'Push B'; S.workouts = [] })
+ expect(phone._ts).toBeGreaterThan(web._ts)
+ // the web, meanwhile offline with an unrelated change, merges the phone's copy
+ const web2 = change(web, T + 30000, S => { S.theme = 'light' })
+ for (const m of [mergeStates(web2, phone), mergeStates(phone, web2)]) {
+ expect(m.restSec).toBe(95)
+ expect(m.routines[0].name).toBe('Push B')
+ expect(m.workouts).toEqual([])
+ expect(m.theme).toBe('light')
+ }
+ })
+
+ it('a delete is always stamped after the entry it removes', () => {
+ const b0 = { _ts: 10, workouts: [{ id: 'dupe', d: '2026-10-06', start: T - 100, end: T }], bodyweight: [{ d: '2026-10-06', w: 80, t: T + 7200e3 }] }
+ const n = change(b0, T - DAY, S => { S.workouts = []; S.bodyweight = [] })
+ expect(n.deleted.workouts.dupe).toBeGreaterThan(T)
+ expect(n.deleted.bodyweight['2026-10-06']).toBeGreaterThan(T + 7200e3)
+ })
+
+ it('a weigh-in logged again after seeing a delete stamped by a clock that runs ahead is kept', () => {
+ const D = '2026-10-06'
+ const b0 = { _ts: T - 5e5, workouts: [], bodyweight: [{ d: D, w: 82, t: T - 4e5 }] }
+ const A = change(b0, T + 7200e3, S => { S.bodyweight = [] }) // clock two hours ahead
+ const B = change(A, T + 600e3, S => { S.bodyweight = [{ d: D, w: 80.4, t: T + 600e3 }] })
+ const A2 = change(A, T + 7200e3 + 5, S => { S.restSec = 120 })
+ expect(mergeStates(A2, B).bodyweight.map(e => e.w)).toEqual([80.4])
+ })
+
+ it('highestStamp reads every kind of stamp', () => {
+ expect(highestStamp({ _ts: 1, edited: { a: 5 }, deleted: { workouts: { x: -9 } }, routines: [{ _ts: 3, _f: { name: 12 } }], plates: { kg: { _ts: 7 } } })).toBe(12)
+ expect(highestStamp(null)).toBe(0)
+ })
+})
+
describe('settings and plan days keep the change made last', () => {
// B, offline, sets Wednesday and the rest timer; A logs a weigh-in later and flips the sound.
const start = () => base({ _ts: 100, week: { 1: ['r1'] }, restSec: 90, sound: true, exNotes: { '0025': 'seat 4' } })
diff --git a/frontend/src/store/useStore.clock.test.jsx b/frontend/src/store/useStore.clock.test.jsx
new file mode 100644
index 000000000..b74ce7e95
--- /dev/null
+++ b/frontend/src/store/useStore.clock.test.jsx
@@ -0,0 +1,37 @@
+// @vitest-environment happy-dom
+
+/* A device whose clock runs behind: every change it makes is stamped after the stamps of the copy
+ it was made on (lib/sync-merge.js stampChange), so it wins over what it had already seen. */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))
+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))
+
+import { DEF, useStore } from './useStore.js'
+
+const clone = v => JSON.parse(JSON.stringify(v))
+const AHEAD = Date.now() + 86400000 // stamps written by a device a day ahead
+
+beforeEach(() => { localStorage.clear(); useStore.setState({ user: null, ready: true }) })
+afterEach(() => { localStorage.clear() })
+
+describe('update stamps after what the copy has seen', () => {
+ it('settings, routines, workouts and removals all come after the newest stamp', () => {
+ const S = { ...clone(DEF), _ts: AHEAD, restSec: 90, edited: { restSec: AHEAD },
+ routines: [{ id: 'r1', name: 'A', ex: [], _ts: AHEAD }],
+ workouts: [{ id: 'w1', d: '2026-10-06', start: 1, end: 2, entries: [], _ts: AHEAD }, { id: 'w2', d: '2026-10-06', start: 3, end: 4, entries: [] }] }
+ useStore.setState({ S })
+ useStore.getState().update(s => {
+ s.restSec = 60
+ s.routines[0].name = 'B'
+ s.workouts[0].note = 'n'; s.workouts[0]._ts = Date.now()
+ s.workouts = s.workouts.filter(w => w.id !== 'w2')
+ })
+ const n = useStore.getState().S
+ expect(n.edited.restSec).toBeGreaterThan(AHEAD)
+ expect(n.routines[0]._ts).toBeGreaterThan(AHEAD)
+ expect(n.workouts[0]._ts).toBeGreaterThan(AHEAD)
+ expect(n.deleted.workouts.w2).toBeGreaterThan(AHEAD)
+ expect(n._ts).toBeGreaterThan(AHEAD)
+ })
+})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 233ee36a4..97b857904 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -8,7 +8,7 @@ import { rememberDefaultLang } from '../lib/default-lang.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
import { refillIfComplete } from '../lib/rotation.js'
-import { mergeStates, localExtras, stampRoutines, stampCustomEx, stampDeletions, stampEdits, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
+import { mergeStates, localExtras, stampChange, highestStamp, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
import { convertStateUnit } from '../lib/units.js'
import { pendingRefCount, settleMedia, loadPending } from '../lib/media-owed.js'
import { referencedHashes } from '../lib/media-refs.js'
@@ -430,7 +430,7 @@ export const useStore = create((set, get) => {
// a pull replaced it with the server's copy.
const persist = (S, push = true, stamp = true) => {
const { base, owed } = metaOf() // the copy being replaced; the new one stands where it stood
- if (stamp) S._ts = Math.max(Date.now(), (base?.ts || 0) + 1)
+ if (stamp) S._ts = Math.max(Date.now(), (base?.ts || 0) + 1, Number(S._ts) || 0)
// Every copy that enters the store — an edit, a pull, an adoption, a restored backup — has its
// custom exercises marked as such (#378): one stored without the flag by an older plan import
// goes out with it on the next push, without a stamp of its own (healCustomEx).
@@ -529,7 +529,7 @@ export const useStore = create((set, get) => {
// A pass of this app's rotation that the merge left complete (each copy finished a session of
// it, or one copy's refill lost to the other's older queue) starts its next pass here, as the
// finish that completed it would have (lib/rotation.js).
- if (refillIfComplete(merged)) merged.edited = { ...(merged.edited || {}), queue: Date.now() }
+ if (refillIfComplete(merged)) merged.edited = { ...(merged.edited || {}), queue: Math.max(Date.now(), highestStamp(merged) + 1) }
persist(merged, false)
if (rev == null) dropSync()
else writeSync(rev, ts)
@@ -1021,13 +1021,11 @@ export const useStore = create((set, get) => {
const prev = get().S
const S = clone(prev)
mut(S)
- const now = Date.now()
- stampRoutines(prev.routines, S.routines, now)
- stampCustomEx(prev.customEx, S.customEx, now)
- // What the change removed, and which settings and plan days it touched, each with its time:
- // a conflict then keeps a removal and the setting changed last (lib/sync-merge.js).
- stampDeletions(prev, S, now)
- stampEdits(prev, S, now)
+ // What the change removed, and which routines, workouts, settings and plan days it touched,
+ // each with one time that comes after every stamp the copy already carries: a conflict then
+ // keeps a removal and the edit made last, even from a device whose clock runs behind
+ // (lib/sync-merge.js stampChange).
+ S._ts = stampChange(prev, S, Date.now())
persist(S, push)
// A photo or video added to a workout is a change worth the day's backup too: the one
// finishing wrote went before the finish screen's pictures (autoBackupNow). Not a removal,
@@ -1063,7 +1061,7 @@ export const useStore = create((set, get) => {
const S0 = get().S
if ((S0.unit || 'kg') === to) return null
const S = clone(convert ? convertStateUnit(S0, to) : { ...S0, unit: to })
- S.unitSet = { at: Date.now(), convert }
+ S.unitSet = { at: Math.max(Date.now(), highestStamp(S0) + 1), convert }
persist(S, true)
return convert && get().ready ? get().pushState() : null
},
@@ -1080,7 +1078,7 @@ export const useStore = create((set, get) => {
resetEverything() {
const cur = get().S
const S = restartedState(cur)
- S.resetAt = Math.max(Date.now(), (Number(cur.resetAt) || 0) + 1)
+ S.resetAt = Math.max(Date.now(), highestStamp(cur) + 1)
S.resetIds = mergeResetIds(cur.resetIds, resetIdsOf(cur))
get().replaceState(S, !!get().user)
if (!get().user) return Promise.resolve()