🐛 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:
2026-12-01 17:56:43 +01:00
parent bd2ec79a69
commit 6ce66f81c7
2 changed files with 295 additions and 25 deletions
+93 -25
View File
@@ -3,6 +3,7 @@ import {
DefaultDataAdapter,
createReactivityAdapter,
type BaseItem,
type Changeset,
type Cursor,
type ReactivityAdapter,
type Selector
@@ -11,6 +12,7 @@ import { SyncManager } from '@signaldb/sync';
import svelteReactivityAdapter from '@signaldb/svelte';
import prepareIndexedDB from '@signaldb/indexeddb';
import { pb } from '$lib/pb';
import type { RecordModel } from 'pocketbase';
import { COLLECTIONS, DATA_FIELDS, ZERO_MEANS_NULL, type CollectionName, type PayloadMap } from '$lib/types';
import { newId } from '$lib/utils';
@@ -147,6 +149,46 @@ let epoch = 0;
let pullRuns = 0;
const pendingCursor = new Map<string, string>();
const staleBuffer = new Map<string, AnyDoc[]>();
/** Change records the last push of a collection sent; the pull after it keeps newer local changes. */
const pushedChanges = new Map<string, Set<string>>();
/** Collections whose local state the sync is about to touch or is touching, by name and nesting depth. */
const applying = new Map<string, number>();
const pause = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
function enterApply(name: string): void {
applying.set(name, (applying.get(name) ?? 0) + 1);
}
function leaveApply(name: string): void {
const depth = (applying.get(name) ?? 0) - 1;
if (depth > 0) applying.set(name, depth);
else applying.delete(name);
}
/** A write in flight has no change record yet, so the server state must wait for it. */
async function quiesce<T extends BaseItem>(c: Collection<T, string>): Promise<void> {
while (c.isPushing()) await pause();
}
/** The sync knows nothing of a write made while it applies server state, so writes wait for it. */
async function waitForApply(name: string): Promise<void> {
while (applying.has(name)) await pause();
}
/** Server records changed since the cursor; a pull inside an apply lets local writes run while the request is out. */
async function pullRecords(name: string, cursor: string | null): Promise<RecordModel[]> {
const inside = applying.has(name);
if (inside) leaveApply(name);
try {
return await pb.collection(name).getFullList({
sort: 'updated',
...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {})
});
} finally {
if (inside) enterApply(name);
}
}
function onSynced(name: string) {
const c = pendingCursor.get(name);
@@ -163,6 +205,21 @@ class WotraSync extends SyncManager<Record<string, unknown>, AnyDoc, string> {
const changes = this.changes;
return inScope() ? changes.find({}).count() : readOnce(changes, {}, (cursor) => cursor.count());
}
override async syncWithData(name: string, data: { changes: Changeset<AnyDoc>; items?: never } | { items: AnyDoc[]; changes?: never }): Promise<void> {
enterApply(name);
try {
await super.syncWithData(name, data);
} finally {
leaveApply(name);
}
}
/** Items with a change record that the push of this round did not send; a scan, since an index lags behind a write in flight. */
async unpushed(name: string, pushed: Set<string> | undefined): Promise<Set<string>> {
await quiesce(this.changes);
const records = await this.changes.find({}, { reactive: false, async: true }).fetch();
const ids = records.filter((c) => c.collectionName === name && !pushed?.has(c.id)).map((c) => (typeof c.data === 'object' ? c.data.id : c.data));
return new Set(ids.map(String));
}
/** Lets writes in flight finish, since the sync manager rejects them after dispose(). */
async settle(): Promise<void> {
const busy = () => [this.changes, ...[...this.collections.values()].map((c) => c.collection)].some((c) => c.isPushing());
@@ -207,6 +264,8 @@ async function doOpenDb(uid: string): Promise<void> {
userId = uid;
pendingCursor.clear();
staleBuffer.clear();
pushedChanges.clear();
applying.clear();
const idb = prepareIndexedDB({ databaseName: localDbName(uid), version: SCHEMA_VERSION, schema: schema() });
const adapter = new DefaultDataAdapter({ storage: (name) => idb(name) });
const c = {} as Record<CollectionName, AnyCollection>;
@@ -217,7 +276,7 @@ async function doOpenDb(uid: string): Promise<void> {
return;
}
cols = c;
const m = new WotraSync({
const m: WotraSync = new WotraSync({
id: SYNC_ID,
dataAdapter: adapter,
reactivity,
@@ -229,11 +288,12 @@ async function doOpenDb(uid: string): Promise<void> {
pull: async ({ name }) => {
pullRuns += 1;
const n = name as CollectionName;
const pushed = pushedChanges.get(name);
pushedChanges.delete(name);
const cursor = localStorage.getItem(cursorKey(uid, name));
const records = await pb.collection(name).getFullList({
sort: 'updated',
...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {})
});
const records = await pullRecords(name, cursor);
await quiesce(c[n]);
const waiting = await m.unpushed(name, pushed);
let max = cursor ?? '';
for (const r of records) if (r.updated > max) max = r.updated;
if (max) pendingCursor.set(name, max);
@@ -242,30 +302,36 @@ async function doOpenDb(uid: string): Promise<void> {
const merged = new Map<string, AnyDoc>();
for (const r of stale) merged.set(r.id, r);
for (const r of records) merged.set(r.id, toRecord(n, r));
return { changes: { added: [], modified: [...merged.values()], removed: [] } };
return { changes: { added: [], modified: [...merged.values()].filter((doc) => !waiting?.has(doc.id)), removed: [] } };
},
push: async ({ name }, { changes }) => {
push: async ({ name }, { changes, rawChanges }) => {
pushedChanges.set(name, new Set((rawChanges as unknown as { id: string }[]).map((c) => c.id)));
const items = [...changes.added, ...changes.modified];
const n = name as CollectionName;
for (let i = 0; i < items.length; i += PUSH_BATCH) {
const res = await pb.send<{ results: PushResult[] }>('/api/sync/push', {
method: 'POST',
body: {
changes: items.slice(i, i + PUSH_BATCH).map((it) => ({
collection: name,
id: it.id,
data: toServerData(n, it),
client_updated_at: it.client_updated_at,
deleted: it.deleted
}))
leaveApply(name);
try {
for (let i = 0; i < items.length; i += PUSH_BATCH) {
const res = await pb.send<{ results: PushResult[] }>('/api/sync/push', {
method: 'POST',
body: {
changes: items.slice(i, i + PUSH_BATCH).map((it) => ({
collection: name,
id: it.id,
data: toServerData(n, it),
client_updated_at: it.client_updated_at,
deleted: it.deleted
}))
}
});
for (const r of res?.results ?? []) {
if (r.status === 'ok' || !r.record || !isCollection(r.collection)) continue;
const list = staleBuffer.get(r.collection) ?? [];
list.push(toRecord(r.collection, r.record));
staleBuffer.set(r.collection, list);
}
});
for (const r of res?.results ?? []) {
if (r.status === 'ok' || !r.record || !isCollection(r.collection)) continue;
const list = staleBuffer.get(r.collection) ?? [];
list.push(toRecord(r.collection, r.record));
staleBuffer.set(r.collection, list);
}
} finally {
enterApply(name);
}
},
registerRemoteChange: async ({ name }, onChange) => {
@@ -401,7 +467,9 @@ export function get<K extends CollectionName>(name: K, id: string): Doc<PayloadM
export async function save<K extends CollectionName>(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise<string> {
if (!cols) throw new Error('database is not open');
const c = cols[name];
await waitForApply(name);
const c = cols?.[name];
if (!c) throw new Error('database is not open');
const rid = id ?? newId();
const now = Date.now();
const prev = readOnce(c, { id: rid }, (cursor) => cursor.fetch()[0]);