🐛 Stop the sync from undoing writes made during a round
The sync manager learns of a local write only from the change record it creates after the write finished, and it applies the pulled server state without regard to newer local changes. A write made while a round was pulling or pushing was therefore replaced by the older server version, or removed as unknown to the snapshot, until the next round pushed it again: a deleted adjustment came back, an edit reverted, a new row vanished for a moment. Each pull now waits for the writes in flight on the collection and on the change records, keeps the server version of items whose change record the round did not push, and local writes wait while the sync applies server state to their collection; network requests stay exempt. The stress test writes to four collections for 300 rounds, with the sync idle and with a push held in flight, and asserts that reactive and plain reads always show the last write. Without the fix it fails in the first round.
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import { tick } from 'svelte';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { addAdjustment, balance, deleteAdjustment } from './app.svelte';
|
||||
import { all, closeDb, get, openDb, pendingCount, remove, save, status, syncNow, update } from './db.svelte';
|
||||
import { watch, type Watcher } from './testing.svelte';
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const server = new Map<string, Map<string, Record<string, unknown>>>();
|
||||
let tick = 0;
|
||||
let hold: { promise: Promise<void>; entered: () => void } | null = null;
|
||||
return {
|
||||
server,
|
||||
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' '),
|
||||
holdNextPush(): { entered: Promise<void>; release: () => void } {
|
||||
let release!: () => void;
|
||||
let enter!: () => void;
|
||||
const entered = new Promise<void>((resolve) => (enter = resolve));
|
||||
hold = { promise: new Promise<void>((resolve) => (release = resolve)), entered: enter };
|
||||
return { entered, release };
|
||||
},
|
||||
async gate() {
|
||||
const current = hold;
|
||||
if (!current) return;
|
||||
hold = null;
|
||||
current.entered();
|
||||
await current.promise;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$lib/pb', () => ({
|
||||
pb: {
|
||||
autoCancellation: () => undefined,
|
||||
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
|
||||
collection: (name: string) => ({
|
||||
getFullList: async (options: { filter?: string }) => {
|
||||
const since = /updated >= "([^"]+)"/.exec(options?.filter ?? '')?.[1];
|
||||
return [...(mocks.server.get(name)?.values() ?? [])].filter((r) => !since || String(r.updated) >= since);
|
||||
},
|
||||
subscribe: async () => async () => undefined
|
||||
}),
|
||||
send: async (path: string, options: { method?: string; body?: unknown }) => {
|
||||
if (path !== '/api/sync/push' || options.method !== 'POST') return {};
|
||||
await mocks.gate();
|
||||
const body = options.body as {
|
||||
changes: { collection: string; id: string; data: Record<string, unknown>; client_updated_at: number; deleted: boolean }[];
|
||||
};
|
||||
const results = body.changes.map((c) => {
|
||||
const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() };
|
||||
let store = mocks.server.get(c.collection);
|
||||
if (!store) {
|
||||
store = new Map();
|
||||
mocks.server.set(c.collection, store);
|
||||
}
|
||||
store.set(c.id, record);
|
||||
return { id: c.id, collection: c.collection, status: 'ok', record };
|
||||
});
|
||||
return { results };
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
type Field = 'start_time' | 'worked_ms' | 'delta_ms' | 'hours_per_week';
|
||||
interface Table {
|
||||
name: 'entries' | 'closed_days' | 'balance_adjustments' | 'settings_history';
|
||||
field: Field;
|
||||
live: Map<string, number>;
|
||||
add: (value: number) => Promise<string>;
|
||||
set: (id: string, value: number) => Promise<void>;
|
||||
}
|
||||
|
||||
const ROUNDS = 300;
|
||||
const FLIGHT_EVERY = 10;
|
||||
|
||||
const tables: Table[] = [
|
||||
{
|
||||
name: 'entries',
|
||||
field: 'start_time',
|
||||
live: new Map(),
|
||||
add: (value) => save('entries', null, { start_time: value, end_time: value + 1000, auto_stopped: false, note: '', day_key: '2026-01-01' }),
|
||||
set: (id, value) => update('entries', id, { start_time: value, end_time: value + 1000 })
|
||||
},
|
||||
{
|
||||
name: 'closed_days',
|
||||
field: 'worked_ms',
|
||||
live: new Map(),
|
||||
add: (value) => save('closed_days', null, { day_key: `2026-01-${String((value % 28) + 1).padStart(2, '0')}`, worked_ms: value, kind: 'work', closed_at: 1 }),
|
||||
set: (id, value) => update('closed_days', id, { worked_ms: value })
|
||||
},
|
||||
{
|
||||
name: 'balance_adjustments',
|
||||
field: 'delta_ms',
|
||||
live: new Map(),
|
||||
add: (value) => addAdjustment({ delta_ms: value, effective_at: value }),
|
||||
set: (id, value) => update('balance_adjustments', id, { delta_ms: value })
|
||||
},
|
||||
{
|
||||
name: 'settings_history',
|
||||
field: 'hours_per_week',
|
||||
live: new Map(),
|
||||
add: (value) => save('settings_history', null, { effective_from: '2000-01-01', hours_per_week: value, workdays_mask: 31, timezone: 'UTC' }),
|
||||
set: (id, value) => update('settings_history', id, { hours_per_week: value })
|
||||
}
|
||||
];
|
||||
|
||||
const sum = (values: Map<string, number>) => [...values.values()].reduce((total, v) => total + v, 0);
|
||||
const rowsOf = (table: Table) => all(table.name) as unknown as ({ id: string } & Record<Field, number>)[];
|
||||
|
||||
describe('reactive reads after writes', () => {
|
||||
let anchor = '';
|
||||
let watchers: { count: Watcher<number>; sum: Watcher<number> }[] = [];
|
||||
let total!: Watcher<number>;
|
||||
let note!: Watcher<string | undefined>;
|
||||
let pending!: Watcher<number>;
|
||||
|
||||
const expectModel = async (round: number, deep: boolean) => {
|
||||
await tick();
|
||||
for (const [k, table] of tables.entries()) {
|
||||
const rows = rowsOf(table);
|
||||
expect(rows).toHaveLength(table.live.size);
|
||||
expect(rows.reduce((total, row) => total + row[table.field], 0)).toBe(sum(table.live));
|
||||
expect(watchers[k]?.count.current).toBe(table.live.size);
|
||||
expect(watchers[k]?.sum.current).toBe(sum(table.live));
|
||||
if (!deep) continue;
|
||||
for (const [id, value] of table.live) expect(get(table.name, id)).toMatchObject({ id, [table.field]: value, deleted: false });
|
||||
}
|
||||
expect(total.current).toBe(sum(tables[2].live));
|
||||
expect(note.current).toBe(`note ${round}`);
|
||||
expect(get('entries', anchor)?.note).toBe(`note ${round}`);
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
await openDb('stress-user');
|
||||
status.online = true;
|
||||
anchor = await save('entries', null, { start_time: 1, end_time: 2, auto_stopped: false, note: 'note 0', day_key: '2026-01-01' });
|
||||
tables[0].live.set(anchor, 1);
|
||||
watchers = tables.map((table) => ({
|
||||
count: watch(() => all(table.name).length),
|
||||
sum: watch(() => rowsOf(table).reduce((total, row) => total + row[table.field], 0))
|
||||
}));
|
||||
total = watch(() => balance().total_delta_ms);
|
||||
note = watch(() => get('entries', anchor)?.note);
|
||||
pending = watch(() => pendingCount());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const w of watchers) {
|
||||
w.count.dispose();
|
||||
w.sum.dispose();
|
||||
}
|
||||
total.dispose();
|
||||
note.dispose();
|
||||
pending.dispose();
|
||||
await closeDb();
|
||||
});
|
||||
|
||||
it(`reflect the last write in ${ROUNDS} rounds, with the sync idle and with a push in flight`, async () => {
|
||||
for (let round = 1; round <= ROUNDS; round += 1) {
|
||||
const value = round * 10;
|
||||
const target = tables[round % tables.length];
|
||||
if (!target) throw new Error('table missing');
|
||||
const added = await target.add(value);
|
||||
target.live.set(added, value);
|
||||
for (const table of tables) {
|
||||
const newest = [...table.live.keys()].at(-1);
|
||||
if (!newest) continue;
|
||||
await table.set(newest, value + 1);
|
||||
table.live.set(newest, value + 1);
|
||||
}
|
||||
const oldest = [...target.live.keys()][0];
|
||||
if (target.live.size > 2 && oldest) {
|
||||
await remove(target.name, oldest);
|
||||
target.live.delete(oldest);
|
||||
}
|
||||
await update('entries', anchor, { note: `note ${round}` });
|
||||
await expectModel(round, round % FLIGHT_EVERY === 0);
|
||||
|
||||
if (round % FLIGHT_EVERY !== 0) continue;
|
||||
await syncNow();
|
||||
expect(pendingCount()).toBe(0);
|
||||
const push = mocks.holdNextPush();
|
||||
const adjustment = await addAdjustment({ delta_ms: 7, effective_at: round });
|
||||
tables[2].live.set(adjustment, 7);
|
||||
const flight = syncNow();
|
||||
await push.entered;
|
||||
await deleteAdjustment(adjustment);
|
||||
tables[2].live.delete(adjustment);
|
||||
const day = await tables[1].add(value);
|
||||
tables[1].live.set(day, value);
|
||||
await expectModel(round, true);
|
||||
const seen = watchers[2]?.count.seen.length ?? 0;
|
||||
push.release();
|
||||
await flight;
|
||||
await syncNow();
|
||||
await expectModel(round, true);
|
||||
expect(pendingCount()).toBe(0);
|
||||
expect(pending.current).toBe(0);
|
||||
const counts = watchers[2]?.count.seen.slice(seen) ?? [];
|
||||
expect(counts.every((count) => count === tables[2].live.size)).toBe(true);
|
||||
}
|
||||
}, 120000);
|
||||
});
|
||||
Reference in New Issue
Block a user