// // Copyright 2023 DXOS.org // import * as A from '@automerge/automerge'; import { type DocumentId, type Heads, type PeerId, generateAutomergeUrl, parseAutomergeUrl, } from '@automerge/automerge-repo'; import { CommitId, SedimentreeId } from '@automerge/automerge-subduction'; import { describe, expect, onTestFinished, test } from 'vitest'; import { sleep } from '@dxos/async'; import { Context } from '@dxos/context'; import { createIdFromSpaceKey } from '@dxos/echo-protocol'; import { invariant } from '@dxos/invariant'; import { PublicKey, SpaceId } from '@dxos/keys'; import { range } from '@dxos/util'; import { createTestSqliteRuntime } from '../testing/index.ts'; import { TestReplicationNetwork } from '../testing/index.ts'; import { AutomergeHost, type RootDocumentSpaceKeyProvider, documentIdToSedimentreeIdHex } from './automerge-host.ts'; import { type EchoNetworkAdapter } from './echo-network-adapter.ts'; import { deriveCollectionIdFromSpaceId } from './space-collection.ts'; import { waitForEviction } from './subduction-test-utils.ts'; describe('AutomergeHost', () => { test('can create documents', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost(runtime); const handle = await host.createDoc(); handle.change((doc: any) => { doc.text = 'Hello world'; }); await host.flush(Context.default()); expect(handle.doc()!.text).toEqual('Hello world'); }); test('resolves a document space from collection membership without a loaded handle', async ({ expect }) => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost(runtime); // Regression: a document known to the space via the root's document list, but whose handle was // never created (eviction / lazy load), must resolve to its space rather than reading as "not // in any space" — the latter produced spurious share-policy (`authorizeFetch`) denials. const spaceId = SpaceId.random(); const { documentId: rootId } = parseAutomergeUrl(generateAutomergeUrl()); const { documentId } = parseAutomergeUrl(generateAutomergeUrl()); await host.updateLocalCollectionState(deriveCollectionIdFromSpaceId(spaceId, rootId), [documentId]); expect(await host.getContainingSpaceIdForDocument(documentId)).toEqual(spaceId); // A document in no registered collection (and with no loaded handle) stays unresolved. const { documentId: unknownId } = parseAutomergeUrl(generateAutomergeUrl()); expect(await host.getContainingSpaceIdForDocument(unknownId)).toBeNull(); // A non-space collection id must not throw out of the resolver and must not resolve. const { documentId: otherId } = parseAutomergeUrl(generateAutomergeUrl()); await host.updateLocalCollectionState('test-collection', [otherId]); expect(await host.getContainingSpaceIdForDocument(otherId)).toBeNull(); }); test('resolves a document space from the embedded root-doc space key when not in any collection', async ({ expect, }) => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); // Fallback path: a document in no local collection resolves its space via the loaded-handle / // root-doc space-key provider, then derives the space id via `createIdFromSpaceKey`. const spaceKey = PublicKey.random(); const { documentId } = parseAutomergeUrl(generateAutomergeUrl()); const host = await setupAutomergeHost(runtime, (id) => (id === documentId ? spaceKey : undefined)); expect(await host.getContainingSpaceIdForDocument(documentId)).toEqual(await createIdFromSpaceKey(spaceKey)); // A document the provider does not recognize (and in no collection) stays unresolved. const { documentId: unknownId } = parseAutomergeUrl(generateAutomergeUrl()); expect(await host.getContainingSpaceIdForDocument(unknownId)).toBeNull(); }); test('changes are preserved in storage', async () => { const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}.db`; const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(tmpPath); const host = await setupAutomergeHost(runtime1); const handle = await host.createDoc(); handle.change((doc: any) => { doc.text = 'Hello world'; }); const url = handle.url; await host.flush(Context.default()); await host.close(); await dispose1(); const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(tmpPath); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost(runtime2); const handle2 = await host2.loadDoc(Context.default(), url); invariant(handle2); await handle2.waitUntilReady(); expect(handle2.doc()!.text).toEqual('Hello world'); await host2.flush(Context.default()); }); test('load resolves when document is created from binary', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost(runtime); // Create a document to get its binary representation const document = A.from({ text: 'Hello world' }); const binary = A.save(document); const { documentId } = parseAutomergeUrl(generateAutomergeUrl()); // Start loading a non-existent document (should hang until created) const loadPromise = host.loadDoc(Context.default(), documentId); // Create the document from binary - this should resolve the load const createdHandle = await host.createDoc(binary, { preserveHistory: true, documentId }); // The load should now resolve const loadedHandle = await loadPromise; invariant(loadedHandle); expect(loadedHandle.doc()).toEqual(createdHandle.doc()); }); test('query single document heads', async () => { const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}.db`; const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(tmpPath); const host = await setupAutomergeHost(runtime1); const handle = await host.createDoc({ text: 'Hello world' }); const expectedHeads = A.getHeads(handle.doc()!); await host.flush(Context.default()); expect(await host.getHeads([handle.documentId])).toEqual([expectedHeads]); await host.close(); await dispose1(); // Simulate a restart. { const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(tmpPath); onTestFinished(() => dispose2()); const host = await setupAutomergeHost(runtime2); expect(await host.getHeads([handle.documentId])).toEqual([expectedHeads]); } }); test('query multiple document heads', async () => { const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}.db`; const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(tmpPath); const host = await setupAutomergeHost(runtime1); const handles = await Promise.all(range(2, () => host.createDoc({ text: 'Hello world' }))); const expectedHeads: (Heads | undefined)[] = handles.map((handle) => A.getHeads(handle.doc()!)); await host.flush(Context.default()); const ids = handles.map((handle) => handle.documentId); ids.splice(1, 0, 'non-existent-id' as DocumentId); expectedHeads.splice(1, 0, undefined); expect(await host.getHeads(ids)).toEqual(expectedHeads); await host.close(); await dispose1(); // Simulate a restart. { const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(tmpPath); onTestFinished(() => dispose2()); const host = await setupAutomergeHost(runtime2); expect(await host.getHeads(ids)).toEqual(expectedHeads); } }); test('loadDoc respects fetchFromNetwork', { timeout: 10_000 }, async () => { const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost(runtime1); const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost(runtime2); const handle = await host2.createDoc({ text: 'Hello world' }); await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); // (1) fetchFromNetwork=false on a doc not yet on disk: returns null immediately // without waiting on the network, even though host2 has it. expect( await host1.loadDoc(Context.default(), handle.documentId, { fetchFromNetwork: false, timeout: 1_000 }), ).toBeNull(); // (2) fetchFromNetwork=true: host1 announces, host2 sends bytes, doc syncs. const loaded = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { fetchFromNetwork: true, timeout: 5_000, }); invariant(loaded); expect(loaded.doc()!.text).toEqual('Hello world'); // (3) Now that host1 has the doc on disk, fetchFromNetwork=false succeeds. await host1.flush(Context.default()); const localOnly = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { fetchFromNetwork: false, }); invariant(localOnly); expect(localOnly.doc()!.text).toEqual('Hello world'); await host1.close(); await host2.close(); await network.close(); }); test('loadDoc with fetchFromNetwork=false does not announce when doc is in storage', { timeout: 5_000 }, async () => { // Pre-populate host1's storage with the doc, then close so that the // host1 we test with has the doc on disk but did not author it (i.e. // it's not in `_createdDocuments` and won't auto-announce). const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}.db`; let documentId: DocumentId; { const { runtime, dispose } = createTestSqliteRuntime(tmpPath); const provider = await setupAutomergeHost(runtime); const handle = await provider.createDoc({ text: 'Hello world' }); documentId = handle.documentId; await provider.flush(Context.default()); await provider.close(); await dispose(); } const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(tmpPath); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost(runtime1); const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost(runtime2); const network = await new TestReplicationNetwork().open(); await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); // Spy on host2's incoming-request event — fires when any peer sends // an automerge `request` message for a doc to host2. If host1 ever // announced wanting `documentId`, this would trigger. const requests: DocumentId[] = []; const adapter = (host2 as unknown as { _echoNetworkAdapter: EchoNetworkAdapter })._echoNetworkAdapter; adapter.documentRequested.on(({ documentId: requestedId }) => { requests.push(requestedId); }); // Load the doc that's already on disk; should resolve from storage. const loaded = await host1.loadDoc<{ text: string }>(Context.default(), documentId, { fetchFromNetwork: false, }); invariant(loaded); expect(loaded.doc()!.text).toEqual('Hello world'); // Give any in-flight share-policy debounce a chance to fire. await sleep(100); expect(requests).not.toContain(documentId); await host1.close(); await host2.close(); await network.close(); }); test('collection synchronization', { timeout: 30_000 }, async () => { const NUM_DOCUMENTS = 10; const { runtime: runtime1, dispose: dispose1 } = createTestSqliteRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost(runtime1); const { runtime: runtime2, dispose: dispose2 } = createTestSqliteRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost(runtime2); const documentIds: DocumentId[] = []; for (const i of range(NUM_DOCUMENTS)) { const handle = await host2.createDoc({ docIndex: i }); documentIds.push(handle.documentId); } await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); const collectionId = 'test-collection'; await host1.updateLocalCollectionState(collectionId, documentIds); await host2.updateLocalCollectionState(collectionId, documentIds); for (const documentId of documentIds) { await expect .poll(() => host1.getHeads([documentId]), { timeout: 20_000 }) .toEqual(await host2.getHeads([documentId])); } await host1.close(); await host2.close(); await network.close(); }); // A document that is `ready` locally but whose heads disagree with a peer's is the one case // neither Subduction retry path covers: `findWithProgress` resolves from the existing query, and // `shareConfigChanged()` skips entries whose last sync succeeded. `_handleCollectionSync` is the // only place that sees the divergence, so it has to be the place that acts on it. test('a diverged ready document is resynced once per head pair', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const handle = await host.createDoc({ value: 1 }); const { documentId } = handle; await host.flush(Context.default()); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); const resynced: DocumentId[] = []; const resyncDocument = host.resyncDocument.bind(host); host.resyncDocument = (id) => { resynced.push(id); resyncDocument(id); }; // A head the local document cannot overlap, so the diff reports `different` rather than // `missingOnLocal`/`missingOnRemote` — the shape that used to fall through to nothing. const peerId = 'test-peer' as PeerId; const remoteState = { documents: { [documentId]: ['0'.repeat(64)] } }; const synchronizer = (host as any)._collectionSynchronizer; synchronizer.onRemoteStateReceived(collectionId, peerId, remoteState); await expect.poll(() => resynced.length, { timeout: 2_000 }).toEqual(1); // A peer repeating an unchanged-but-still-diverged state is deliberately not deduped by // `onRemoteStateReceived` (that is what keeps the diff loop alive), so the guard against // re-arming the heal backoff has to live on this side. synchronizer.onRemoteStateReceived(collectionId, peerId, remoteState); await sleep(500); expect(resynced).toEqual([documentId]); // Clearing the collection drops its budget, so registering it again earns a fresh resync rather // than being suppressed by the stale entry. await host.clearLocalCollectionState(collectionId); await host.updateLocalCollectionState(collectionId, [documentId]); synchronizer.onRemoteStateReceived(collectionId, peerId, remoteState); await expect.poll(() => resynced.length, { timeout: 2_000 }).toEqual(2); // A removed document never converges, so its retry budget has to go with it. const resyncHeads: Map = (host as any)._divergedResyncHeads; expect([...resyncHeads.values()].some((entry) => entry.documentId === documentId)).toBe(true); await host.removeDocument(documentId); expect([...resyncHeads.values()].some((entry) => entry.documentId === documentId)).toBe(false); }); test('a resident document whose heads overlap is synced, and resynced once for a remote head it lacks', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const handle = await host.createDoc({ value: 1 }); const { documentId } = handle; await host.flush(Context.default()); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); const [localHead] = (await host.getHeads([documentId]))[0] ?? []; const [missingHead] = A.getHeads(A.from({ elsewhere: true })); const resynced: DocumentId[] = []; const resyncDocument = host.resyncDocument.bind(host); host.resyncDocument = (id) => { resynced.push(id); resyncDocument(id); }; const synchronizer = host['_collectionSynchronizer']; const peerId = 'test-peer' as PeerId; const advertise = async (heads: string[]) => { synchronizer.onRemoteStateReceived(collectionId, peerId, { documents: { [documentId]: heads } }); await host['_handleCollectionSync'](Context.default(), collectionId, peerId); }; await advertise([localHead, missingHead]); expect((await host.getCollectionSyncState(collectionId)).peers?.[0]?.differentDocuments).toEqual(0); expect(resynced).toEqual([documentId]); // A malformed head is ignored rather than fatal. await advertise([localHead, 'not-a-hash']); expect((await host.getCollectionSyncState(collectionId)).peers?.[0]?.differentDocuments).toEqual(0); expect(resynced).toEqual([documentId]); }); test('an evicted document is loaded for an overlapping remote head it has not confirmed', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true, residency: { evictionDelay: 0, minResidentDocuments: 0 }, }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const handle = await host.createDoc({ value: 1 }); const { documentId } = handle; const [ancestorHead] = A.getHeads(handle.doc()); handle.change((doc: any) => { doc.value = 2; }); await host.flush(Context.default()); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); const [localHead] = (await host.getHeads([documentId]))[0] ?? []; const [missingHead] = A.getHeads(A.from({ elsewhere: true })); const synchronizer = host['_collectionSynchronizer']; const peerId = 'test-peer' as PeerId; const differentDocuments = async () => (await host.getCollectionSyncState(collectionId)).peers?.[0]?.differentDocuments; let loads = 0; const leaseUntilSettled = host['_leaseUntilSettled']; host['_leaseUntilSettled'] = (id: DocumentId) => { loads += id === documentId ? 1 : 0; leaseUntilSettled.call(host, id); }; const loadsAfter = async (heads: string[]) => { const before = loads; synchronizer.onRemoteStateReceived(collectionId, peerId, { documents: { [documentId]: heads } }); await host['_handleCollectionSync'](Context.default(), collectionId, peerId); return loads - before; }; // Resident: checked and confirmed. expect(await loadsAfter([localHead, ancestorHead])).toEqual(0); handle[Symbol.dispose](); await waitForEviction(expect, host, documentId); // Evicted: only a confirmed head counts as present, and the heads overlap either way. expect(await loadsAfter([localHead, ancestorHead])).toEqual(0); expect(await loadsAfter([localHead, missingHead])).toEqual(1); expect(await differentDocuments()).toEqual(0); }); test('after a restart a remote head is confirmed without a load only when storage holds its whole history', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const openHost = async () => { const host = new AutomergeHost({ runtime, useSubduction: true, residency: { evictionDelay: 0, minResidentDocuments: 0 }, }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); return host; }; const writer = await openHost(); const handle = await writer.createDoc({ value: 1 }); const { documentId } = handle; const [ancestorHead] = A.getHeads(handle.doc()); handle.change((doc: any) => { doc.value = 2; }); const orphanParent = A.change(A.clone(handle.doc()), (doc: any) => { doc.value = 3; }); const orphan = A.change(A.clone(orphanParent), (doc: any) => { doc.value = 4; }); const [orphanHead] = A.getHeads(orphan); handle[Symbol.dispose](); await waitForEviction(expect, writer, documentId); await ( await writer.subduction ).storeCommit( SedimentreeId.fromBytes(Buffer.from(documentIdToSedimentreeIdHex(documentId), 'hex')), CommitId.fromHexString(orphanHead), A.getHeads(orphanParent).map((head) => CommitId.fromHexString(head)), A.getLastLocalChange(orphan)!, ); await writer.flush(Context.default()); await writer.close(); const host = await openHost(); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); const [localHead] = (await host.getHeads([documentId]))[0] ?? []; const [missingHead] = A.getHeads(A.from({ elsewhere: true })); const synchronizer = host['_collectionSynchronizer']; const peerId = 'test-peer' as PeerId; let loads = 0; const leaseUntilSettled = host['_leaseUntilSettled']; host['_leaseUntilSettled'] = (id: DocumentId) => { loads += id === documentId ? 1 : 0; leaseUntilSettled.call(host, id); }; const loadsAfter = async (heads: string[]) => { const before = loads; synchronizer.onRemoteStateReceived(collectionId, peerId, { documents: { [documentId]: heads } }); await host['_handleCollectionSync'](Context.default(), collectionId, peerId); return loads - before; }; expect(await loadsAfter([localHead, ancestorHead])).toEqual(0); expect(await loadsAfter([localHead, orphanHead])).toEqual(1); expect(await loadsAfter([localHead, missingHead])).toEqual(1); }); test('an evicted document lacking a change stays synced and is loaded once per head pair and connection', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true, residency: { evictionDelay: 0, minResidentDocuments: 0 }, }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const handle = await host.createDoc({ value: 1 }); const { documentId } = handle; await host.flush(Context.default()); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); const [localHead] = (await host.getHeads([documentId]))[0] ?? []; const [missingHead] = A.getHeads(A.from({ elsewhere: true })); const [otherMissingHead] = A.getHeads(A.from({ elsewhere: false })); const synchronizer = host['_collectionSynchronizer']; const peerId = 'test-peer' as PeerId; const differentDocuments = async () => (await host.getCollectionSyncState(collectionId)).peers?.[0]?.differentDocuments; let loads = 0; const leaseUntilSettled = host['_leaseUntilSettled']; host['_leaseUntilSettled'] = (id: DocumentId) => { loads += id === documentId ? 1 : 0; leaseUntilSettled.call(host, id); }; // A scheduled pass may spend the budget first; the count is the same either way. const loadsAfter = async (change: () => void) => { const before = loads; change(); await host['_handleCollectionSync'](Context.default(), collectionId, peerId); return loads - before; }; const advertise = (heads: string[]) => () => synchronizer.onRemoteStateReceived(collectionId, peerId, { documents: { [documentId]: heads } }); expect(await loadsAfter(advertise([localHead, missingHead]))).toEqual(1); handle[Symbol.dispose](); await waitForEviction(expect, host, documentId); expect(await differentDocuments()).toEqual(0); expect(await loadsAfter(() => {})).toEqual(0); expect(await loadsAfter(advertise([localHead, otherMissingHead]))).toEqual(1); await waitForEviction(expect, host, documentId); expect(await loadsAfter(() => {})).toEqual(0); // The peer resends its state after reconnecting. expect( await loadsAfter(() => { host['_onPeerDisconnected'](peerId); advertise([localHead, otherMissingHead])(); }), ).toEqual(1); }); test('data stored for a document no collection references does not fault it in, across a restart', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const residency = { evictionDelay: 0, minResidentDocuments: 0 }; const collectionId = 'test-collection'; const before = new AutomergeHost({ runtime, useSubduction: true, residency }); await before.open(); const removed = await before.createDoc({ value: 1 }); const kept = await before.createDoc({ value: 2 }); await before.flush(Context.default()); removed[Symbol.dispose](); kept[Symbol.dispose](); // Garbage collection removes a document from every collection. await before.updateLocalCollectionState(collectionId, [kept.documentId]); await before.removeDocument(removed.documentId); await before.close(); const host = new AutomergeHost({ runtime, useSubduction: true, residency }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); await host.updateLocalCollectionState(collectionId, [kept.documentId]); // The listener is synchronous, so both outcomes are final here. const repo = host['_repo']; repo.emit('subduction-detached-data', { documentId: removed.documentId }); repo.emit('subduction-detached-data', { documentId: kept.documentId }); expect(host.loadedDocumentIds).toContain(kept.documentId); expect(host.loadedDocumentIds).not.toContain(removed.documentId); }); // The share-policy kick walks every resident document and Subduction ignores it for a diverged one, // so an evicted diverged document must not re-arm it on every diff pass. test('a diverged evicted document does not kick the share policy', async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true, residency: { evictionDelay: 0, minResidentDocuments: 0 }, }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const handle = await host.createDoc({ value: 1 }); const { documentId } = handle; await host.flush(Context.default()); const collectionId = 'test-collection'; await host.updateLocalCollectionState(collectionId, [documentId]); handle[Symbol.dispose](); await waitForEviction(expect, host, documentId); const task = (host as any)._sharePolicyChangedTask; const schedule = task.schedule.bind(task); let kicks = 0; task.schedule = () => { kicks++; schedule(); }; // The pass faults the document back in after deciding on the kick. const leaseUntilSettled = (host as any)._leaseUntilSettled.bind(host); const leased: DocumentId[] = []; (host as any)._leaseUntilSettled = (id: DocumentId) => { leased.push(id); leaseUntilSettled(id); }; const synchronizer = (host as any)._collectionSynchronizer; synchronizer.onRemoteStateReceived(collectionId, 'test-peer' as PeerId, { documents: { [documentId]: ['0'.repeat(64)] }, }); await expect.poll(() => leased, { timeout: 2_000 }).toContain(documentId); expect(kicks).toBe(0); }); // `DeferredTask` clears its scheduled flag before running the callback, so a throttle that waited // inside the callback queued a second run for kicks it had already covered — and that run fanned // out again a full interval later. test('a burst of share-policy kicks inside the throttle window fans out once', { timeout: 15_000 }, async () => { const { runtime, dispose } = createTestSqliteRuntime(); onTestFinished(() => dispose()); const host = new AutomergeHost({ runtime, useSubduction: true }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const repo = (host as any)._repo; const shareConfigChanged = repo.shareConfigChanged.bind(repo); let kicks = 0; repo.shareConfigChanged = () => { kicks++; shareConfigChanged(); }; // Inside a throttle window, as right after a previous kick. Wide, so the first run parks even on a // loaded runner: one that reached it only after the deadline would kick at once, and the burst // below would then legitimately cause a second kick. (host as any)._sharePolicyKickNextAllowedAt = Date.now() + 3_000; const task = (host as any)._sharePolicyChangedTask; task.schedule(); await expect.poll(() => (host as any)._sharePolicyKickParked, { timeout: 2_500 }).toBe(true); // Issued while the first run is parked, which is exactly what the parked kick covers. task.schedule(); task.schedule(); await expect.poll(() => kicks, { timeout: 10_000 }).toBe(1); // A second fan-out would land one minimum interval after the first. await sleep(1_500); expect(kicks).toBe(1); }); }); type RuntimeArg = ReturnType['runtime']; const setupAutomergeHost = async (runtime: RuntimeArg, getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider) => { const host = new AutomergeHost({ runtime, getSpaceKeyByRootDocumentId }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); return host; };