Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: remove document init machine (#4178)

Wolf Mermelsteine3b4d47eb8ca
diff --git a/docker-compose.yml b/docker-compose.yml
index ffd9b6b402..6dac43bc9a 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -134,6 +134,10 @@ services:
ports:
- "8086:8080"
environment:
+ # - OVERRIDE_SYNC_SERVICE_URL=https://sync-service-playground.macroverse.workers.dev
+ # uncomment above, and comment out below, for when you want to use the playground sync service. also use
+ # VITE_SYNC_SERVICE_HOST=sync-service-playground.macroverse.workers.dev VITE_LOCAL_SERVERS=ALL bun run dev
+ # if you do so
- OVERRIDE_SYNC_SERVICE_URL=http://sync-service:8787
depends_on:
- redis
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index 07e5bca9f0..e43d6e4145 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -114,7 +114,12 @@ const createBlock = async (spec: {
if (split) {
split.replace({
- next: { type: blockName, id, params: createMdParams },
+ next: {
+ type: blockName,
+ id,
+ params: createMdParams,
+ preserveParams: true,
+ },
mergeHistory: true,
referredFrom: 'launcher',
});
diff --git a/js/app/packages/app/component/split-layout/layoutManager.ts b/js/app/packages/app/component/split-layout/layoutManager.ts
index e919de8be2..49a9622f14 100644
--- a/js/app/packages/app/component/split-layout/layoutManager.ts
+++ b/js/app/packages/app/component/split-layout/layoutManager.ts
@@ -38,7 +38,13 @@ type SplitKey = `${BlockName | BlockAlias | 'component'}:${string}`;
*/
export type EntryState = Record<string, unknown>;
-export type SplitContent =
+export type SplitContent = {
+ /**
+ * Whether to preserve the params originally passed when navigating to this content.
+ * If false, then it only does so the first time.
+ */
+ preserveParams?: boolean;
+} & (
| {
type: BlockName | BlockAlias;
id: string;
@@ -51,7 +57,8 @@ export type SplitContent =
id: string;
params?: Record<string, unknown>;
state?: EntryState;
- };
+ }
+);
export type SplitContentType = SplitContent['type'];
@@ -636,7 +643,10 @@ export function createSplitLayout(
cause: NavigationCause = 'fresh'
) {
const otherSplits = state.splits.filter((s) => s.id !== split.id);
- const content = attachAliasContext(next);
+ let content = attachAliasContext(next);
+ if (!content.preserveParams && content.params !== undefined) {
+ content = { ...content, params: undefined };
+ }
if (isDuplicateSplit(otherSplits, next)) return;
const splitIndex = splitIndexById(split.id);
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index 2dc138b07c..96e8b07899 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -115,10 +115,9 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
const getSyncSource = blockSyncSourceSignal.get;
const setBlockError = blockErrorSignal.set;
- const wasDirty = BrowserWALStore.isDirtyHint(LORO_WAL_DB_NAME, blockId);
const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, {
liveSyncSource: () => getSyncSource()!,
- wasDirty,
+ documentId: blockId,
});
const snapshotStore = new IDBSnapshotStore<RawUpdate>(
@@ -136,8 +135,6 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
}
setBlockError(null);
- // Fan out — the state machine in LoroManager handles precedence
- // and rejects events that don't apply for the current `wasDirty` mode.
if (optimisticSnapshot) {
loroManager.ingest({
kind: 'optimistic',
@@ -145,7 +142,7 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
});
}
- // unawaited — state machine handles precedence
+ // First one wins automatically (loro manager takes care of ignoring the rest)
ingestLocalSnapshot(loroManager, snapshotStore, walStore);
ingestS3Snapshot(loroManager, blockId);
ingestRemoteSnapshot(loroManager, data.doInitialSync);
diff --git a/js/app/packages/block-md/component/MarkdownCollabProvider.tsx b/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
index 03e7942b3f..a25cbe0634 100644
--- a/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
+++ b/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
@@ -1,6 +1,7 @@
import { markdownBlockErrorSignal } from '@block-md/signal/error';
import { createAwareness } from '@core/collab/awareness';
import { createSyncEngine } from '@core/collab/engine';
+import { logSyncService } from '@core/collab/logger';
import type { LoroManager } from '@core/collab/manager';
import {
IDBSnapshotStore,
@@ -418,7 +419,13 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
}
function startSync() {
- syncEngine.start();
+ const started = syncEngine.start();
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'debug',
+ context: {},
+ message: `engine.start() → ${started}`,
+ });
props.pluginManager.use(lexicalStateSyncPlugin);
}
@@ -428,21 +435,51 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
() => loroManager.isInitialized() ?? false,
(isInitialized) => {
if (!isInitialized) {
- console.warn('loro manager not initialized');
+ logSyncService({
+ documentId: syncSource()?.documentId ?? 'unknown',
+ level: 'debug',
+ context: {},
+ message: 'MarkdownCollabProvider: manager not yet initialized',
+ });
return;
}
const source = docSource();
- if (!source) return;
+ if (!source) {
+ logSyncService({
+ documentId: syncSource()?.documentId ?? 'unknown',
+ level: 'debug',
+ context: {},
+ message: 'editor init: no docSource yet, waiting (skeleton stays)',
+ });
+ return;
+ }
if (isSourceSyncService(source)) {
// Get the current state from the loroManager
// At this point, the loroManager should be initialized and should
// have the initial state from the sync service
const state = untrack(loroManager.state);
+ const empty = state
+ ? isStateEmpty(state.state as unknown as SerializedEditorState)
+ : null;
+
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'info',
+ context: { misc: { hasState: !!state, isEmpty: empty } },
+ message:
+ 'MarkdownCollabProvider: manager initialized, initializing editor',
+ });
//TODO: some more descriptive user facing error should be displayed here
if (!state) {
- console.error('could not initialize editor from sync service');
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'error',
+ context: {},
+ message:
+ 'editor init: no state from loroManager — editor will NOT become ready (skeleton stays)',
+ });
return;
}
@@ -450,15 +487,34 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
setDidFirstSync(true);
// Initialize the editor with the initial state from the sync service
- if (isStateEmpty(state.state as unknown as SerializedEditorState)) {
+ if (empty) {
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'debug',
+ context: {},
+ message: 'editor init: empty',
+ });
initializeEditorEmpty(props.editor);
} else {
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'debug',
+ context: {},
+ message: 'editor init: versioned state',
+ });
const initError = initializeEditorWithVersionedState(
props.editor,
state.state as unknown as SerializedEditorState,
loroManager.getPeerIdStr
);
if (initError !== null) {
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'error',
+ context: { misc: { initError } },
+ message:
+ 'editor init: initializeEditorWithVersionedState failed',
+ });
props.setEditorError(initError);
return;
}
@@ -467,6 +523,20 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
// Start the sync engine
startSync();
props.setEditorReady(true);
+ logSyncService({
+ documentId: syncSource()!.documentId,
+ level: 'info',
+ context: {},
+ message: 'editor ready (skeleton cleared)',
+ });
+ } else {
+ logSyncService({
+ documentId: syncSource()?.documentId ?? 'unknown',
+ level: 'debug',
+ context: {},
+ message:
+ 'editor init: source is not sync-service, skipping editor init (skeleton stays)',
+ });
}
}
)
diff --git a/js/app/packages/core/collab/document-init-machine.test.ts b/js/app/packages/core/collab/document-init-machine.test.ts
deleted file mode 100644
index 05653318ed..0000000000
--- a/js/app/packages/core/collab/document-init-machine.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { DocInitMachine } from './document-init-machine';
-
-describe('DocInitMachine', () => {
- describe('starting phase', () => {
- it('starts clean at rank 0 when wasDirty=false', () => {
- const m = DocInitMachine.create(false);
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 0 });
- });
-
- it('starts dirty awaiting when wasDirty=true', () => {
- const m = DocInitMachine.create(true);
- expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'awaiting' });
- });
- });
-
- describe('clean mode', () => {
- it('cascade: optimistic -> s3 -> dss converges to synced', () => {
- const m = DocInitMachine.create(false);
- expect(m.receive('optimistic')).toBe('apply');
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 1 });
- expect(m.receive('s3')).toBe('apply');
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 2 });
- expect(m.receive('dss')).toBe('apply');
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 3 });
- });
-
- it('lower-or-equal-authority kinds are ignored once a higher one is applied', () => {
- const m = DocInitMachine.create(false);
- m.receive('s3'); // rank 2
- // both lower (rank 1) and equal (rank 2) get dropped
- expect(m.receive('optimistic')).toBe('ignore');
- expect(m.receive('local')).toBe('ignore');
- expect(m.receive('s3')).toBe('ignore');
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 2 });
- });
-
- it('requested is meaningless in clean mode, always ignored', () => {
- const m = DocInitMachine.create(false);
- expect(m.receive('requested')).toBe('ignore');
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 0 });
- });
-
- it('once synced, everything is ignored', () => {
- const m = DocInitMachine.create(false);
- m.receive('dss');
- for (const kind of [
- 'optimistic',
- 'local',
- 's3',
- 'dss',
- 'requested',
- ] as const) {
- expect(m.receive(kind)).toBe('ignore');
- }
- expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 3 });
- });
- });
-
- describe('dirty mode', () => {
- it('only local transitions out of awaiting; all shallow snapshots are dropped', () => {
- const m = DocInitMachine.create(true);
- for (const kind of ['optimistic', 's3', 'dss', 'requested'] as const) {
- expect(m.receive(kind)).toBe('ignore');
- }
- expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'awaiting' });
- expect(m.receive('local')).toBe('applyThenRequestDelta');
- expect(m.currentPhase()).toEqual({
- mode: 'dirty',
- phase: 'awaitingDelta',
- });
- });
-
- it('only requested transitions out of awaitingDelta', () => {
- const m = DocInitMachine.create(true);
- m.receive('local');
- for (const kind of ['optimistic', 'local', 's3', 'dss'] as const) {
- expect(m.receive(kind)).toBe('ignore');
- }
- expect(m.currentPhase()).toEqual({
- mode: 'dirty',
- phase: 'awaitingDelta',
- });
- expect(m.receive('requested')).toBe('apply');
- expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'synced' });
- });
-
- it('full sequence: shallow snapshots arriving before AND during catch-up are dropped', () => {
- const m = DocInitMachine.create(true);
- expect(m.receive('optimistic')).toBe('ignore'); // early arrival
- expect(m.receive('dss')).toBe('ignore'); // early arrival
- expect(m.receive('local')).toBe('applyThenRequestDelta');
- expect(m.receive('s3')).toBe('ignore'); // during catch-up
- expect(m.receive('dss')).toBe('ignore'); // during catch-up
- expect(m.receive('requested')).toBe('apply');
- expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'synced' });
- });
- });
-});
diff --git a/js/app/packages/core/collab/document-init-machine.ts b/js/app/packages/core/collab/document-init-machine.ts
deleted file mode 100644
index e459b44c6c..0000000000
--- a/js/app/packages/core/collab/document-init-machine.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { match } from 'ts-pattern';
-
-/**
- * State machine for cold-load doc initialization. Coordinates which
- * snapshot source seeds the doc and rejects sources that would corrupt it.
- *
- * - clean mode (wasDirty=false): higher-authority snapshots win.
- * Once we've taken dss, we're synced.
- * - dirty mode (wasDirty=true): only the local snapshot + the resulting
- * `requestUpdatesSince` delta are accepted. Shallow snapshots from the
- * server are unsafe on top of dirty local state, we need a proper updates
- * result.
- */
-
-export type SnapshotKind = 'optimistic' | 'local' | 's3' | 'dss' | 'requested'; // op-delta from requestUpdatesSince
-
-export type Instruction = 'apply' | 'applyThenRequestDelta' | 'ignore';
-
-/**
- * Authority rank for the cold-start snapshot cascade.
- * Higher = closer to server truth.
- */
-const SNAPSHOT_AUTHORITY = {
- optimistic: 1,
- local: 1,
- s3: 2,
- dss: 3,
- requested: 0,
-} as const satisfies Record<SnapshotKind, number>;
-
-/** Phase is the machine's internal state. The discriminated union prevents
- * e.g. dirty-mode states from showing up in clean-mode reasoning. */
-type CleanPhase = { mode: 'clean'; appliedRank: 0 | 1 | 2 | 3 };
-type DirtyPhase = {
- mode: 'dirty';
- phase: 'awaiting' | 'awaitingDelta' | 'synced';
-};
-export type Phase = CleanPhase | DirtyPhase;
-
-type Transition = { instruction: Instruction; next: Phase };
-
-export class DocInitMachine {
- private phase: Phase;
-
- private constructor(wasDirty: boolean) {
- this.phase = wasDirty
- ? { mode: 'dirty', phase: 'awaiting' }
- : { mode: 'clean', appliedRank: 0 };
- }
-
- /** Pass `wasDirty: true` when the WAL has undelivered entries
- *
- * The machine then refuses every shallow snapshot and only accepts the
- * local snapshot (which triggers `requestUpdatesSince`) followed by
- * the resulting op delta.
- */
- public static create(wasDirty: boolean): DocInitMachine {
- return new DocInitMachine(wasDirty);
- }
-
- /** Feed the machine a snapshot of a given kind. Returns what the caller
- * should do with the bytes. */
- public receive(kind: SnapshotKind): Instruction {
- const { instruction, next } =
- this.phase.mode === 'clean'
- ? stepClean(this.phase, kind)
- : stepDirty(this.phase, kind);
- this.phase = next;
- return instruction;
- }
-
- public currentPhase(): Phase {
- return this.phase;
- }
-}
-
-function stepClean(phase: CleanPhase, kind: SnapshotKind): Transition {
- const rank = SNAPSHOT_AUTHORITY[kind];
- // rank=0 means "kind doesn't apply in clean mode" (just `requested`).
- // rank <= appliedRank means we've already taken something at least as
- // authoritative — applying again would be a no-op or a regression.
- if (rank === 0 || rank <= phase.appliedRank) {
- return { instruction: 'ignore', next: phase };
- }
- return {
- instruction: 'apply',
- next: { mode: 'clean', appliedRank: rank as 1 | 2 | 3 },
- };
-}
-
-function stepDirty(phase: DirtyPhase, kind: SnapshotKind): Transition {
- return match<[DirtyPhase['phase'], SnapshotKind], Transition>([
- phase.phase,
- kind,
- ])
- .with(['awaiting', 'local'], () => ({
- instruction: 'applyThenRequestDelta',
- next: { mode: 'dirty', phase: 'awaitingDelta' },
- }))
- .with(['awaitingDelta', 'requested'], () => ({
- instruction: 'apply',
- next: { mode: 'dirty', phase: 'synced' },
- }))
- .otherwise(() => ({ instruction: 'ignore', next: phase }));
-}
diff --git a/js/app/packages/core/collab/engine.ts b/js/app/packages/core/collab/engine.ts
index aa786b843a..99e65dcf59 100644
--- a/js/app/packages/core/collab/engine.ts
+++ b/js/app/packages/core/collab/engine.ts
@@ -1,11 +1,11 @@
import { type InferType, SyncDirection } from '@loro-mirror/packages/core/src';
-import { logger } from '@observability/logger';
import { Mutex } from 'async-mutex';
import type { VersionVector } from 'loro-crdt';
import type { ResultAsync } from 'neverthrow';
import { type Accessor, createEffect, createSignal, on } from 'solid-js';
import { match } from 'ts-pattern';
import type { Awareness } from './awareness';
+import { logSyncService } from './logger';
import { type LoroManager, LoroStateTag, type StateUpdate } from './manager';
import type { GenericRootSchema, LoroRawUpdate, RawUpdate } from './shared';
import type { SnapshotStore } from './snapshot-store';
@@ -87,13 +87,24 @@ export class SyncEngine<S extends GenericRootSchema, D> {
this.snapshotStore = snapshotStore;
}
+ private log(
+ level: Parameters<typeof logSyncService>[0]['level'],
+ message: string,
+ extra?: Record<string, unknown>
+ ) {
+ logSyncService({
+ documentId: this.syncs.live.documentId,
+ level,
+ context: extra ? { misc: extra } : {},
+ message,
+ });
+ }
+
public start(): boolean {
if (this._isRunning) return true; // already running — idempotent
if (!this.loroManager.isInitialized()) {
- logger.warn('Loro manager not initialized, engine will not start', {
- documentId: this.syncs.live.documentId,
- });
+ this.log('warn', 'engine.start: manager not initialized, aborting');
return false;
}
@@ -131,6 +142,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {
this._isRunning = true;
this.onRunningChange(true);
+ this.log('info', 'engine.start: ok');
return true;
}
@@ -150,6 +162,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {
this.syncs.live.pushAwareness(this.awareness.getEncodedLocalAwareness());
this._isRunning = false;
this.onRunningChange(false);
+ this.log('info', 'engine.stop: ok');
}
public async syncStateToLoro(state: InferType<S>) {
@@ -159,11 +172,8 @@ export class SyncEngine<S extends GenericRootSchema, D> {
const syncResult = await this.loroManager.syncToLoro(state);
if (syncResult.isErr()) {
- logger.error('failed to sync state to remote', {
- resolution: 'reset engine',
- scope: 'sync_engine',
- err: syncResult,
- documentId: this.syncs.live.documentId,
+ this.log('error', 'syncStateToLoro: failed, resetting engine', {
+ err: syncResult.error,
});
this.reset();
}
@@ -185,24 +195,19 @@ export class SyncEngine<S extends GenericRootSchema, D> {
}
await this.syncLock.runExclusive(async () => {
+ this.log('info', 'engine.reset: starting');
const snapshot = await (snapshotThunk ?? this.defaultSnapshotThunk)();
if (snapshot.isErr()) {
- logger.error('failed to get snapshot from source', {
- resolution: 'fail',
- scope: 'sync_engine',
+ this.log('error', 'engine.reset: failed to get snapshot', {
err: snapshot.error,
- documentId: this.syncs.live.documentId,
});
return;
}
const resetResult = await this.loroManager.reset(snapshot.value);
if (resetResult.isErr()) {
- logger.error('failed to reset engine or loro manager', {
- resolution: 'fail',
- scope: 'sync_engine',
- err: resetResult,
- documentId: this.syncs.live.documentId,
+ this.log('error', 'engine.reset: loro manager reset failed', {
+ err: resetResult.error,
});
return;
}
@@ -237,6 +242,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {
private async handleLocalUpdates(update: LoroRawUpdate) {
if (this.readonly()) return;
+ this.log('debug', 'engine: local update, appending to WAL');
void this.syncs.wal.append(update);
this.crossTabChannel?.postMessage({ type: 'update', data: update });
}
@@ -248,6 +254,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {
try {
const doc = this.loroManager.getDoc();
+ this.log('debug', 'engine: persisting snapshot', { doc: doc.toJSON() });
const snapshot = doc.export({
mode: 'shallow-snapshot',
frontiers: doc.oplogFrontiers(),
@@ -256,55 +263,51 @@ export class SyncEngine<S extends GenericRootSchema, D> {
// now safe to drop WAL entries it captures. we prune only
// after the save succeeds so that we can always recover fully.
await this.syncs.wal.pruneDelivered();
+ this.log('debug', 'engine: snapshot persisted ok');
} catch (err) {
- // DOMException's name/message aren't own-enumerable, so logging the
- // bare object hides everything but the type. Pull them out by hand.
- logger.error('failed to persist snapshot', {
- scope: 'sync_engine',
- documentId: this.syncs.live.documentId,
+ this.log('error', 'engine: failed to persist snapshot', {
errName: err instanceof Error ? err.name : undefined,
errMessage: err instanceof Error ? err.message : String(err),
- err,
});
}
}
private async handleRemoteUpdate(update: RawUpdate) {
await this.syncLock.runExclusive(async () => {
+ this.log('debug', 'engine: handling remote update');
const importResult = this.loroManager.importUpdate(update);
await Promise.resolve();
if (importResult.isErr()) {
- logger.error('failed to import remote update', {
- resolution: 'reset engine',
- scope: 'sync_engine',
- err: importResult,
- documentId: this.syncs.live.documentId,
+ this.log('error', 'engine: failed to import remote update, resetting', {
+ err: importResult.error,
});
- console.error(importResult);
this.reset();
return;
}
+ this.log('debug', 'engine: remote update imported ok');
});
}
private handleSourceEvent(event: SyncSourceEvent) {
switch (event.type) {
case 'update':
+ this.log('debug', 'engine: source event: update');
this.handleRemoteUpdate(event.update);
break;
case 'awareness':
this.awareness.importRemoteAwareness(event.awareness);
break;
case 'incremental_snapshot':
+ this.log('debug', 'engine: source event: incremental_snapshot');
this.handleRemoteUpdate(event.snapshot);
break;
- case 'reconnect': {
- logger.log('reconnecting, requesting updates since current version', {
- documentId: this.syncs.live.documentId,
- });
+ case 'reconnect':
+ this.log(
+ 'info',
+ 'engine: reconnect, requesting updates since current version'
+ );
this.requestAndHandleUpdatesSince(this.loroManager.getDoc().version());
break;
- }
}
}
@@ -312,12 +315,13 @@ export class SyncEngine<S extends GenericRootSchema, D> {
since: VersionVector,
attempt = 1
) {
+ this.log('debug', `engine: requestUpdatesSince (attempt ${attempt})`);
const updates = await this.syncs.live.requestUpdatesSince(since);
if (updates.isErr() || !updates.value) {
- console.error(
- 'failed to request updates since',
- 'error' in updates ? updates.error : 'update is undefined'
- );
+ this.log('error', 'engine: requestUpdatesSince failed', {
+ err: updates.isErr() ? updates.error : 'update is undefined',
+ attempt,
+ });
if (updates.isErr() && attempt < REQUEST_UPDATES_MAX_ATTEMPTS) {
await new Promise((resolve) =>
setTimeout(resolve, REQUEST_UPDATES_RETRY_DELAY_MS)
@@ -327,6 +331,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {
return;
}
+ this.log('debug', 'engine: requestUpdatesSince ok, applying update');
this.handleRemoteUpdate(updates.value);
}
}
diff --git a/js/app/packages/core/collab/logger.ts b/js/app/packages/core/collab/logger.ts
new file mode 100644
index 0000000000..a5b937f088
--- /dev/null
+++ b/js/app/packages/core/collab/logger.ts
@@ -0,0 +1,28 @@
+export type WalContext = {
+ count: number;
+ dirty: number;
+ mostRecentEdit?: number;
+};
+
+export type SyncLogContext = {
+ wal?: WalContext;
+ misc?: Record<string, unknown>;
+};
+
+export function logSyncService({
+ documentId,
+ level,
+ context,
+ message,
+}: {
+ documentId: string;
+ level: 'debug' | 'info' | 'warn' | 'error';
+ context: SyncLogContext;
+ message: string;
+}): void {
+ if (level === 'debug' && !(window as any).debugSyncServiceLog) return;
+ console[level === 'info' ? 'log' : level](
+ { documentId, t: Date.now(), ...context },
+ message
+ );
+}
diff --git a/js/app/packages/core/collab/manager-integration.test.ts b/js/app/packages/core/collab/manager-integration.test.ts
index 7d6d6602ca..5b8ae05061 100644
--- a/js/app/packages/core/collab/manager-integration.test.ts
+++ b/js/app/packages/core/collab/manager-integration.test.ts
@@ -42,7 +42,7 @@ function pushToServer(
server.applyUpdate(manager.getDoc().export({ mode: 'update' }));
}
-describe('LoroManager + DocInitMachine — two-client merge', () => {
+describe('LoroManager seed + converge — two-client merge', () => {
it("client B reconnects dirty: requestUpdatesSince merges its offline edits with A's concurrent edits", async () => {
await createRoot(async (dispose) => {
// ── X: shared initial snapshot ────────────────────────────────────
@@ -53,14 +53,14 @@ describe('LoroManager + DocInitMachine — two-client merge', () => {
// ── Client A — always online ──────────────────────────────────────
const clientA = createLoroManager(TEST_SCHEMA, {
liveSyncSource: () => server.asLiveSyncSource(),
- wasDirty: false,
+ documentId: 'test-doc-a',
});
await clientA.ingest({ kind: 'dss', snapshot: initialSnapshotX });
// ── Client B — will go offline ────────────────────────────────────
const clientB = createLoroManager(TEST_SCHEMA, {
liveSyncSource: () => server.asLiveSyncSource(),
- wasDirty: false,
+ documentId: 'test-doc-b',
});
await clientB.ingest({ kind: 'dss', snapshot: initialSnapshotX });
@@ -87,11 +87,11 @@ describe('LoroManager + DocInitMachine — two-client merge', () => {
});
pushToServer(clientA, server);
- // ── B reconnects: fresh manager seeded with wasDirty=true ─────────
+ // ── B reconnects: fresh manager seeds from its local snapshot ─────
const reconnectSource = server.asLiveSyncSource();
const reconnectedB = createLoroManager(TEST_SCHEMA, {
liveSyncSource: () => reconnectSource,
- wasDirty: true,
+ documentId: 'test-doc-b-reconnect',
});
await reconnectedB.ingest({
@@ -101,7 +101,7 @@ describe('LoroManager + DocInitMachine — two-client merge', () => {
// ── Assertions ────────────────────────────────────────────────────
- // 1. The state machine triggered exactly one requestUpdatesSince.
+ // 1. Seeding triggered exactly one requestUpdatesSince to converge.
expect(reconnectSource.requestUpdatesSince).toHaveBeenCalledTimes(1);
// 2. It was called with B's post-offline version vector (so the
diff --git a/js/app/packages/core/collab/manager.ts b/js/app/packages/core/collab/manager.ts
index 92347d8cdf..fdc7fe44ef 100644
--- a/js/app/packages/core/collab/manager.ts
+++ b/js/app/packages/core/collab/manager.ts
@@ -17,7 +17,7 @@ import {
} from 'loro-crdt';
import { err, ok, type Result } from 'neverthrow';
import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
-import { DocInitMachine } from './document-init-machine';
+import { logSyncService } from './logger';
import type { GenericRootSchema, LoroRawUpdate, RawUpdate } from './shared';
import type { LiveSyncSource } from './source';
@@ -239,13 +239,10 @@ export type SnapshotIngest =
| { kind: 'dss'; snapshot: RawUpdate };
export type LoroManagerOptions = {
- /** Accessor returning the live sync source. Required because the init
- * state machine may need to call `requestUpdatesSince` on it. */
+ /** Accessor returning the live sync source. Required because ingest converges
+ * to server truth via `requestUpdatesSince` after seeding. */
liveSyncSource: () => LiveSyncSource;
- /** True if the WAL had undelivered entries at the start of this session.
- * Read synchronously from `BrowserWALStore.isDirtyHint(documentId)` —
- * determines which path the init state machine takes. */
- wasDirty: boolean;
+ documentId: string;
};
/** Creates a new [LoroManager] instance
@@ -264,7 +261,25 @@ export function createLoroManager<S extends GenericRootSchema>(
const [error, setError] = createSignal<LoroManagerError[]>([]);
const [state, setState] = createSignal<StateUpdate<S>>();
- const initMachine = DocInitMachine.create(options.wasDirty);
+ const { documentId } = options;
+ /**
+ * True once the doc has been seeded from any snapshot.
+ * We ignore any subsequent snapshots provided after.
+ */
+ let seeded = false;
+ const docJson = (): unknown => {
+ try {
+ return loroDoc().toJSON();
+ } catch (e) {
+ return `<toJSON failed: ${e}>`;
+ }
+ };
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: 'manager: created',
+ });
/** Util for awaiting the sync of the mirror to finish */
const awaitMirrorSync = async () => {
@@ -285,7 +300,12 @@ export function createLoroManager<S extends GenericRootSchema>(
try {
importStatus = loroDoc().import(update);
} catch (e) {
- console.error('Failed to import update', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `importUpdate failed: ${e}`,
+ });
pushError(LoroManagerError.ImportFailed);
return err([
{
@@ -298,12 +318,24 @@ export function createLoroManager<S extends GenericRootSchema>(
const didChange = Object.keys(importStatus.success).length > 0;
if (Object.keys(importStatus.pending ?? {}).length > 0) {
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: 'importUpdate: pending updates after import',
+ });
pushError(LoroManagerError.ImportFailed);
return err([
{ code: LoroManagerError.ImportFailed, message: 'Import failed' },
]);
}
+ logSyncService({
+ documentId: documentId,
+ level: 'info',
+ context: { misc: { loroSuccess: importStatus.success, doc: docJson() } },
+ message: `importUpdate: ok (didChange=${didChange})`,
+ });
return ok(didChange);
};
@@ -315,7 +347,12 @@ export function createLoroManager<S extends GenericRootSchema>(
try {
importStatus = loroDoc().importBatch(updates);
} catch (e) {
- console.error('Failed to import update', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `importBatchUpdates failed: ${e}`,
+ });
pushError(LoroManagerError.ImportFailed);
return err([
{
@@ -328,12 +365,24 @@ export function createLoroManager<S extends GenericRootSchema>(
const didChange = Object.keys(importStatus.success).length > 0;
if (Object.keys(importStatus.pending ?? {}).length > 0) {
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: 'importBatchUpdates: pending updates after import',
+ });
pushError(LoroManagerError.ImportFailed);
return err([
{ code: LoroManagerError.ImportFailed, message: 'Import failed' },
]);
}
+ logSyncService({
+ documentId: documentId,
+ level: 'info',
+ context: { misc: { loroSuccess: importStatus.success } },
+ message: `importBatchUpdates: ok (${updates.length} updates, didChange=${didChange})`,
+ });
return ok(didChange);
};
@@ -360,7 +409,12 @@ export function createLoroManager<S extends GenericRootSchema>(
},
}));
} catch (e) {
- console.error('Failed to sync mirror', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `initializeFromSnapshot: mirror sync failed: ${e}`,
+ });
pushError(LoroManagerError.InitializeFailed);
return err([
{
@@ -373,6 +427,12 @@ export function createLoroManager<S extends GenericRootSchema>(
setInitialized(true);
setMirror(mirror_);
+ logSyncService({
+ documentId: documentId,
+ level: 'info',
+ context: { misc: { doc: docJson() } },
+ message: 'initializeFromSnapshot: ok, manager initialized',
+ });
return ok(undefined);
};
@@ -414,7 +474,12 @@ export function createLoroManager<S extends GenericRootSchema>(
})),
});
} catch (e) {
- console.error('Failed to export update', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `getUpdateSince: export failed: ${e}`,
+ });
pushError(LoroManagerError.ExportFailed);
return err([
{
@@ -457,7 +522,12 @@ export function createLoroManager<S extends GenericRootSchema>(
await awaitMirrorSync();
} catch (e) {
- console.error('Failed to sync to loro', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `syncToLoro failed: ${e}`,
+ });
return err([
{
code: LoroManagerError.SyncFailed,
@@ -466,6 +536,12 @@ export function createLoroManager<S extends GenericRootSchema>(
]);
}
+ logSyncService({
+ documentId: documentId,
+ level: 'debug',
+ context: {},
+ message: 'syncToLoro: ok',
+ });
return ok(undefined);
};
@@ -482,7 +558,12 @@ export function createLoroManager<S extends GenericRootSchema>(
try {
importStatus = newDoc.import(snapshot);
} catch (e) {
- console.error('Failed to import snapshot', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `reset: snapshot import failed: ${e}`,
+ });
pushError(LoroManagerError.ImportFailed);
return err([
{
@@ -518,6 +599,12 @@ export function createLoroManager<S extends GenericRootSchema>(
setInitialized(true);
+ logSyncService({
+ documentId: documentId,
+ level: 'info',
+ context: { misc: { loroSuccess: importStatus.success } },
+ message: 'reset: ok, manager re-initialized',
+ });
return ok(undefined);
};
@@ -529,7 +616,12 @@ export function createLoroManager<S extends GenericRootSchema>(
try {
container = loroDoc().getContainerById(id);
} catch (e) {
- console.error('Failed to get container', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `getContainerById failed: ${e}`,
+ });
pushError(LoroManagerError.GetContainerByIdFailed);
return err([
{ code: LoroManagerError.GetContainerByIdFailed, message: e },
@@ -561,7 +653,12 @@ export function createLoroManager<S extends GenericRootSchema>(
]);
}
} catch (e) {
- console.error('Failed to get cursor pos', e);
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `getCursorPos failed: ${e}`,
+ });
pushError(LoroManagerError.GetCursorPosFailed);
return err([{ code: LoroManagerError.GetCursorPosFailed, message: e }]);
}
@@ -594,69 +691,119 @@ export function createLoroManager<S extends GenericRootSchema>(
if (!initialized()) {
const initResult = await initializeFromSnapshot(snapshot);
if (initResult.isErr()) {
- console.error(
- `LoroManager.ingest(${context}): initializeFromSnapshot failed`,
- initResult.error
- );
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `applySnapshot(${context}): initializeFromSnapshot failed`,
+ });
return false;
}
return true;
}
const importResult = importUpdate(snapshot);
if (importResult.isErr()) {
- console.error(
- `LoroManager.ingest(${context}): importUpdate failed`,
- importResult.error
- );
+ logSyncService({
+ documentId: documentId,
+ level: 'error',
+ context: {},
+ message: `applySnapshot(${context}): importUpdate failed`,
+ });
return false;
}
return true;
};
/**
- * Internal helper: drive the init state machine for a given snapshot kind
+ * Pull every server op since our current version and merge it in.
+ **/
+ const convergeFromServer = async (): Promise<void> => {
+ const deltaResult = await options
+ .liveSyncSource()
+ .requestUpdatesSince(loroDoc().version());
+ if (deltaResult.isErr()) {
+ logSyncService({
+ documentId,
+ level: 'warn',
+ context: {},
+ message: 'converge: requestUpdatesSince failed',
+ });
+ return;
+ }
+ const deltaImport = importUpdate(deltaResult.value);
+ if (deltaImport.isErr()) {
+ logSyncService({
+ documentId,
+ level: 'error',
+ context: {},
+ message: 'converge: failed to apply server delta',
+ });
+ return;
+ }
+ logSyncService({
+ documentId,
+ level: 'info',
+ context: { misc: { doc: docJson() } },
+ message: 'converge: applied server delta',
+ });
+ };
+
+ /**
+ * Feed a snapshot from any source. The first snapshot to arrive seeds the
+ * (empty) doc; later snapshots are ignored because loro can't merge a snapshot
+ * onto a non-empty doc. After seeding we converge to server truth via
+ * `requestUpdatesSince`. Offline edits carried as `walUpdates` are replayed as
+ * updates (those *do* merge), regardless of seed order.
*/
const ingest = async (input: SnapshotIngest): Promise<void> => {
- const instruction = initMachine.receive(input.kind);
- if (instruction === 'ignore') return;
+ if (seeded) {
+ // Already seeded — a second snapshot can't merge. The only thing worth
+ // taking from a later `local` is its WAL updates (real ops → mergeable).
+ if (input.kind === 'local' && input.walUpdates?.length) {
+ const replayResult = importBatchUpdates(input.walUpdates);
+ if (replayResult.isErr()) {
+ logSyncService({
+ documentId,
+ level: 'error',
+ context: {},
+ message: `ingest(${input.kind}): WAL replay failed`,
+ });
+ }
+ } else {
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: `ingest(${input.kind}): ignored (already seeded)`,
+ });
+ }
+ return;
+ }
const applied = await applySnapshot(input.snapshot, input.kind);
if (!applied) return;
+ seeded = true;
+ logSyncService({
+ documentId,
+ level: 'info',
+ context: { misc: { doc: docJson() } },
+ message: `ingest: seeded from ${input.kind}`,
+ });
if (input.kind === 'local' && input.walUpdates?.length) {
const replayResult = importBatchUpdates(input.walUpdates);
if (replayResult.isErr()) {
- console.error(
- `LoroManager.ingest(${input.kind}): WAL replay failed`,
- replayResult.error
- );
+ logSyncService({
+ documentId,
+ level: 'error',
+ context: {},
+ message: `ingest(${input.kind}): WAL replay failed`,
+ });
}
}
- if (instruction !== 'applyThenRequestDelta') return;
-
- // Local was dirty — fetch the precise delta from the live source.
- const liveSource = options.liveSyncSource();
- const deltaResult = await liveSource.requestUpdatesSince(
- loroDoc().version()
- );
- if (deltaResult.isErr()) {
- console.error(
- `LoroManager.ingest(${input.kind}): requestUpdatesSince failed`,
- deltaResult.error
- );
- return;
- }
- const requestedInstruction = initMachine.receive('requested');
- if (requestedInstruction !== 'apply') return;
-
- const deltaImport = importUpdate(deltaResult.value);
- if (deltaImport.isErr()) {
- console.error(
- `LoroManager.ingest(${input.kind}): failed to apply requested delta`,
- deltaImport.error
- );
- }
+ // dss is already server truth so no reason to request updates in that case
+ if (input.kind !== 'dss') await convergeFromServer();
};
return {
diff --git a/js/app/packages/core/collab/snapshot-store.ts b/js/app/packages/core/collab/snapshot-store.ts
index d6665b735c..34a3781050 100644
--- a/js/app/packages/core/collab/snapshot-store.ts
+++ b/js/app/packages/core/collab/snapshot-store.ts
@@ -1,4 +1,5 @@
import { type DBSchema, type IDBPDatabase, openDB as idbOpen } from 'idb';
+import { logSyncService } from './logger';
import type { LoroManager } from './manager';
import type { GenericRootSchema, RawUpdate } from './shared';
import type { WALStore } from './wal';
@@ -39,12 +40,27 @@ export class IDBSnapshotStore<T> implements SnapshotStore<T> {
public async save(snapshot: T): Promise<void> {
const db = await this.db;
await db.put(STORE, { scopeId: this.scopeId, snapshot });
+ logSyncService({
+ documentId: this.scopeId,
+ level: 'debug',
+ context: {},
+ message: 'snapshot-store: saved to IDB',
+ });
}
public async load(): Promise<T | null> {
const db = await this.db;
const row = await db.get(STORE, this.scopeId);
- return row?.snapshot ?? null;
+ const found = row?.snapshot ?? null;
+ logSyncService({
+ documentId: this.scopeId,
+ level: 'debug',
+ context: {},
+ message: found
+ ? 'snapshot-store: loaded from IDB'
+ : 'snapshot-store: no snapshot found',
+ });
+ return found;
}
public async delete(): Promise<void> {
@@ -68,6 +84,12 @@ export async function loadCachedState<S extends GenericRootSchema>(
const initResult = await loroManager.initializeFromSnapshot(snapshot);
if (initResult.isErr()) {
+ logSyncService({
+ documentId: 'unknown',
+ level: 'warn',
+ context: {},
+ message: 'snapshot-store: failed to initialize from snapshot',
+ });
// Stale or corrupt snapshot. We might just keep getting this error, so
// let's drop it.
await snapshotStore.delete();
@@ -81,9 +103,11 @@ export async function loadCachedState<S extends GenericRootSchema>(
// Stop replaying. Skipped entries are safe: delivered ones are on the
// server (server sync will bring them back) and undelivered ones are
// still in the WAL (next edit or reconnect will flush them).
- console.error('failed to replay WAL entry during cold load', {
- entryId: entry.id,
- err: importResult.error,
+ logSyncService({
+ documentId: 'unknown',
+ level: 'error',
+ context: { misc: { entryId: entry.id } },
+ message: 'snapshot-store: WAL replay failed during cold load',
});
break;
}
diff --git a/js/app/packages/core/collab/testing.ts b/js/app/packages/core/collab/testing.ts
index 9fa319b40e..dc5bbff77f 100644
--- a/js/app/packages/core/collab/testing.ts
+++ b/js/app/packages/core/collab/testing.ts
@@ -74,8 +74,6 @@ export class MockWALStore<T> implements WALStore<T> {
return this.entries.length;
}
- public markClean(): void {}
-
/** Test helper: seed an entry with an explicit createdAt timestamp. */
public seedEntry(update: T, createdAt: number, delivered = false): number {
const id = this.nextId++;
diff --git a/js/app/packages/core/collab/wal.ts b/js/app/packages/core/collab/wal.ts
index 7d23a2d30b..f0776ded6d 100644
--- a/js/app/packages/core/collab/wal.ts
+++ b/js/app/packages/core/collab/wal.ts
@@ -1,4 +1,5 @@
import { type DBSchema, type IDBPDatabase, openDB as idbOpen } from 'idb';
+import { logSyncService, type WalContext } from './logger';
import type { RawUpdate } from './shared';
import type { LiveSyncSource } from './source';
@@ -31,9 +32,6 @@ export interface WALStore<T> {
pruneDelivered(): Promise<void>;
/** Drop entries older than `ttlMs`. Returns the number deleted. */
pruneExpired(ttlMs: number): Promise<number>;
- /** Signal that all entries have been delivered and nothing new is queued.
- * Implementations may use this to clear a cached "dirty" hint. */
- markClean(): void;
count(): Promise<number>;
}
@@ -46,13 +44,6 @@ export const LORO_WAL_DB_NAME = 'macro-document-wal';
const DB_VERSION = 1;
-// The "dirty hint" we keep in localStorage is just a best effort cache that
-// let's us more quickly send out a request to ask sync service for updates. We
-// could just use idb but it's simple and faster.
-const DIRTY_HINT_KEY_PREFIX = 'macro-wal-dirty-';
-const dirtyHintKey = (dbName: string, scopeId: string) =>
- `${DIRTY_HINT_KEY_PREFIX}${dbName}-${scopeId}`;
-
interface WALSchema<T> extends DBSchema {
updates: {
key: number;
@@ -76,7 +67,7 @@ export class BrowserWALStore<T> implements WALStore<T> {
}
constructor(
- private readonly dbName: string,
+ dbName: string,
private readonly scopeId: string
) {
this._db = BrowserWALStore.openDb<T>(dbName);
@@ -96,10 +87,6 @@ export class BrowserWALStore<T> implements WALStore<T> {
});
}
- static isDirtyHint(dbName: string, scopeId: string): boolean {
- return localStorage.getItem(dirtyHintKey(dbName, scopeId)) === '1';
- }
-
/** List every scopeId that currently has at least one entry. Uses a
* unique-key cursor on the `scopeId` index, so it doesn't load entries. */
static async listScopeIds(dbName: string): Promise<string[]> {
@@ -116,15 +103,7 @@ export class BrowserWALStore<T> implements WALStore<T> {
return scopeIds;
}
- private setDirtyHint(): void {
- localStorage.setItem(dirtyHintKey(this.dbName, this.scopeId), '1');
- }
-
public async append(update: T): Promise<void> {
- // Set the localStorage hint BEFORE writing to IDB so a crash between
- // the two leaves us in the "maybe dirty" state (safe) rather than
- // "clean but actually has entries" (dangerous).
- this.setDirtyHint();
const db = await this.db();
await db.add('updates', {
scopeId: this.scopeId,
@@ -134,10 +113,6 @@ export class BrowserWALStore<T> implements WALStore<T> {
});
}
- public markClean(): void {
- localStorage.removeItem(dirtyHintKey(this.dbName, this.scopeId));
- }
-
public async getAll(): Promise<WALEntry<T>[]> {
const db = await this.db();
return db.getAllFromIndex('updates', 'scopeId', this.scopeId) as Promise<
@@ -204,9 +179,9 @@ export class BrowserWALStore<T> implements WALStore<T> {
/**
* Append-only queue with retry semantics. Caller-supplied `push` does the
- * actual transport; the syncer handles persistence, batching, dedupe, and
- * markClean coordination. Triggering flushes on transport reconnect (or
- * other "try again" signals) is the caller's responsibility.
+ * actual transport; the syncer handles persistence, batching, and dedupe.
+ * Triggering flushes on transport reconnect (or other "try again" signals)
+ * is the caller's responsibility.
*/
export class WALSyncer<T> {
/** True while a flush is in progress — prevents concurrent flushes. */
@@ -225,7 +200,8 @@ export class WALSyncer<T> {
constructor(
private readonly store: WALStore<T>,
- private readonly push: (items: T[]) => Promise<boolean>
+ private readonly push: (items: T[]) => Promise<boolean>,
+ private readonly label?: string
) {
this.readyPromise = this.setup();
}
@@ -233,8 +209,13 @@ export class WALSyncer<T> {
/* Right now just drops expired entries. */
private async setup(): Promise<void> {
const deleted = await this.store.pruneExpired(WAL_TTL_MS);
- if (deleted > 0) {
- console.warn(`WAL: dropped expired entries (count: ${deleted})`);
+ if (deleted > 0 && this.label) {
+ logSyncService({
+ documentId: this.label,
+ level: 'warn',
+ context: { wal: await this.summary() },
+ message: `WAL: dropped ${deleted} expired entries`,
+ });
}
}
@@ -245,11 +226,25 @@ export class WALSyncer<T> {
public async append(item: T): Promise<void> {
await this.ready();
await this.store.append(item);
+ if (this.label)
+ logSyncService({
+ documentId: this.label,
+ level: 'debug',
+ context: { wal: await this.summary() },
+ message: 'WAL: wrote to IDB',
+ });
this.hasNewPending = true;
void this.flush(); // unawaited
}
public flush(): Promise<void> {
+ if (this.label)
+ logSyncService({
+ documentId: this.label,
+ level: 'debug',
+ context: {},
+ message: `WAL flush: triggered (isFlushing=${this.isFlushing})`,
+ });
if (this.isFlushing) return this.pendingFlush;
this.pendingFlush = this.doFlush();
return this.pendingFlush;
@@ -259,6 +254,16 @@ export class WALSyncer<T> {
return this.store.pruneDelivered();
}
+ public async summary(): Promise<WalContext> {
+ const entries = await this.store.getAll();
+ const undelivered = entries.filter((e) => !e.delivered);
+ return {
+ count: entries.length,
+ dirty: undelivered.length,
+ mostRecentEdit: undelivered.at(-1)?.createdAt,
+ };
+ }
+
public destroy(): void {
for (const fn of this.cleanupFns) fn();
this.cleanupFns = [];
@@ -280,16 +285,33 @@ export class WALSyncer<T> {
const undelivered = entries.filter((e) => !e.delivered);
if (undelivered.length === 0) return; // nothing to do
+ if (this.label)
+ logSyncService({
+ documentId: this.label,
+ level: 'debug',
+ context: { wal: await this.summary() },
+ message: `WAL flush: pushing ${undelivered.length} entries`,
+ });
+
const delivered = await this.push(undelivered.map((e) => e.update));
if (delivered) {
await this.store.markDelivered(undelivered.map((e) => e.id));
- // Clear the dirty hint only if no new edits arrived during the flush.
- if (!this.hasNewPending) this.store.markClean();
+ if (this.label)
+ logSyncService({
+ documentId: this.label,
+ level: 'debug',
+ context: { wal: await this.summary() },
+ message: `WAL flush: delivered ${undelivered.length} entries`,
+ });
} else {
- console.warn('WAL flush: push not acked', {
- count: undelivered.length,
- });
+ if (this.label)
+ logSyncService({
+ documentId: this.label,
+ level: 'warn',
+ context: { wal: await this.summary() },
+ message: `WAL flush: push not acked (${undelivered.length} entries)`,
+ });
succeeded = false;
}
} finally {
@@ -313,8 +335,10 @@ export function createWALSyncSource(
LORO_WAL_DB_NAME,
live.documentId
);
- const syncer = new WALSyncer<RawUpdate>(store, (updates) =>
- live.pushUpdate(updates)
+ const syncer = new WALSyncer<RawUpdate>(
+ store,
+ (updates) => live.pushUpdate(updates),
+ live.documentId
);
live.listen((event) => {
if (event.type === 'reconnect') void syncer.flush();
diff --git a/js/app/packages/service-clients/service-sync/source.ts b/js/app/packages/service-clients/service-sync/source.ts
index 5e1585a63c..991035a624 100644
--- a/js/app/packages/service-clients/service-sync/source.ts
+++ b/js/app/packages/service-clients/service-sync/source.ts
@@ -1,3 +1,4 @@
+import { logSyncService } from '@core/collab/logger';
import type { RawUpdate } from '@core/collab/shared';
import {
type InitialSync,
@@ -136,6 +137,13 @@ export const createSyncServiceSource = (
// server's RemoteInitialSync message arrives (~50ms after WS opens).
// `doInitialSync()` just returns the cached promise; if it's called late,
// it still resolves because the listener captured the message.
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: 'sync source: created, waiting for WS open',
+ });
+
let initialSyncReceived = false;
const initialSyncPromise = ResultAsync.fromPromise(
raceTimeout(
@@ -146,6 +154,12 @@ export const createSyncServiceSource = (
() => SyncError.timeout(TIMEOUTS.INITIAL_SYNC)
).map((message) => {
initialSyncReceived = true;
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: 'sync source: initial sync received',
+ });
// Start heartbeat only after initial sync completes successfully
// This prevents the heartbeat from closing the connection during slow initial syncs
ws.startHeartbeat();
@@ -187,6 +201,12 @@ export const createSyncServiceSource = (
});
createReconnectEffect(ws, async () => {
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: 'sync source: WS reconnected, waiting for initial sync',
+ });
// Always restart heartbeat after reconnect, regardless of sync success/failure.
// This ensures the connection is monitored even if sync fails.
// startHeartbeat() is safe to call - it will no-op if connection closed.
@@ -203,15 +223,24 @@ export const createSyncServiceSource = (
).map((message) => message.value as InitialSync);
if (reconnectSyncResult.isErr()) {
- console.error(
- 'Failed to reconnect to sync service',
- reconnectSyncResult.error
- );
+ logSyncService({
+ documentId,
+ level: 'warn',
+ context: { misc: { error: reconnectSyncResult.error } },
+ message: 'sync source: reconnect initial sync timed out',
+ });
// Heartbeat is already running from above, so connection remains monitored
// even though sync failed. The connection will eventually timeout and retry.
return;
}
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message:
+ 'sync source: reconnect initial sync received, emitting reconnect event',
+ });
eventBus.emit({
type: 'reconnect',
snapshot: reconnectSyncResult.value.snapshot,
@@ -324,6 +353,12 @@ export const createSyncServiceSource = (
}
const cleanup = () => {
+ logSyncService({
+ documentId,
+ level: 'debug',
+ context: {},
+ message: 'sync source: cleanup called, closing WS',
+ });
if (typeof window !== 'undefined') {
window.removeEventListener('online', handleOnline);
document.removeEventListener('visibilitychange', handleVisibilityChange);
diff --git a/rust/sync-service/justfile b/rust/sync-service/justfile
index 6e6908fa5a..7eda2c5bc5 100644
--- a/rust/sync-service/justfile
+++ b/rust/sync-service/justfile
@@ -17,7 +17,7 @@ setup:
npm install && cd bebop/ && npx bebopc build
worker_build_setup:
- cargo install worker-build
+ cargo install [email protected]
# initialize the local D1 database used by wrangler dev
migrate-d1-local:
diff --git a/rust/sync-service/wrangler.toml b/rust/sync-service/wrangler.toml
index af71d314cc..606e98cf29 100644
--- a/rust/sync-service/wrangler.toml
+++ b/rust/sync-service/wrangler.toml
@@ -3,7 +3,7 @@ main = "build/worker/shim.mjs"
compatibility_date = "2025-03-05"
[build]
-command = "cargo install -q worker-build --locked && worker-build --release"
+command = "cargo install -q [email protected] --locked && worker-build --release"
[observability.logs]
enabled = true