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: an older app's own new change goes through after another device wrote, only its old copy coming back is set back

Duarte Santosd156961c7b03
diff --git a/api/server.js b/api/server.js
index d65fc4322..8dcb6028d 100644
--- a/api/server.js
+++ b/api/server.js
@@ -191,10 +191,10 @@ function readStateStrict(uid) {
catch (e) { return e.code === 'ENOENT' ? null : UNREADABLE; }
try { return JSON.parse(raw); } catch { return UNREADABLE; }
}
-// A stored document as a client gets it: without the server's own note `_unstamped`.
+// A stored document as a client gets it: without the server's own notes `_unstamped` and `_prior`.
function forClient(S) {
- if (!S || typeof S !== 'object' || !('_unstamped' in S)) return S;
- const { _unstamped, ...rest } = S;
+ if (!S || typeof S !== 'object' || !('_unstamped' in S || '_prior' in S)) return S;
+ const { _unstamped, _prior, ...rest } = S;
return rest;
}
// An entry is an object a reader can dereference, and `records` is every entry of a stored
@@ -2093,7 +2093,8 @@ const routes = {
// `_rev`, so every other reader of the file — reminder tick, admin, Coach, MCP — is unaffected).
// A client pushes it back as `baseRev`, and a write over a document it never saw is refused.
// `_unstamped` is the server's note of what it stamped for an older app's last push
- // (sync-stamps.js ownRecord): read back only by the next PUT, never sent to a client.
+ // (sync-stamps.js ownRecord), `_prior` what each field held before (notePrior): read back only
+ // by the next PUT, never sent to a client.
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
diff --git a/api/sync-stamps.js b/api/sync-stamps.js
index 13f3562d6..33b9e4eb6 100644
--- a/api/sync-stamps.js
+++ b/api/sync-stamps.js
@@ -25,10 +25,12 @@
// entries removed, settings and plan days changed, entries edited. A setting, plan day or
// entry field whose stored stamp is later than the one the writer sent back (it never saw
// that change) keeps the stored value: an older app back from a dead spot no longer sets
-// them back. What remains: such a writer's own change of that same field in the meantime
-// loses to the stamped one (two changes, neither saw the other), one that sends no record of
-// edits at all (it never read a copy from an updated app) still wins as before, and the older
-// app shows its own value until it next reads the profile;
+// them back. Only a value the field held before is put back (its old copy coming back, see
+// notePrior): one the field never held is that writer's own new choice and goes through. What
+// remains: such a writer changing a field back to exactly an earlier value after another
+// device changed it loses to that change, one that sends no record of edits at all (it never
+// read a copy from an updated app) still wins as before, and the older app shows its own
+// value until it next reads the profile;
// 3. for every writer: an entry the document holds while a removal on record says it was
// deleted after its last edit is kept, and marked as added back. An updated app never sends
// such a document, so this is an older app's merge (or its Coach undo, or a backup it
@@ -59,7 +61,7 @@ const capStamps = m => {
return m;
};
const OWN_MERGE = new Set([
- '_ts', '_rev', '_wid', '_wids', '_unstamped', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',
+ '_ts', '_rev', '_wid', '_wids', '_unstamped', '_prior', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',
'workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx',
'exWeights', 'balanceOverrides', 'loadKind', 'plates',
]);
@@ -181,8 +183,67 @@ function ownRecord(next, now, own, fp) {
return { fp, ...(Object.keys(ed).length ? { ed } : {}), ...(Object.keys(f).length ? { f } : {}) };
}
+// What each setting, plan day and entry field held before (`_prior` on the stored document, never
+// sent to a client): per field, short hashes of its last PRIOR_KEEP values before each change. A
+// writer that does not stamp keeps the record of edits it last read and never gets the stamps the
+// server gave its own pushes (it reads the profile again only once the revision moves, and its
+// whole-document merge after a 409 keeps its own older record), so "a later stamp than the one it
+// sent" alone also caught its own next change of that field, and put back a workout set it had just
+// logged (RC item-3 analysis 2026-10-07). With this, a field changed after the writer's copy is put
+// back only when what it sends is a value the field held before: its old copy coming back. A value
+// the field never held is its own new choice and goes through, stamped. A field with no history yet
+// (stamped before `_prior` was kept) is put back as before.
+// The limit: an older app changing a field back to exactly a value it held before, after another
+// device changed it, looks like its old copy and loses to that change.
+const PRIOR_KEEP = 6;
+const PRIOR_MAX = 5000;
+function valueHash(v) {
+ const str = v === undefined ? 'u' : JSON.stringify(v);
+ let a = 0x811c9dc5;
+ for (let i = 0; i < str.length; i++) a = Math.imul(a ^ str.charCodeAt(i), 0x01000193) >>> 0;
+ return `${str.length}.${a.toString(36)}`;
+}
+// `next._prior`: the stored one, with every field this write changes noted, for every writer.
+function notePrior(cur, next) {
+ const pr = isMap(cur?._prior) ? clone(cur._prior) : {};
+ const note = (key, b, a) => {
+ if (same(b, a)) return;
+ const h = valueHash(b);
+ delete pr[key]; // re-added last: the most recently changed go last
+ pr[key] = [...list(cur?._prior?.[key]).filter(x => x !== h), h].slice(-PRIOR_KEEP);
+ };
+ for (const k of new Set([...Object.keys(cur || {}), ...Object.keys(next)])) {
+ if (OWN_MERGE.has(k)) continue;
+ if (PER_KEY.has(k)) {
+ const pm = isMap(cur[k]) ? cur[k] : {}, nm = isMap(next[k]) ? next[k] : {};
+ for (const s of new Set([...Object.keys(pm), ...Object.keys(nm)])) note(`${k}.${s}`, pm[s], nm[s]);
+ } else if (k in next) note(k, cur[k], next[k]);
+ }
+ const live = new Set();
+ for (const f of ENTRY_LISTS) {
+ const before = new Map(list(cur?.[f]).filter(x => isMap(x) && x.id != null).map(x => [x.id, x]));
+ for (const x of list(next[f])) {
+ if (!isMap(x) || x.id == null) continue;
+ live.add(`${f}|${x.id}`);
+ const o = before.get(x.id);
+ if (!o || sameEntry(o, x)) continue;
+ for (const k of new Set([...Object.keys(o), ...Object.keys(x)])) if (!ENTRY_META.has(k)) note(`${f}|${x.id}|${k}`, o[k], x[k]);
+ }
+ }
+ // An entry that is gone takes its history with it; the oldest changed fields go past PRIOR_MAX.
+ for (const key of Object.keys(pr)) {
+ if (!ENTRY_LISTS.some(f => key.startsWith(`${f}|`))) continue;
+ if (!live.has(key.slice(0, key.lastIndexOf('|')))) delete pr[key];
+ }
+ const ks = Object.keys(pr);
+ for (const key of ks.slice(0, Math.max(0, ks.length - PRIOR_MAX))) delete pr[key];
+ if (Object.keys(pr).length) next._prior = pr; else delete next._prior;
+}
// Step 2: what a writer that does not stamp changed against the copy it read, stamped at `now`.
function stampUnstamped(cur, next, sent, now, own = null) {
+ // Whether `v` is a value the field held before (see notePrior); a field with no history: yes.
+ const pr = isMap(cur?._prior) ? cur._prior : {};
+ const wasBefore = (key, v) => !Array.isArray(pr[key]) || pr[key].includes(valueHash(v));
// Removals: every entry the stored copy had and this one lacks, unless already on record.
const del = isMap(next.deleted) ? next.deleted : {};
for (const [f, key] of Object.entries(DEL_LISTS)) {
@@ -219,13 +280,13 @@ function stampUnstamped(cur, next, sent, now, own = null) {
for (const s of new Set([...Object.keys(pm), ...Object.keys(nm)])) {
const sk = `${k}.${s}`;
if ((s in pm) === (s in nm) && same(pm[s], nm[s])) continue;
- if (stale(sk)) {
+ if (stale(sk) && wasBefore(sk, nm[s])) {
const into = isMap(next[k]) ? next[k] : (next[k] = {});
if (s in pm) into[s] = clone(pm[s]); else delete into[s];
} else if (!moved(sk)) ed[sk] = now;
}
} else if (n !== undefined && !same(p, n)) { // absent: a field the writer does not know
- if (stale(k)) { if (k in cur) next[k] = clone(p); else delete next[k]; }
+ if (stale(k) && wasBefore(k, n)) { if (k in cur) next[k] = clone(p); else delete next[k]; }
else if (!moved(k)) ed[k] = now;
}
}
@@ -254,6 +315,7 @@ function stampUnstamped(cur, next, sent, now, own = null) {
if (ENTRY_META.has(k) || !((Number(of[k]) || 0) > (Number(base[k]) || 0))) continue;
if (ownStamp(own?.f?.[`${f}|${x.id}`], k, of[k])) continue;
if ((k in old) === (k in x) && same(old[k], x[k])) continue;
+ if (!wasBefore(`${f}|${x.id}|${k}`, x[k])) continue;
if (k in old) x[k] = clone(old[k]); else delete x[k];
}
const fx = { ...base };
@@ -320,7 +382,7 @@ const V139_DROPS = {
// The lists inside an entry that are walked too, and how their items are matched.
const NESTED = { routines: ['ex'], workouts: ['entries'], 'workouts.entries': ['sets'] };
// Server bookkeeping and the records merged on their own: never put back from the stored copy.
-const NOT_KEPT = new Set(['_rev', '_wid', '_wids', '_unstamped', 'active', 'resetAt', 'resetIds', 'deleted', 'edited']);
+const NOT_KEPT = new Set(['_rev', '_wid', '_wids', '_unstamped', '_prior', 'active', 'resetAt', 'resetIds', 'deleted', 'edited']);
// `x` with every key of `old` it lacks and the writer cannot have dropped on purpose. Mutates `x`.
function keepKeys(old, x, place) {
@@ -404,7 +466,7 @@ function keepHeld(next, now) {
*/
// What a document says, without its stamps and the server's bookkeeping: whether the server put
// back anything of what a writer sent (stampPut's `report`).
-const BOOKKEEPING = new Set(['_ts', '_f', '_u', '_rev', '_wid', '_wids', '_unstamped', 'edited', 'deleted', 'undone']);
+const BOOKKEEPING = new Set(['_ts', '_f', '_u', '_rev', '_wid', '_wids', '_unstamped', '_prior', 'edited', 'deleted', 'undone']);
const content = S => JSON.stringify(S, (k, v) => (BOOKKEEPING.has(k) ? undefined : v));
export function stampPut(cur, next, { overRead = false, stamped = false, now = Date.now(), report = null } = {}) {
@@ -412,8 +474,13 @@ export function stampPut(cur, next, { overRead = false, stamped = false, now = D
const t = Math.max(Number(now) || 0, highestStamp(cur) + 1, highestStamp(next) + 1);
const reset = (Number(next.resetAt) || 0) > (Number(cur?.resetAt) || 0);
const sent = isMap(next.edited) ? { ...next.edited } : null;
- // Only the push that made it may use it (see ownRecord); whatever a writer sent back goes.
+ // The note of what the server stamped for an older app outlives the writes in between (an updated
+ // app's, or one not over the revision it read), for as long as each stamp is still the stored one:
+ // the older app's merge after the 409 such a write causes keeps its own record of edits, so its
+ // next push still matches the fingerprint, and its own change is still its own.
+ const prevOwn = isMap(cur?._unstamped) ? cur._unstamped : null;
delete next._unstamped;
+ delete next._prior;
if (cur && !reset) {
const d = mergeDeletions(cur.deleted, next.deleted);
if (d) next.deleted = d; else delete next.deleted;
@@ -430,9 +497,13 @@ export function stampPut(cur, next, { overRead = false, stamped = false, now = D
stampUnstamped(cur, next, sent, t, own);
const rec = ownRecord(next, t, own, fp);
if (rec) next._unstamped = rec;
+ } else if (prevOwn && !reset) {
+ const rec = ownRecord(next, NaN, prevOwn, prevOwn.fp);
+ if (rec) next._unstamped = rec;
}
if (before != null && content(next) !== before) report.changed = true;
}
keepHeld(next, t);
+ if (cur && !reset) notePrior(cur, next);
return next;
}
diff --git a/api/test/sync-stamps.test.js b/api/test/sync-stamps.test.js
index bd7a43555..fe62f4761 100644
--- a/api/test/sync-stamps.test.js
+++ b/api/test/sync-stamps.test.js
@@ -328,11 +328,56 @@ test('a stamp the server gave one older app still holds against another that rea
other.restSec = 90;
stampPut(clone(cur), other, { overRead: true, stamped: false, now: NOW + 1000 });
assert.equal(other.restSec, 120);
- // and an updated app's write in between ends the run: the older app's next push is a 409 anyway,
- // and nothing of the record is left for it
+ // and an updated app's write in between keeps the record of the stamp still stored: the older
+ // app's merge after the 409 keeps its own record of edits, so its next change is still its own
const app = clone(one); app.theme = 'x';
stampPut(clone(one), app, { overRead: true, stamped: true, now: NOW + 2000 });
- assert.equal('_unstamped' in app, false);
+ assert.equal(app._unstamped?.ed?.restSec, one.edited.restSec);
+});
+
+test('an older app\'s own next change goes through after another device wrote in between; its old copy coming back does not', () => {
+ let cur = stored();
+ const put = (doc, now, stamped = false) => { const next = clone(doc); stampPut(clone(cur), next, { overRead: true, stamped, now }); cur = next; return next; };
+ const old = clone(cur); // what v1.3.9 read, record and all
+ old.restSec = 180;
+ old.workouts.push({ id: 'w3', d: '2026-10-03', start: 5, end: 6, entries: [{ id: 'bench', sets: [{ w: 60, r: 5 }] }], _ts: NOW - 50 });
+ put(old, NOW);
+ old.workouts[2].entries[0].sets.push({ w: 70, r: 5 });
+ put(old, NOW + 1000);
+ assert.equal(cur.workouts[2].entries[0].sets.length, 2);
+ // an updated app changes the queue (and reads the server's copy, so it sends the stamps)
+ const app = clone(cur); delete app._unstamped; delete app._prior;
+ app.queue = { ids: ['b'] }; app.edited = { ...app.edited, queue: NOW + 2000 };
+ put(app, NOW + 2000, true);
+ assert.equal('_prior' in app, false);
+ // the older app, on its own copy (its merge after the 409 keeps its older record and the queue
+ // from before): a 3rd logged set and a second change of the rest time are its own and land, the
+ // queue it still holds is the one from before and stays set back
+ old.restSec = 270; old.workouts[2].entries[0].sets.push({ w: 80, r: 3 });
+ put(old, NOW + 3000);
+ assert.equal(cur.restSec, 270);
+ assert.deepEqual(cur.workouts[2].entries[0].sets.map(x => x.w), [60, 70, 80]);
+ assert.deepEqual(cur.queue, { ids: ['b'] });
+ // a new pick of the queue it makes before it reads the profile again is its own choice
+ old.queue = { ids: ['c'] };
+ put(old, NOW + 4000);
+ assert.deepEqual(cur.queue, { ids: ['c'] });
+ assert.ok(cur.edited.queue >= NOW + 4000);
+ // a workout that is removed takes its history with it
+ assert.ok(Object.keys(cur._prior).some(k => k.startsWith('workouts|w3|')));
+ old.workouts = old.workouts.filter(w => w.id !== 'w3');
+ put(old, NOW + 5000);
+ assert.ok(!Object.keys(cur._prior || {}).some(k => k.startsWith('workouts|w3|')));
+ assert.ok(cur.deleted.workouts.w3 > 0);
+});
+
+test('a field with no history of its earlier values (stamped before it was kept) is put back as before', () => {
+ const cur = stored();
+ cur.edited = { restSec: NOW - 1000 }; // changed on an updated app since the old copy
+ const old = clone(cur); old.edited = { restSec: NOW - 8000 };
+ old.restSec = 45; // a value it never held: without `_prior`, still put back
+ stampPut(clone(cur), old, { overRead: true, stamped: false, now: NOW });
+ assert.equal(old.restSec, 90);
});
test('PUT /api/data: an older app\'s two changes of one setting in a row both land, and the note stays on the server', async t => {
@@ -361,6 +406,8 @@ test('PUT /api/data: an older app\'s two changes of one setting in a row both la
assert.equal(now.state.restSec, 150);
assert.equal(now.rev, r.body.rev); // nothing set back, so nothing to read again
assert.equal('_unstamped' in now.state, false);
+ assert.equal('_prior' in now.state, false);
const onDisk = JSON.parse(fs.readFileSync(path.join(dataDir, 'state-u1.json'), 'utf8'));
assert.ok(onDisk._unstamped?.ed?.restSec > 0);
+ assert.equal(onDisk._prior?.restSec?.length, 2); // 100, then 120
});
diff --git a/frontend/src/lib/sync-fuzz.test.js b/frontend/src/lib/sync-fuzz.test.js
index d82e17b28..ae291d6f9 100644
--- a/frontend/src/lib/sync-fuzz.test.js
+++ b/frontend/src/lib/sync-fuzz.test.js
@@ -14,6 +14,8 @@ import { stampPut } from '../../../api/sync-stamps.js'
const { mergeStates, stampWorkout, keepReset } = M
const unitOps = []
const clone = o => (o === undefined ? undefined : JSON.parse(JSON.stringify(o)))
+// What server.js sends a client: the stored document without the server's own notes.
+const forClient = S => { const x = clone(S); if (x) { delete x._unstamped; delete x._prior } return x }
const DEL = '__DELETED__'
function rng(seed) { let s = seed >>> 0 || 1; return () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296 } }
@@ -71,7 +73,7 @@ function run(seed, opts = {}) {
function serverPut(body) {
const cur = server.doc
const curRev = server.rev
- if (body.baseRev != null && body.baseRev !== curRev) return { status: 409, state: clone(cur), rev: curRev }
+ if (body.baseRev != null && body.baseRev !== curRev) return { status: 409, state: forClient(cur), rev: curRev }
const st = clone(body.state)
delete st.active
const storedReset = Number(cur?.resetAt) || 0
@@ -110,7 +112,7 @@ function run(seed, opts = {}) {
if (!r.online) return
if (r.inflight) pushRecv(r)
if (r.pushTm) push(r)
- const state = clone(server.doc), rev = server.rev
+ const state = forClient(server.doc), rev = server.rev
const S = r.S
const dirty = r.owed
if (!r.base) {
@@ -341,7 +343,7 @@ function run(seed, opts = {}) {
for (let round = 0; round < 6; round++) for (const r of reps) { T += 1000; pull(r) }
const strip = S => { const x = clone(S); for (const k of ['_ts', '_rev', 'active']) delete x[k]; return JSON.stringify(sortKeys(x)) }
const problems = []
- const sv = strip(server.doc || DEF())
+ const sv = strip(forClient(server.doc) || DEF())
for (const r of reps) if (strip(r.S) !== sv) problems.push(`no-converge r${r.i}`)
// ---- oracle -----------------------------------------------------------------------------
const D = server.doc || DEF()
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 3062842eb..9c9c9e04b 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -600,7 +600,7 @@ function applyDeletions(S, deleted) {
// a rotation pass refilled on the phone survives a setting flipped on the desktop. Fields with a
// merge of their own are not stamped here; a field nobody stamped follows the newer copy, as before.
const OWN_MERGE = new Set([
- '_ts', '_rev', '_wid', '_wids', '_unstamped', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',
+ '_ts', '_rev', '_wid', '_wids', '_unstamped', '_prior', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',
'workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx',
'exWeights', 'balanceOverrides', 'loadKind', 'plates',
])
@@ -861,7 +861,8 @@ export function mergeStates(a0, b0, { prefer } = {}) {
delete out._rev
delete out._wid
delete out._wids
- delete out._unstamped // the server's own note (api/sync-stamps.js), never a client's
+ delete out._unstamped // the server's own notes (api/sync-stamps.js), never a client's
+ delete out._prior
// The accent fields end up in CSS: whatever either copy brought, only a clean value goes on.
sanitizeAccent(out)
return out