Skip to content

A local-first personal finance app

[AI] Restore clock timestamp when message sync fails (#8904)

Joshua Soberg1b245f260011
diff --git a/packages/loot-core/src/server/sync/index.ts b/packages/loot-core/src/server/sync/index.ts
index a360862d8f..2517a6b559 100644
--- a/packages/loot-core/src/server/sync/index.ts
+++ b/packages/loot-core/src/server/sync/index.ts
@@ -399,7 +399,7 @@ export type Message = {
value: string | number | null | UnknownFormatValue;
};
-async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
+async function _applyMessages(messages: Message[], isReceived = false) {
if (checkSyncingMode('import')) {
applyMessagesForImport(messages);
return undefined;
@@ -484,7 +484,9 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
const applied = apply(
msg,
getIn(oldData, [dataset, row]) || added.has(dataset + row),
- deferUnknownSchema,
+ // Inbound messages may come from a newer version of the app, so
+ // unknown-schema errors defer instead of failing the batch
+ isReceived,
);
if (applied) {
@@ -543,7 +545,11 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
newData = fetchData(idsPerTable);
};
- db.transaction(applyInTransaction, { immediate: true });
+ if (isReceived) {
+ receiveInTransaction(messages, applyInTransaction);
+ } else {
+ db.transaction(applyInTransaction, { immediate: true });
+ }
// The transaction succeeded, so we can update in-memory objects now
undo.appendMessages(messages, oldData);
@@ -634,34 +640,54 @@ async function _applyMessages(messages: Message[], deferUnknownSchema = false) {
export const applyMessages = sequential(_applyMessages);
-export function receiveMessages(messages: Message[]): Promise<Message[]> {
- try {
- // Receiving the latest timestamp preserves the clock and drift check while
- // advancing the counter once per batch.
- let latest = null;
- for (const { timestamp } of messages) {
- if (
- latest === null ||
- timestamp.millis() > latest.millis() ||
- (timestamp.millis() === latest.millis() &&
- timestamp.counter() > latest.counter())
- ) {
- latest = timestamp;
- }
- }
- if (latest !== null) {
- Timestamp.recv(latest);
+// Receiving the batch's latest timestamp inside the transaction advances
+// the clock once per batch and includes it in the saved `messages_clock`
+// row. If the transaction fails, the clock is restored along with it.
+function receiveInTransaction(
+ messages: Message[],
+ applyInTransaction: () => void,
+) {
+ let latest: Timestamp | null = null;
+ for (const { timestamp } of messages) {
+ if (
+ latest === null ||
+ timestamp.millis() > latest.millis() ||
+ (timestamp.millis() === latest.millis() &&
+ timestamp.counter() > latest.counter())
+ ) {
+ latest = timestamp;
}
+ }
+
+ const clock = getClock();
+ const savedMillis = clock.timestamp.millis();
+ const savedCounter = clock.timestamp.counter();
+ try {
+ db.transaction(
+ () => {
+ if (latest !== null) {
+ Timestamp.recv(latest);
+ }
+ applyInTransaction();
+ },
+ { immediate: true },
+ );
+ } catch (e) {
+ clock.timestamp.setMillis(savedMillis);
+ clock.timestamp.setCounter(savedCounter);
+ throw e;
+ }
+}
+
+export async function receiveMessages(messages: Message[]): Promise<Message[]> {
+ try {
+ return await runMutator(() => applyMessages(messages, true));
} catch (e) {
if (e instanceof Timestamp.ClockDriftError) {
throw new SyncError('clock-drift');
}
throw e;
}
-
- // Inbound messages may come from a newer version of the app, so
- // unknown-schema errors defer instead of failing the batch
- return runMutator(() => applyMessages(messages, true));
}
async function errorHandler(e: Error) {
diff --git a/packages/loot-core/src/server/sync/sync.test.ts b/packages/loot-core/src/server/sync/sync.test.ts
index 0a9b455972..1f4fe1549c 100644
--- a/packages/loot-core/src/server/sync/sync.test.ts
+++ b/packages/loot-core/src/server/sync/sync.test.ts
@@ -11,6 +11,7 @@ import * as encoder from './encoder';
import { isError } from './utils';
import {
+ addSyncListener,
applyMessages,
fullSync,
receiveMessages,
@@ -188,7 +189,7 @@ describe('Sync', () => {
expect(getClock().timestamp.toString() > latest).toBe(true);
});
- it('should reject a batch holding a far-future timestamp', () => {
+ it('should reject a batch holding a far-future timestamp', async () => {
// `toISOString` writes years above 9999 as `+010000-…`, which sorts below
// every normal timestamp. The batch maximum must not rank it last, which
// would let it skip the clock drift check.
@@ -202,12 +203,66 @@ describe('Sync', () => {
),
});
- expect(() =>
+ await expect(
receiveMessages([
message(Date.parse('1970-01-02T00:00:00.000Z')),
message(253402300800000),
]),
- ).toThrow(expect.objectContaining({ reason: 'clock-drift' }));
+ ).rejects.toMatchObject({ reason: 'clock-drift' });
+ });
+});
+
+describe('receiveMessages', () => {
+ function conflictingMessages() {
+ const timestamp = new Timestamp(Date.now() + 5000, 0, '0000000000000001');
+ // Duplicate timestamps make the batch fail inside the database transaction.
+ return ['foo', 'bar'].map(row => ({
+ dataset: 'transactions',
+ row,
+ column: 'amount',
+ value: 3200,
+ timestamp,
+ }));
+ }
+
+ it('discards failed clock advances before receiving the next queued batch', async () => {
+ const messages = conflictingMessages();
+ const failedBatch = receiveMessages(messages);
+ const nextBatch = receiveMessages([
+ {
+ ...messages[0],
+ timestamp: new Timestamp(Date.now() + 1000, 0, '0000000000000002'),
+ },
+ ]);
+
+ await expect(failedBatch).rejects.toThrow(/UNIQUE constraint failed/);
+ await expect(nextBatch).resolves.toHaveLength(1);
+ expect(getClock().timestamp.millis()).toBe(Date.now() + 1000);
+ expect(getClock().timestamp.counter()).toBe(1);
+ });
+
+ it('does not reuse timestamps issued while a failed receive is pending', async () => {
+ const failedBatch = receiveMessages(conflictingMessages());
+ const issued = Timestamp.send();
+
+ await expect(failedBatch).rejects.toThrow(/UNIQUE constraint failed/);
+ expect(Timestamp.send().toString() > issued.toString()).toBe(true);
+ });
+
+ it('keeps the received clock when a step after the commit fails', async () => {
+ const [message] = conflictingMessages();
+ const removeListener = addSyncListener(() => {
+ throw new Error('listener failed');
+ });
+
+ try {
+ await expect(receiveMessages([message])).rejects.toThrow(
+ 'listener failed',
+ );
+ } finally {
+ removeListener();
+ }
+ expect(getClock().timestamp.millis()).toBe(message.timestamp.millis());
});
});
diff --git a/upcoming-release-notes/restore-clock-state-on-failed-received-messages-sync.md b/upcoming-release-notes/restore-clock-state-on-failed-received-messages-sync.md
new file mode 100644
index 0000000000..07d77c1839
--- /dev/null
+++ b/upcoming-release-notes/restore-clock-state-on-failed-received-messages-sync.md
@@ -0,0 +1,6 @@
+---
+category: Bugfixes
+authors: [jsoberg]
+---
+
+Restore the sync clock when a batch of received changes fails to apply, so the failure no longer leaves the clock advanced