// // Copyright 2026 DXOS.org // import { getHeads } from '@automerge/automerge'; import * as Automerge from '@automerge/automerge'; import { type DocumentId, type Heads, type SubductionPeerBinding, generateAutomergeUrl, parseAutomergeUrl, } from '@automerge/automerge-repo'; import { describe, onTestFinished, test } from 'vitest'; import { sleep } from '@dxos/async'; import { Context } from '@dxos/context'; import { type CollectionId, createIdFromSpaceKey } from '@dxos/echo-protocol'; import * as RuntimeProvider from '@dxos/effect/RuntimeProvider'; import { invariant } from '@dxos/invariant'; import { PublicKey } from '@dxos/keys'; import { TestBuilder as TeleportBuilder, TestPeer as TeleportPeer } from '@dxos/teleport/testing'; import { range } from '@dxos/util'; import { TestReplicationNetwork, createTestSqliteRuntime } from '../testing/index.ts'; import { AutomergeHost } from './automerge-host.ts'; import { MeshEchoReplicator } from './mesh-echo-replicator.ts'; import { SqliteStorageAdapter } from './sqlite-storage-adapter.ts'; import { deleteSubductionRemoteHeads } from './subduction-migrations/0001_delete_remote_heads.ts'; import { NO_TRAFFIC_WINDOW_MS, SYNC_WINDOW_MS, createDenyGate, waitForDoc, waitForEviction, waitForHostHeads, } from './subduction-test-utils.ts'; describe('AutomergeHost with Subduction', () => { test('can create documents', async ({ expect }) => { const { runtime, dispose } = createRuntime(); 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('changes are preserved in storage', async ({ expect }) => { const { runtime, dispose } = createRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost({ runtime }); 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(); const host2 = await setupAutomergeHost({ runtime }); 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('a write after eviction and re-lease is persisted', async ({ expect }) => { // Eviction unloads a document that may be leased again later: the fork's subduction source has // to re-attach to the new handle, or every subsequent write is dropped on the floor. const { runtime, dispose } = createRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost({ runtime }); const created = await host.createDoc({ text: 'first' }); const documentId = created.documentId; const url = created.url; await host.flush(Context.default()); created[Symbol.dispose](); await waitForEviction(expect, host, documentId); using reacquired = host.acquireDoc(documentId); await reacquired.waitUntilReady(); reacquired.change((doc: any) => { doc.text = 'second'; }); await host.flush(Context.default()); await host.close(); const reopened = await setupAutomergeHost({ runtime }); using loaded = (await reopened.loadDoc(Context.default(), url))!; await loaded.waitUntilReady(); expect(loaded.doc()?.text).toEqual('second'); }); test('a write after eviction and re-lease reaches a peer', async ({ expect }) => { // The subduction source keeps a per-document record bound to the handle it attached to; if // eviction leaves that record in place, writes through the re-leased document are never synced. const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const created = await host1.createDoc({ text: 'first' }); const documentId = created.documentId; await host1.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); using mirrored = (await host2.loadDoc(Context.default(), documentId))!; await expect.poll(() => mirrored.doc()?.text, { timeout: SYNC_WINDOW_MS }).toEqual('first'); created[Symbol.dispose](); await waitForEviction(expect, host1, documentId); using reacquired = host1.acquireDoc(documentId); await reacquired.waitUntilReady(); reacquired.change((doc: any) => { doc.text = 'second'; }); await host1.flush(Context.default()); await expect.poll(() => mirrored.doc()?.text, { timeout: SYNC_WINDOW_MS }).toEqual('second'); } finally { await host1.close(); await host2.close(); await network.close(); } }); test('a change that arrives while the document is evicted is applied', async ({ expect }) => { const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); using created = await host1.createDoc({ text: 'first' }); const documentId = created.documentId; await host1.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); // Pushes load only documents a local collection lists. await host2.updateLocalCollectionState('test-collection', [documentId]); const mirrored = await host2.loadDoc(Context.default(), documentId); invariant(mirrored); await waitForDoc(mirrored, (doc) => doc?.text === 'first'); mirrored[Symbol.dispose](); await waitForEviction(expect, host2, documentId); created.change((doc: any) => { doc.text = 'second'; }); await host1.flush(Context.default()); const [expected] = await host1.getHeads([documentId]); invariant(expected); await waitForHostHeads(host2, documentId, expected); } finally { await host1.close(); await host2.close(); await network.close(); } }); test( 'a peer not holding a document catches up when its sync round outlasts the eviction delay', { timeout: 4 * SYNC_WINDOW_MS, }, async ({ expect }) => { // Faulted in to catch up and ready at once from its older local copy, the document was evicted mid-round. const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const writer = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const reader = await setupAutomergeHost({ runtime: rt2.runtime, residency: { evictionDelay: 50, minResidentDocuments: 0 }, }); const created = await writer.createDoc<{ edit: number }>({ edit: 0 }); const documentId = created.documentId; await writer.flush(Context.default()); const writerHeads = () => { const doc = created.doc(); invariant(doc, 'The writer holds the document.'); return getHeads(doc); }; // Each message outlasts the reader's idle delay, so every sync round does too. const network = await new TestReplicationNetwork({ latency: 150 }).open(); try { await writer.addReplicator(Context.default(), await network.createReplicator()); await reader.addReplicator(Context.default(), await network.createReplicator()); const collectionId = 'test-collection'; await writer.updateLocalCollectionState(collectionId, [documentId]); await reader.updateLocalCollectionState(collectionId, [documentId]); await expect .poll(async () => (await reader.getHeads([documentId]))[0], { timeout: SYNC_WINDOW_MS }) .toEqual(writerHeads()); await waitForEviction(expect, reader, documentId); created.change((doc) => { doc.edit = 1; }); await writer.flush(Context.default()); await expect .poll(async () => (await reader.getHeads([documentId]))[0], { timeout: SYNC_WINDOW_MS }) .toEqual(writerHeads()); } finally { await writer.close(); await reader.close(); await network.close(); } }, ); test('sync works both ways after the stored remote heads are deleted', async ({ expect }) => { // The recovery page's Repair action deletes these records. They only cache what a peer last reported, so a // host restarted without them must still pull and push, and record the peer's heads again. const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const network = await new TestReplicationNetwork().open(); const connectHost1 = async () => { const host = await setupAutomergeHost({ runtime: rt1.runtime }); await host.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); return host; }; let host1 = await connectHost1(); try { await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); const created = await host1.createDoc({ text: 'first' }); const documentId = created.documentId; await host1.flush(Context.default()); using mirrored = (await host2.loadDoc(Context.default(), documentId))!; await expect.poll(() => mirrored.doc()?.text, { timeout: SYNC_WINDOW_MS }).toEqual('first'); await expect.poll(() => countStoredRemoteHeads(rt1.runtime), { timeout: SYNC_WINDOW_MS }).toBeGreaterThan(0); created[Symbol.dispose](); await host1.close(); const { deleted } = await RuntimeProvider.runPromise(rt1.runtime)(deleteSubductionRemoteHeads()); expect(deleted).toBeGreaterThan(0); expect(await countStoredRemoteHeads(rt1.runtime)).toBe(0); host1 = await connectHost1(); using reopened = (await host1.loadDoc(Context.default(), documentId))!; await reopened.waitUntilReady(); expect(reopened.doc()!.text).toEqual('first'); mirrored.change((doc: any) => { doc.pulled = true; }); await expect.poll(() => reopened.doc()?.pulled, { timeout: SYNC_WINDOW_MS }).toBe(true); reopened.change((doc: any) => { doc.pushed = true; }); await expect.poll(() => mirrored.doc()?.pushed, { timeout: SYNC_WINDOW_MS }).toBe(true); await expect.poll(() => countStoredRemoteHeads(rt1.runtime), { timeout: SYNC_WINDOW_MS }).toBeGreaterThan(0); } finally { await host1.close(); await host2.close(); await network.close(); } }); test('load resolves when document is created from binary', async ({ expect }) => { const { runtime, dispose } = createRuntime(); onTestFinished(() => dispose()); const host = await setupAutomergeHost({ runtime }); const document = Automerge.from({ text: 'Hello world' }); const binary = Automerge.save(document); const { documentId } = parseAutomergeUrl(generateAutomergeUrl()); const loadPromise = host.loadDoc(Context.default(), documentId); const createdHandle = await host.createDoc(binary, { preserveHistory: true, documentId }); const loadedHandle = await loadPromise; invariant(loadedHandle); expect(loadedHandle.doc()).toEqual(createdHandle.doc()); }); test('query single document heads', async ({ expect }) => { const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}`; const { runtime, dispose } = createRuntime(tmpPath); const host = await setupAutomergeHost({ runtime }); const handle = await host.createDoc({ text: 'Hello world' }); const expectedHeads = getHeads(handle.doc()!); await host.flush(Context.default()); expect(await host.getHeads([handle.documentId])).toEqual([expectedHeads]); await host.close(); await dispose(); { const { runtime: runtime2, dispose: dispose2 } = createRuntime(tmpPath); onTestFinished(() => dispose2()); const host = await setupAutomergeHost({ runtime: runtime2 }); expect(await host.getHeads([handle.documentId])).toEqual([expectedHeads]); } }); test('query multiple document heads', async ({ expect }) => { const tmpPath = `/tmp/dxos-${PublicKey.random().toHex()}`; const { runtime, dispose } = createRuntime(tmpPath); const host = await setupAutomergeHost({ runtime }); const handles = await Promise.all(range(2, () => host.createDoc({ text: 'Hello world' }))); const expectedHeads: (Heads | undefined)[] = handles.map((handle) => 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 dispose(); { const { runtime: runtime2, dispose: dispose2 } = createRuntime(tmpPath); onTestFinished(() => dispose2()); const host = await setupAutomergeHost({ runtime: runtime2 }); expect(await host.getHeads(ids)).toEqual(expectedHeads); } }); test('loads remote document over replication network', async ({ expect }) => { const { runtime: runtime1, dispose: dispose1 } = createRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost({ runtime: runtime1 }); const { runtime: runtime2, dispose: dispose2 } = createRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost({ runtime: runtime2 }); const handle = await host2.createDoc({ text: 'Hello from Subduction' }); await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); const loaded = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 1_000 }); invariant(loaded); expect(loaded.doc()!.text).toEqual('Hello from Subduction'); } finally { await host1.close(); await host2.close(); await network.close(); } }); // Sequential close (one host fully shut down before the other starts) // exercises the same teardown path as the existing // `loads remote document over replication network` test and is included as a // baseline for the concurrent-close case below. test('sequential close after sync does not hang', async ({ expect }) => { const { runtime: runtime1, dispose: dispose1 } = createRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost({ runtime: runtime1 }); const { runtime: runtime2, dispose: dispose2 } = createRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost({ runtime: runtime2 }); const handle = await host2.createDoc({ text: 'Hello from Subduction' }); 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 loaded = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 1_000 }); invariant(loaded); expect(loaded.doc()!.text).toEqual('Hello from Subduction'); await host1.close(); await host2.close(); await network.close(); }); // Reproduces a hang during teardown observed in client-level invitation tests: // when two hosts have synced over the mesh-style replicator and then close // concurrently, one side's `_close` (specifically `_repo.flush()`) never // returns. The first close to arrive tears down its side of the connection // (cancels readers / aborts writers); the second host then enters `_close` // and gets stuck draining subduction state that depends on the now-dead // peer. test('concurrent close after sync does not hang', async ({ expect }) => { const { runtime: runtime1, dispose: dispose1 } = createRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost({ runtime: runtime1 }); const { runtime: runtime2, dispose: dispose2 } = createRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost({ runtime: runtime2 }); const handle = await host2.createDoc({ text: 'Hello from Subduction' }); 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 loaded = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 1_000 }); invariant(loaded); expect(loaded.doc()!.text).toEqual('Hello from Subduction'); await Promise.all([host1.close(), host2.close()]); await network.close(); }); test('collection synchronization', async ({ expect }) => { const NUM_DOCUMENTS = 10; const { runtime: runtime1, dispose: dispose1 } = createRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost({ runtime: runtime1 }); const { runtime: runtime2, dispose: dispose2 } = createRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost({ runtime: 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(); try { await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); const collectionId = 'test-collection'; const collectionUpdates: CollectionId[] = []; const unsubscribe = host1.collectionStateUpdated.on(({ collectionId }) => { collectionUpdates.push(collectionId); }); await host1.updateLocalCollectionState(collectionId, documentIds); await host2.updateLocalCollectionState(collectionId, documentIds); for (const documentId of documentIds) { await expect .poll(() => host1.getHeads([documentId]), { timeout: 1_000 }) .toEqual(await host2.getHeads([documentId])); } // collectionStateUpdated fires whenever host1 observes a `collection-state` from host2 // (see {@link CollectionSynchronizer.peerCollectionStateUpdated}). At least one event must // arrive for the heads to have converged via the collection-sync path rather than // raw Subduction byte transport. expect(collectionUpdates).toContain(collectionId as CollectionId); unsubscribe(); } finally { await host1.close(); await host2.close(); await network.close(); } }); describe('subductionPolicy gates host-to-host replication', () => { // Two hosts where the holder advertises the doc; the fetcher should receive it. // Mirrors the "loads remote document over replication network" baseline but // explicitly exercises `_subductionPolicy.authorizeFetch` via the per-connection // `shouldAdvertise` predicate. test('authorized holder allows fetcher', async ({ expect }) => { const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const handle = await host2.createDoc({ text: 'authorized' }); await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); const loaded = await host1.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 1_000 }); invariant(loaded); expect(loaded.doc()!.text).toEqual('authorized'); } finally { await host1.close(); await host2.close(); await network.close(); } }); // Holder's `shouldAdvertise` returns false → `_subductionPolicy.authorizeFetch` // on the holder rejects the fetcher's request → fetcher's query never reaches // `'ready'` and the local doc stays empty. test('unauthorized holder blocks fetcher (authorizeFetch denial)', async ({ expect }) => { const gate = createDenyGate(); const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const handle = await host2.createDoc({ text: 'should-not-fetch' }); await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); // host2 (holder) refuses to advertise. await host2.addReplicator( Context.default(), await network.createReplicator({ shouldAdvertise: () => gate.refuse() }), ); // Don't await `loadDoc` (it would hang). Probe via findWithProgress and assert no transition to 'ready'. const progress = host1.acquireDoc<{ text: string }>(handle.documentId); // Wait for the holder to actually refuse to advertise, not for a span in which it might. await gate.waitForDenial(); expect(progress.state).to.not.equal('ready'); expect(progress.doc()?.text).to.be.undefined; } finally { await host1.close(); await host2.close(); await network.close(); } }); // Flip the holder's `shouldAdvertise` from false to true and kick `shareConfigChanged()` // via the host (e.g. by calling `createDoc` which now schedules the task in both modes). // Per SKILL doc, `shareConfigChanged()` is the documented recovery hatch for // `authorizeFetch`-denied entries. test('shareConfigChanged() recovers after authorizeFetch denial flips to allow', async ({ expect }) => { const gate = createDenyGate(); const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const handle = await host2.createDoc({ text: 'recover-me' }); await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { const host1Replicator = await network.createReplicator({ shouldAdvertise: () => true }); const host2Replicator = await network.createReplicator({ shouldAdvertise: () => gate.refuse() }); await host1.addReplicator(Context.default(), host1Replicator); await host2.addReplicator(Context.default(), host2Replicator); const progress = host1.acquireDoc<{ text: string }>(handle.documentId); // Wait for the holder to actually refuse to advertise, not for a span in which it might. await gate.waitForDenial(); expect(progress.state).to.not.equal('ready'); // Flip the holder to allow, then drive a no-op commit on the holder. // Creating a fresh doc on host2 schedules `_sharePolicyChangedTask`, which // calls `_repo.shareConfigChanged()` on host2 — the documented recovery // hatch for `authorizeFetch`-denied entries. host2Replicator.shouldAdvertise = () => true; await host2.createDoc({ kick: true }); await expect.poll(() => progress.state, { timeout: SYNC_WINDOW_MS }).toEqual('ready'); expect(progress.doc()?.text).toEqual('recover-me'); } finally { await host1.close(); await host2.close(); await network.close(); } }); // Regression test for the patched `Repo.on('subduction-peer-bound', ...)` event // (mirrors upstream automerge/automerge-repo#635). Subduction's discovery handshake // produces a verified peer id on the responder side; in our test topology (both // hosts use `role: 'connect'`) at least one side observes the binding. We assert // the binding fields rather than count of events: the responder's binding must // carry the connector's repo PeerId and a distinct subduction PeerId. test('subduction-peer-bound event surfaces verified peer ids', async ({ expect }) => { const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); // The Subduction handshake only triggers when there is data to sync. Create a // doc on host2 before connecting so the adapter-connect flow runs end-to-end. await host2.createDoc({ text: 'binding-fixture' }); await host2.flush(Context.default()); const bindings: Array<{ side: 'host1' | 'host2'; binding: SubductionPeerBinding }> = []; ((host1 as any)._repo as any).on('subduction-peer-bound', (b: SubductionPeerBinding) => bindings.push({ side: 'host1', binding: b }), ); ((host2 as any)._repo as any).on('subduction-peer-bound', (b: SubductionPeerBinding) => bindings.push({ side: 'host2', binding: b }), ); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); await expect.poll(() => bindings.length, { timeout: 3_000 }).toBeGreaterThan(0); for (const { side, binding } of bindings) { invariant('repoPeerId' in binding, 'expected adapter binding'); // repoPeerId on side X should match the OTHER host's repo peerId. const expectedRemote = side === 'host1' ? host2.peerId : host1.peerId; expect(binding.repoPeerId).toEqual(expectedRemote); // The subduction PeerId is the verified signer Ed25519 pubkey hex — disjoint // from the repo PeerId (which is the `host-` label). expect(binding.subductionPeerId.toString()).not.toEqual(binding.repoPeerId); } } finally { await host1.close(); await host2.close(); await network.close(); } }); }); // Characterization of `_subductionPolicy` recovery behavior introduced by // PR 11351 — relevant to the production sync-divergence investigation. // // Setup: both hosts have the same documents with DIVERGENT commits (each // side has one local commit the other lacks), mirroring production state // where the sync diagnostic reports `differentDocuments: N` and // `localDocumentCount === remoteDocumentCount`. // // FINDING: with `AutomergeHost.useSubduction: true`, even when one side's // policy denies BOTH `authorizeFetch` and `authorizePut` during the // initial subduction sync round (confirmed via subduction_core WARNs // `policy denied: authorizePut denied by client share policy`), flipping // the policy to allow recovers replication in seconds on `AutomergeHost`'s // own machinery — no fresh commit and no `shareConfigChanged()` from the // test — PROVIDED the scope change is signalled. // // CORRECTION: an earlier reading of this test had recovery needing no // signal at all. It does. `_sharePolicyChangedTask` is scheduled by // `onConnectionOpen`, `onConnectionAuthScopeChanged` and `documentRequested` // only; a policy flip that signals none of them recovers just when a heal // retry happens to request a document, which is why the unsignalled version // failed at every window from 10s to 70s. Production always pairs a policy // change with `onConnectionAuthScopeChanged` (e.g. // `MeshEchoReplicator.authorizeDevice`), so the test now does too. // // This contradicts the raw-Repo F1 test in // `automerge-repo-subduction.test.ts` ("authorizePut deny → allow needs // a fresh holder commit to recover"), suggesting that the // `AutomergeHost` wrapper papers over the raw bridge's recovery gap. // // Implication for the production sync bug: a transient policy denial // during initial sync does NOT explain a persistent multi-second // divergence under `AutomergeHost`. The production bug must have a // different root cause. describe('initial-sync policy denial: recovery characterization', () => { const NUM_DOCUMENTS = 5; const createDivergentDocs = async (host1: AutomergeHost, host2: AutomergeHost): Promise => { const documentIds: DocumentId[] = []; for (const i of range(NUM_DOCUMENTS)) { const initial = Automerge.from({ docIndex: i, version: 0 }); const binary = Automerge.save(initial); const { documentId } = parseAutomergeUrl(generateAutomergeUrl()); const h1 = await host1.createDoc(binary, { documentId, preserveHistory: true }); const h2 = await host2.createDoc(binary, { documentId, preserveHistory: true }); h1.change((doc: any) => { doc.fromHost1 = true; }); h2.change((doc: any) => { doc.fromHost2 = true; }); documentIds.push(documentId); } await host1.flush(Context.default()); await host2.flush(Context.default()); return documentIds; }; const allConverged = async (host1: AutomergeHost, host2: AutomergeHost, ids: DocumentId[]) => { for (const id of ids) { const h1 = [...((await host1.getHeads([id]))[0] ?? [])].sort(); const h2 = [...((await host2.getHeads([id]))[0] ?? [])].sort(); if (h1.length !== h2.length || h1.some((h, i) => h !== h2[i])) { return false; } } return true; }; test('deny→allow flip recovers via AutomergeHost machinery once the scope change is signalled', async ({ expect, }) => { const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const documentIds = await createDivergentDocs(host1, host2); const network = await new TestReplicationNetwork().open(); try { let allowOnHost1 = false; const refused = new Set(); const host1Replicator = await network.createReplicator({ shouldAdvertise: ({ documentId }) => { if (allowOnHost1) { return true; } refused.add(documentId); return false; }, }); await host1.addReplicator(Context.default(), host1Replicator); await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); // Hold deny until EVERY document has been refused at least once, so each entry has a // failed round for the scope-change signal below to re-drive. Waiting on the first // refusal alone flips the policy before the later entries have settled, and nothing // then re-drives them; a fixed span was the previous stand-in for this. await expect.poll(() => refused.size, { timeout: SYNC_WINDOW_MS }).toBeGreaterThanOrEqual(documentIds.length); // `refused` is observed on host1, but host2's round settles failed a moment later, and the // scope-change signal below only re-drives entries that have ALREADY failed. Nothing // reports that transition, so this last hop is a short bounded grace rather than an event. await sleep(NO_TRAFFIC_WINDOW_MS); expect(await allConverged(host1, host2, documentIds)).toBe(false); allowOnHost1 = true; // Signal the scope change the way production does. `_sharePolicyChangedTask` is scheduled // by exactly three things — `onConnectionOpen`, `onConnectionAuthScopeChanged`, and an // incidental `documentRequested` — and flipping a `shouldAdvertise` closure fires none of // them, so without this the test waits on a heal retry happening to ask host1 for a doc. // That is why it failed at windows of 10s, 20s, 35s and 70s alike. for (const connection of host1Replicator.connections) { host1Replicator.context!.onConnectionAuthScopeChanged(connection); } // Its own window, and the widest in the suite: recovery here rides `_sharePolicyChangedTask`, // which throttles to `SHARE_POLICY_KICK_MIN_INTERVAL_MS` (1s) before it even fans out, over // five documents. 10s held when the file ran alone but not against the rest of the suite in // parallel; 15s is the value measured green across 20 consecutive full runs. await expect.poll(() => allConverged(host1, host2, documentIds), { timeout: 15_000 }).toBe(true); } finally { await host1.close(); await host2.close(); await network.close(); } }); test('control: docs converge when policy never denies', async ({ expect }) => { const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupAutomergeHost({ runtime: rt1.runtime }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupAutomergeHost({ runtime: rt2.runtime }); const documentIds = await createDivergentDocs(host1, host2); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); await host2.addReplicator(Context.default(), await network.createReplicator({ shouldAdvertise: () => true })); await expect.poll(() => allConverged(host1, host2, documentIds), { timeout: SYNC_WINDOW_MS }).toBe(true); } finally { await host1.close(); await host2.close(); await network.close(); } }); }); test('collection synchronization is bidirectional', async ({ expect }) => { const host1DocumentIds: DocumentId[] = []; const host2DocumentIds: DocumentId[] = []; const { runtime: runtime1, dispose: dispose1 } = createRuntime(); onTestFinished(() => dispose1()); const host1 = await setupAutomergeHost({ runtime: runtime1 }); for (const i of range(3)) { const handle = await host1.createDoc({ host: 1, docIndex: i }); host1DocumentIds.push(handle.documentId); } await host1.flush(Context.default()); const { runtime: runtime2, dispose: dispose2 } = createRuntime(); onTestFinished(() => dispose2()); const host2 = await setupAutomergeHost({ runtime: runtime2 }); for (const i of range(3)) { const handle = await host2.createDoc({ host: 2, docIndex: i }); host2DocumentIds.push(handle.documentId); } await host2.flush(Context.default()); const network = await new TestReplicationNetwork().open(); try { await host1.addReplicator(Context.default(), await network.createReplicator()); await host2.addReplicator(Context.default(), await network.createReplicator()); const host1CollectionId = 'test-host1-collection'; await host1.updateLocalCollectionState(host1CollectionId, host1DocumentIds); await host2.updateLocalCollectionState(host1CollectionId, host1DocumentIds); for (const documentId of host1DocumentIds) { await expect .poll(() => host2.getHeads([documentId]), { timeout: 1_000 }) .toEqual(await host1.getHeads([documentId])); } const host2CollectionId = 'test-host2-collection'; await host1.updateLocalCollectionState(host2CollectionId, host2DocumentIds); await host2.updateLocalCollectionState(host2CollectionId, host2DocumentIds); for (const documentId of host2DocumentIds) { await expect .poll(() => host1.getHeads([documentId]), { timeout: 1_000 }) .toEqual(await host2.getHeads([documentId])); } } finally { await host1.close(); await host2.close(); await network.close(); } }); // End-to-end policy gating using the real DXOS replication stack: // `MeshEchoReplicator` over `TeleportBuilder`. The mesh replicator is the // production wiring for peer-to-peer DXOS connections; it gates per-space // via `authorizeDevice(await createIdFromSpaceKey(spaceKey), deviceKey)`. describe('subductionPolicy + MeshEchoReplicator', () => { // Two hosts in the same space, both authorized → doc replicates. test('authorized peers in same space replicate', async ({ expect }) => { const spaceKey = PublicKey.random(); const teleportBuilder = new TeleportBuilder(); onTestFinished(() => teleportBuilder.destroy()); const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupMeshAutomergeHost({ runtime: rt1.runtime, spaceKey, teleportBuilder }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupMeshAutomergeHost({ runtime: rt2.runtime, spaceKey, teleportBuilder }); const handle = await host2.host.createDoc({ text: 'mesh-authorized' }); await host2.host.flush(Context.default()); await connectMeshPeers(teleportBuilder, host1, host2, spaceKey, /* authorized */ true); await expect .poll( async () => ( await host1.host.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 1_000 }) )?.doc()?.text, { timeout: 3_000 }, ) .toEqual('mesh-authorized'); }); // Two hosts in the same space, but neither side `authorizeDevice`s the other. // `MeshReplicatorConnection.shouldAdvertise` consults `_authorizedDevices`, which // is empty → `_subductionPolicy.authorizeFetch` rejects on the holder → fetcher // never reaches `'ready'`. test('unauthorized peers cannot fetch (authorizeFetch denial)', async ({ expect }) => { const spaceKey = PublicKey.random(); const teleportBuilder = new TeleportBuilder(); onTestFinished(() => teleportBuilder.destroy()); const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupMeshAutomergeHost({ runtime: rt1.runtime, spaceKey, teleportBuilder }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupMeshAutomergeHost({ runtime: rt2.runtime, spaceKey, teleportBuilder }); const handle = await host2.host.createDoc({ text: 'mesh-denied' }); await host2.host.flush(Context.default()); await connectMeshPeers(teleportBuilder, host1, host2, spaceKey, /* authorized */ false); // An unauthorized mesh connection advertises nothing, so there is no refusal to observe and // no traffic to drain — the bounded window is the assertion. const progress = host1.host.acquireDoc<{ text: string }>(handle.documentId); await sleep(NO_TRAFFIC_WINDOW_MS); expect(progress.state).to.not.equal('ready'); expect(progress.doc()?.text).to.be.undefined; }); // Start unauthorized; the holder's `_subductionPolicy.authorizeFetch` rejects. // Then authorize the device on the holder and drive a fresh commit (which schedules // `_sharePolicyChangedTask` → `_repo.shareConfigChanged()` on the holder — the // documented recovery hatch). The denied entry on the fetcher should clear and // the doc syncs. test('authorizeDevice after denial recovers replication', async ({ expect }) => { const spaceKey = PublicKey.random(); const teleportBuilder = new TeleportBuilder(); onTestFinished(() => teleportBuilder.destroy()); const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupMeshAutomergeHost({ runtime: rt1.runtime, spaceKey, teleportBuilder }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupMeshAutomergeHost({ runtime: rt2.runtime, spaceKey, teleportBuilder }); const handle = await host2.host.createDoc({ text: 'mesh-recover' }); await host2.host.flush(Context.default()); await connectMeshPeers(teleportBuilder, host1, host2, spaceKey, /* authorized */ false); // Probe but don't wait on `findWithProgress` (the subduction fork transitions // to `'unavailable'` when no peer serves the doc, which is sticky). // As above: nothing crosses an unauthorized connection, so this negative is a bounded window. await sleep(NO_TRAFFIC_WINDOW_MS); using probe = host1.host.acquireDoc<{ text: string }>(handle.documentId); expect(probe.state).to.not.equal('ready'); await host1.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceKey), host2.teleport.peerId); await host2.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceKey), host1.teleport.peerId); await host2.host.createDoc({ kick: true }); // Re-probe via a fresh load: the previous `DocumentQuery` may already have // entered `'unavailable'`, which is a terminal state in this fork. await expect .poll( async () => (await host1.host.loadDoc<{ text: string }>(Context.default(), handle.documentId, { timeout: 500 }))?.doc() ?.text, { timeout: SYNC_WINDOW_MS }, ) .toEqual('mesh-recover'); }); // Per-space authorization scoping: a device authorized for space A must not be // able to fetch documents that belong to space B, even on the same connection. // Verifies that `_subductionPolicy.authorizeFetch` resolves the doc's // `spaceKey` via `getContainingSpaceForDocument` → `_getSpaceKeyByRootDocumentId` // and that `MeshReplicatorConnection.shouldAdvertise` rejects when the device // is not in `_authorizedDevices[spaceB]`. test('device authorized for space A cannot fetch space B docs', async ({ expect }) => { const spaceA = PublicKey.random(); const spaceB = PublicKey.random(); const teleportBuilder = new TeleportBuilder(); onTestFinished(() => teleportBuilder.destroy()); // host2 owns two docs; we'll allocate the document ids up front so we can // wire the per-doc space lookup before either host opens. const spaceADocId = parseAutomergeUrl(generateAutomergeUrl()).documentId; const spaceBDocId = parseAutomergeUrl(generateAutomergeUrl()).documentId; const spaceLookup = (documentId: string): PublicKey | undefined => documentId === spaceADocId ? spaceA : documentId === spaceBDocId ? spaceB : undefined; const rt1 = createRuntime(); onTestFinished(() => rt1.dispose()); const host1 = await setupMeshAutomergeHost({ runtime: rt1.runtime, spaceLookup, teleportBuilder, }); const rt2 = createRuntime(); onTestFinished(() => rt2.dispose()); const host2 = await setupMeshAutomergeHost({ runtime: rt2.runtime, spaceLookup, teleportBuilder, }); await host2.host.createDoc(Automerge.from({ text: 'space-A-doc' }), { documentId: spaceADocId, preserveHistory: true, }); await host2.host.createDoc(Automerge.from({ text: 'space-B-doc' }), { documentId: spaceBDocId, preserveHistory: true, }); await host2.host.flush(Context.default()); // Authorize the device pair only for space A on both sides. await host1.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceA), host2.teleport.peerId); await host2.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceA), host1.teleport.peerId); const [connection1, connection2] = await teleportBuilder.connect(host1.teleport, host2.teleport); connection1.teleport.addExtension('automerge', host1.meshReplicator.createExtension()); connection2.teleport.addExtension('automerge', host2.meshReplicator.createExtension()); // Space A doc replicates. await expect .poll( async () => (await host1.host.loadDoc<{ text: string }>(Context.default(), spaceADocId, { timeout: 1_000 }))?.doc() ?.text, { timeout: 3_000 }, ) .toEqual('space-A-doc'); // Space B doc does NOT — host2's `_subductionPolicy.authorizeFetch` resolves // its space → spaceB, finds no authorized devices for spaceB, rejects. // No wait needed: the space-A poll above already observed this connection carrying a doc, so // anything space B was going to receive over it would have arrived by now. const progress = host1.host.acquireDoc<{ text: string }>(spaceBDocId); expect(progress.state).to.not.equal('ready'); expect(progress.doc()?.text).to.be.undefined; }); }); }); type RuntimeHandle = ReturnType; type RuntimeArg = RuntimeHandle['runtime']; const createRuntime = (tmpPath?: string): RuntimeHandle => { return createTestSqliteRuntime(tmpPath ? tmpPath + '.db' : ':memory:'); }; const countStoredRemoteHeads = async (runtime: RuntimeArg): Promise => { const adapter = new SqliteStorageAdapter({ runtime }); await adapter.open(); return (await adapter.loadRange(['subduction', 'remote-heads'])).length; }; const setupAutomergeHost = async ({ runtime, residency, }: { runtime: RuntimeArg; residency?: ConstructorParameters[0]['residency']; }) => { const host = new AutomergeHost({ runtime, useSubduction: true, residency, }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); return host; }; type MeshTestPeer = { host: AutomergeHost; meshReplicator: MeshEchoReplicator; teleport: TeleportPeer; }; /** * Spin up an `AutomergeHost` whose subduction transport carries a * `MeshEchoReplicator`, the production p2p wiring. The host's * `getSpaceKeyByRootDocumentId` is stubbed to return the test space key for any * document id, so `_subductionPolicy.authorizeFetch` → `MeshReplicatorConnection.shouldAdvertise` * resolves the space lookup without depending on actual `DatabaseDirectory` docs. */ const setupMeshAutomergeHost = async ({ runtime, spaceKey, spaceLookup, teleportBuilder, }: { runtime: RuntimeArg; /** Single-space mode: every doc reports this space. */ spaceKey?: PublicKey; /** Multi-space mode: per-doc lookup; takes precedence over `spaceKey`. */ spaceLookup?: (documentId: string) => PublicKey | undefined; teleportBuilder: TeleportBuilder; }): Promise => { invariant(spaceKey || spaceLookup, 'either spaceKey or spaceLookup is required'); const host = new AutomergeHost({ runtime, useSubduction: true, // Bypass DatabaseDirectory lookup: route every doc through a synthetic // `documentId → spaceKey` map so `MeshReplicatorConnection.shouldAdvertise` // can look up `_authorizedDevices[space]` without depending on // `DatabaseDirectory`-shaped contents. getSpaceKeyByRootDocumentId: spaceLookup ?? (() => spaceKey), }); await host.open(); onTestFinished(async () => { if (host.isOpen) { await host.close(); } }); const meshReplicator = new MeshEchoReplicator(); await host.addReplicator(Context.default(), meshReplicator); const teleport = teleportBuilder.createPeer({ factory: () => new TeleportPeer() }); return { host, meshReplicator, teleport }; }; /** * Bring up a teleport connection between two `MeshTestPeer`s and (optionally) * `authorizeDevice` each side for the given `spaceKey`. Returns when the * automerge extension has been wired into both teleport endpoints. */ const connectMeshPeers = async ( builder: TeleportBuilder, peer1: MeshTestPeer, peer2: MeshTestPeer, spaceKey: PublicKey, authorized: boolean, ) => { if (authorized) { await peer1.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceKey), peer2.teleport.peerId); await peer2.meshReplicator.authorizeDevice(await createIdFromSpaceKey(spaceKey), peer1.teleport.peerId); } const [connection1, connection2] = await builder.connect(peer1.teleport, peer2.teleport); connection1.teleport.addExtension('automerge', peer1.meshReplicator.createExtension()); connection2.teleport.addExtension('automerge', peer2.meshReplicator.createExtension()); };