// // Copyright 2026 DXOS.org // import { RawString, getHeads, hasHeads, init, loadIncremental } from '@automerge/automerge'; import { describe, expect, onTestFinished, test, vi } from 'vitest'; import { Context } from '@dxos/context'; import { BACKED_OBJECT_LIMIT, type DatabaseDirectory, EntityStructure, SpaceDocVersion, createIdFromSpaceKey, } from '@dxos/echo-protocol'; import { objectStructureFromJson } from '@dxos/echo/internal'; import * as EffectEx from '@dxos/effect/EffectEx'; import { type IndexCursor } from '@dxos/index-core'; import { invariant } from '@dxos/invariant'; import { DXN, type EntityId, PublicKey, SpaceId } from '@dxos/keys'; import { AutomergeHost } from '../automerge/index.ts'; import { createTestSqliteRuntime } from '../testing/index.ts'; import { AutomergeDataSource, headsCodec } from './automerge-data-source.ts'; const TEST_TYPE = DXN.make('com.example.type.test', '0.1.0'); const OTHER_TYPE = DXN.make('com.example.type.other', '0.1.0'); const PERSON_TYPE = DXN.make('com.example.type.person', '0.1.0'); /** * Set up a real AutomergeHost with SQLite storage. */ const setupAutomergeHost = async (): Promise => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime }); await host.open(); onTestFinished(async () => { await host.close(); }); return host; }; /** * Create a DatabaseDirectory document with the given objects. */ const createDatabaseDirectory = async ( host: AutomergeHost, spaceId: SpaceId, objects: Record, ): Promise>>> => { const handle = await host.createDoc({ version: SpaceDocVersion.CURRENT, access: { spaceId }, objects: {}, links: {}, }); handle.change((doc) => { doc.objects = objects; }); return handle; }; describe('AutomergeDataSource', () => { test('headsCodec encodes and decodes heads correctly', () => { const heads = ['abc123', 'def456']; const encoded = headsCodec.encode(heads); expect(encoded).toBe('abc123|def456'); expect(headsCodec.decode(encoded)).toEqual(['abc123', 'def456']); }); test('headsCodec sorts heads for consistent encoding', () => { const heads1 = ['def456', 'abc123']; const heads2 = ['abc123', 'def456']; expect(headsCodec.encode(heads1)).toBe(headsCodec.encode(heads2)); }); test('returns empty when no documents exist', async () => { const host = await setupAutomergeHost(); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toHaveLength(0); }); test('returns new documents that have no cursor', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const handle = await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Test Document' } }), }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(1); expect(result.objects[0].documentId).toBe(handle.documentId); expect(result.objects[0].data.title).toBe('Test Document'); expect(result.cursors).toHaveLength(1); expect(result.cursors[0].resourceId).toBe(handle.documentId); expect(result.cursors[0].cursor).toBe(headsCodec.encode(getHeads(handle.doc()!))); }); test('records the heads it read as the version, and ships heads only once they are saved', async () => { const host = await setupAutomergeHost(); const handle = await createDatabaseDirectory(host, SpaceId.random(), { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'saved', body: new RawString('raw text') }, }), }); await host.flush(Context.default()); const savedHeads = getHeads(handle.doc()!); handle.change((doc) => { doc.objects!['obj-1'].data.title = 'unsaved'; }); const dataSource = new AutomergeDataSource(host); const unsaved = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); const unsavedObject = unsaved.objects.find((object) => object.data.id === 'obj-1'); const unsavedDoc = handle.doc(); invariant(unsavedDoc); expect(unsavedObject?.heads).toBeUndefined(); expect(unsavedObject?.version).toEqual(getHeads(unsavedDoc)); await host.flush(Context.default()); const cursor: IndexCursor = { indexName: 'fts', spaceId: null, sourceName: 'automerge', resourceId: handle.documentId, cursor: headsCodec.encode(savedHeads), }; const { objects } = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [cursor])); const object = objects.find((object) => object.data.id === 'obj-1'); invariant(object?.heads); expect(object.heads).toEqual(getHeads(handle.doc()!)); expect(object.version).toEqual(object.heads); const stored = loadIncremental(init(), (await host.readStoredChanges(handle.documentId))!); expect(hasHeads(stored, [...object.heads])).toBe(true); const structure = objectStructureFromJson(JSON.parse(JSON.stringify(object.data))); expect(structure.data.title).toBe('unsaved'); expect(structure.data.body).toBe('raw text'); }); test('backs no object that shares its document, was merged away, or is over the size limit', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'shared' } }), 'obj-2': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'shared' } }), }); await createDatabaseDirectory(host, spaceId, { 'obj-3': EntityStructure.makeObject({ type: TEST_TYPE, data: { body: new RawString('x'.repeat(BACKED_OBJECT_LIMIT + 1)) }, }), }); const merged = EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'merged' } }); merged.system = { ...merged.system, mergedInto: 'obj-1' as EntityId }; await createDatabaseDirectory(host, spaceId, { 'obj-4': merged }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const { objects } = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(objects).toHaveLength(4); expect(objects.every((object) => object.heads === undefined && object.version !== undefined)).toBe(true); }); test('returns documents with changed heads', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const handle1 = await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Doc 1' } }), }); const handle2 = await createDatabaseDirectory(host, spaceId, { 'obj-2': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Doc 2' } }), }); await host.flush(Context.default()); // Capture heads before mutation. const doc1HeadsBefore = headsCodec.encode(getHeads(handle1.doc()!)); const doc2Heads = headsCodec.encode(getHeads(handle2.doc()!)); // Modify doc1 to have new heads. handle1.change((doc: DatabaseDirectory) => { doc.objects!['obj-1'].data.title = 'Doc 1 Updated'; }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const cursors: IndexCursor[] = [ { indexName: 'fts', spaceId: null, sourceName: 'automerge', resourceId: handle1.documentId, cursor: doc1HeadsBefore, }, { indexName: 'fts', spaceId: null, sourceName: 'automerge', resourceId: handle2.documentId, cursor: doc2Heads }, ]; const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), cursors)); // Only doc1 changed. expect(result.objects).toHaveLength(1); expect(result.objects[0].documentId).toBe(handle1.documentId); }); test('skips documents with unchanged heads', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const handle = await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Doc 1' } }), }); await host.flush(Context.default()); const currentHeads = headsCodec.encode(getHeads(handle.doc()!)); const dataSource = new AutomergeDataSource(host); const cursors: IndexCursor[] = [ { indexName: 'fts', spaceId: null, sourceName: 'automerge', resourceId: handle.documentId, cursor: currentHeads, }, ]; const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), cursors)); expect(result.objects).toHaveLength(0); expect(result.cursors).toHaveLength(0); }); test('respects limit option', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); // Create 3 documents. for (let i = 1; i <= 3; i++) { await createDatabaseDirectory(host, spaceId, { [`obj-${i}`]: EntityStructure.makeObject({ type: TEST_TYPE, data: { title: `Doc ${i}` } }), }); } await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), [], { limit: 2 }), ); expect(result.objects).toHaveLength(2); expect(result.cursors).toHaveLength(2); expect(result.more).toBe(true); // A limit the backlog exactly fills is not a cut: `more` says a changed document was left behind. const exact = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [], { limit: 3 })); expect(exact.objects).toHaveLength(3); expect(exact.more).toBe(false); }); test('extracts multiple objects from a document', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Object 1' } }), 'obj-2': EntityStructure.makeObject({ type: OTHER_TYPE, data: { title: 'Object 2' } }), }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(2); expect(result.objects.map((o) => o.data.id)).toContain('obj-1'); expect(result.objects.map((o) => o.data.id)).toContain('obj-2'); }); test('skips outdated documents', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); // Create a document with outdated version. const handle = await host.createDoc({ version: 0 as SpaceDocVersion, // Outdated version. access: { spaceId }, objects: {}, links: {}, }); handle.change((doc) => { doc.objects = { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Test' } }), }; }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toEqual([{ spaceId, resourceId: handle.documentId, cursor: expect.any(String) }]); const again = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), result.cursors)); expect(again.cursors).toEqual([]); }); test('extracts object attributes correctly', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); await createDatabaseDirectory(host, spaceId, { 'person-1': EntityStructure.makeObject({ type: PERSON_TYPE, data: { name: 'Alice', age: 30 }, }), }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(1); const obj = result.objects[0]; expect(obj.data.id).toBe('person-1'); expect(obj.data['@type']).toBe(PERSON_TYPE); expect(obj.data.name).toBe('Alice'); expect(obj.data.age).toBe(30); }); test('skips documents without space identifiers', async () => { const host = await setupAutomergeHost(); // Create a document without access.spaceId/spaceKey. const handle = await host.createDoc({ version: SpaceDocVersion.CURRENT, objects: {}, links: {}, }); handle.change((doc) => { doc.objects = { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'No Space' } }), }; }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toEqual([{ spaceId: null, resourceId: handle.documentId, cursor: expect.any(String) }]); }); test('a document whose space cannot be derived is read and gets a cursor', async () => { const host = await setupAutomergeHost(); const handle = await createDatabaseDirectory(host, 'not-a-space-id' as SpaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Bad space' } }), }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toEqual([{ spaceId: null, resourceId: handle.documentId, cursor: expect.any(String) }]); }); test('a document whose read throws gets a cursor, with none of its objects, and is not read again', async () => { const host = await setupAutomergeHost(); const handle = await createDatabaseDirectory(host, SpaceId.random(), { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Corrupt' } }), }); await host.flush(Context.default()); vi.spyOn(host, 'loadDoc').mockResolvedValue({ doc: () => { throw new Error('corrupt document'); }, [Symbol.dispose]: () => {}, } as never); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toEqual([{ spaceId: null, resourceId: handle.documentId, cursor: expect.any(String) }]); const again = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), result.cursors)); expect(again.cursors).toEqual([]); }); test('a document whose read throws partway contributes none of its objects', async () => { const host = await setupAutomergeHost(); const handle = await createDatabaseDirectory(host, SpaceId.random(), { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Fine' } }), 'obj-2': null as never, }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(0); expect(result.cursors).toMatchObject([{ resourceId: handle.documentId }]); }); test('derives spaceId from documents that only carry the legacy spaceKey field', async () => { const host = await setupAutomergeHost(); const spaceKey = PublicKey.random(); const handle = await host.createDoc({ version: SpaceDocVersion.CURRENT, access: { spaceKey: spaceKey.toHex() }, objects: {}, links: {}, }); handle.change((doc) => { doc.objects = { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Legacy Doc' } }), }; }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(1); expect(result.objects[0].spaceId).toBe(await createIdFromSpaceKey(spaceKey)); }); test('prefers access.spaceId over the legacy spaceKey field', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const spaceKey = PublicKey.random(); const handle = await host.createDoc({ version: SpaceDocVersion.CURRENT, access: { spaceId, spaceKey: spaceKey.toHex() }, objects: {}, links: {}, }); handle.change((doc) => { doc.objects = { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'New Doc' } }), }; }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const result = await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); expect(result.objects).toHaveLength(1); expect(result.objects[0].spaceId).toBe(spaceId); }); test('a late-arriving old change lands in its own hour and is counted once', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const handle = await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'Original' } }), }); await host.flush(Context.default()); const dataSource = new AutomergeDataSource(host); const firstResult = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), [], { activity: true }), ); expect(firstResult.activity).toEqual([expect.objectContaining({ documentId: handle.documentId, full: true })]); invariant(firstResult.activity, 'activity requested via getChangedObjects options'); const firstChanges = firstResult.activity[0].changes; expect(firstChanges.length).toBeGreaterThan(0); const now = Date.now(); for (const change of firstChanges) { expect(Math.abs(change.time - now)).toBeLessThan(5_000); } const firstCursor = firstResult.cursors[0]; const OLD_MS = Date.now() - 30 * 24 * 3_600_000; const OLD_S = Math.floor(OLD_MS / 1000); handle.change( (doc: DatabaseDirectory) => { invariant(doc.objects, 'objects populated by createDatabaseDirectory'); // A string field is spliced character-by-character in this Automerge build and would not exercise `ops === 1`. doc.objects['obj-1'].data.count = 42; }, { time: OLD_S }, ); await host.flush(Context.default()); const cursorsAfterFirstCall: IndexCursor[] = [ { indexName: 'activity', spaceId: null, sourceName: 'automerge', resourceId: handle.documentId, cursor: firstCursor.cursor, }, ]; const secondResult = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), cursorsAfterFirstCall, { activity: true }), ); expect(secondResult.activity).toEqual([ { spaceId, documentId: handle.documentId, full: false, changes: [{ time: OLD_S * 1000, ops: 1 }] }, ]); const secondCursor = secondResult.cursors[0]; const cursorsAfterSecondCall: IndexCursor[] = [ { indexName: 'activity', spaceId: null, sourceName: 'automerge', resourceId: handle.documentId, cursor: secondCursor.cursor, }, ]; const thirdResult = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), cursorsAfterSecondCall, { activity: true }), ); expect(thirdResult.activity).toEqual([]); }); test('a branch document counted before its root was read is discarded once the root names it', async () => { const host = await setupAutomergeHost(); const spaceId = SpaceId.random(); const dataSource = new AutomergeDataSource(host); const toCursors = (result: { cursors: { resourceId: string | null; cursor: string | number }[] }): IndexCursor[] => result.cursors.map(({ resourceId, cursor }) => ({ indexName: 'activity', spaceId: null, sourceName: 'automerge', resourceId, cursor, })); const branch = await createDatabaseDirectory(host, spaceId, { 'obj-1': EntityStructure.makeObject({ type: TEST_TYPE, data: { title: 'On a branch' } }), }); await host.flush(Context.default()); const first = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), [], { activity: true }), ); expect(first.activity).toEqual([expect.objectContaining({ documentId: branch.documentId, full: true })]); invariant(first.activity, 'activity requested via getChangedObjects options'); expect(first.activity[0].changes.length).toBeGreaterThan(0); const root = await createDatabaseDirectory(host, spaceId, {}); root.change((doc: DatabaseDirectory) => { doc.branches = { 'obj-1': { feature: { members: { 'obj-1': branch.url } } } }; }); await host.flush(Context.default()); await EffectEx.runAndForwardErrors(dataSource.getChangedObjects(Context.default(), [])); const second = await EffectEx.runAndForwardErrors( dataSource.getChangedObjects(Context.default(), toCursors(first), { activity: true }), ); expect(second.activity).toContainEqual({ spaceId, documentId: branch.documentId, full: true, changes: [] }); expect(second.activity).toContainEqual(expect.objectContaining({ documentId: root.documentId })); }); });