Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([conflict-journal-subscribe-fanout-flush-coalesce]): coalesce base-hash flushes across auto-subscribe fan-out
[._.]/ Adam Eivyc9baef4e7251
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 54233f69a1..e9abdaa10a 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -216,6 +216,16 @@ export async function getOutboundCoverageForPeer(peerId) {* receiver-side reverse-subscribe path; it suppresses the immediate push so* we don't ping-pong (the peer that triggered the reverse just pushed us* the latest state by definition).+ *+ * `opts.awaitInitialPush` makes the first-insert push AWAITED instead of+ * fire-and-forget. Default false preserves the non-blocking single-subscribe+ * contract (the HTTP route and one-off subscribes must not stall on a slow+ * peer). The fan-out helpers set it true so the push — and the base-hash+ * stamps inside it — settle synchronously within an enclosing+ * `withBaseHashFlushBatch` scope; otherwise the async stamps escape the scope+ * and the per-record `sync_base_hashes.json` flush can't be coalesced. The+ * push failure stays non-fatal either way (logged, never thrown), so one dead+ * peer can't abort a fan-out loop.*/export async function subscribePeer({ peerId, recordKind, recordId }, opts = {}) {if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) {@@ -278,9 +288,13 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})// result lastPushedHash will short-circuit anyway. Callers that need a// forced re-push can call pushRecordToPeer(sub) directly.if (created && !opts.adoptedFromReverse) {- pushRecordToPeer(sub).catch((err) => {+ const initialPush = pushRecordToPeer(sub).catch((err) => {console.log(`⚠️ peerSync: initial push failed for ${sub.id}: ${err.message}`);});+ // Fan-out callers await the push inside a flush batch so its base-hash+ // stamps land before the batch's terminal flush; the default path leaves it+ // fire-and-forget so a single subscribe never blocks on a slow peer.+ if (opts.awaitInitialPush) await initialPush;}// `created` distinguishes a freshly-inserted subscription from an idempotent// hit on an existing one. Auto-subscribe helpers use this to suppress@@ -369,16 +383,22 @@ export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {// peers would otherwise return the existing subs and emit misleading// "🔗 auto-subscribed" lines on every retry / restart.const created = [];- for (const peer of targets) {- const sub = await subscribePeer({ peerId: peer.instanceId, recordKind, recordId }).catch((err) => {- console.log(`⚠️ peerSync: auto-subscribe ${recordKind}/${recordId} → ${peer.name || peer.instanceId} failed: ${err.message}`);- return null;- });- if (sub && sub.created) {- created.push({ peerId: peer.instanceId, subscriptionId: sub.id });- console.log(`🔗 peerSync: auto-subscribed ${recordKind}/${recordId} → ${peer.name || peer.instanceId}`);+ // Coalesce the base-hash flushes across this fan-out: one record subscribed+ // to N peers fires N initial pushes, each of which would otherwise rewrite+ // sync_base_hashes.json. `awaitInitialPush` keeps each push's stamps inside+ // the batch so the single terminal write covers all N.+ await withBaseHashFlushBatch(async () => {+ for (const peer of targets) {+ const sub = await subscribePeer({ peerId: peer.instanceId, recordKind, recordId }, { awaitInitialPush: true }).catch((err) => {+ console.log(`⚠️ peerSync: auto-subscribe ${recordKind}/${recordId} → ${peer.name || peer.instanceId} failed: ${err.message}`);+ return null;+ });+ if (sub && sub.created) {+ created.push({ peerId: peer.instanceId, subscriptionId: sub.id });+ console.log(`🔗 peerSync: auto-subscribed ${recordKind}/${recordId} → ${peer.name || peer.instanceId}`);+ }}- }+ });return created;}@@ -440,13 +460,19 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {// second toggle on the same category) don't double-report or noise the// backfill log line with already-subscribed records.const created = [];- for (const rec of missing) {- const sub = await subscribePeer({ peerId, recordKind, recordId: rec.id }, { skipCursorInit: cursorInited }).catch((err) => {- console.log(`⚠️ peerSync: backfill-subscribe ${recordKind}/${rec.id} → ${peerId} failed: ${err.message}`);- return null;- });- if (sub && sub.created) created.push({ recordId: rec.id, subscriptionId: sub.id });- }+ // Coalesce the base-hash flushes across the backfill: N records subscribed to+ // one peer fire N initial pushes, each of which would otherwise rewrite+ // sync_base_hashes.json. `awaitInitialPush` keeps each push's stamps inside+ // the batch so the single terminal write covers all N.+ await withBaseHashFlushBatch(async () => {+ for (const rec of missing) {+ const sub = await subscribePeer({ peerId, recordKind, recordId: rec.id }, { skipCursorInit: cursorInited, awaitInitialPush: true }).catch((err) => {+ console.log(`⚠️ peerSync: backfill-subscribe ${recordKind}/${rec.id} → ${peerId} failed: ${err.message}`);+ return null;+ });+ if (sub && sub.created) created.push({ recordId: rec.id, subscriptionId: sub.id });+ }+ });if (created.length > 0) {console.log(`🔗 peerSync: backfill-subscribed ${created.length} ${recordKind} record(s) → ${peerId}`);}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 49dfe81690..91de03e7a3 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -110,6 +110,7 @@ import { getBackendName } from '../memoryBackend.js';import { getCatalogBundleForRef } from '../catalogDB.js';import { applyRemoteChanges as applyCatalogRemoteChanges } from '../catalogSync.js';import { listCursors, __drainForTests as __drainCursors } from './peerTombstoneCursors.js';+import { getSyncBaseHash, contentHashForRecord, __resetBaseHashCacheForTests } from '../../lib/conflictJournal.js';let originalDataPath;let originalImagesPath;@@ -185,6 +186,11 @@ beforeEach(async () => {vi.mocked(getCatalogBundleForRef).mockReset().mockResolvedValue({ ingredients: [], refs: [] });vi.mocked(applyCatalogRemoteChanges).mockReset().mockResolvedValue({ errors: [] });+ // The conflict-journal base-hash side store caches `_baseHashes` against the+ // first PATHS.data it loaded; reset it so each test's fresh tmpdir starts+ // with an empty map (and stamps from a prior test don't bleed in).+ __resetBaseHashCacheForTests();+await __resetForTests();});@@ -525,6 +531,24 @@ describe('peerSync', () => {const second = await autoSubscribeRecordToAllPeers('universe', 'u1');expect(second).toEqual([]);});++ it('persists the base hash synchronously (awaitInitialPush coalesces the flush)', async () => {+ // Regression for the flush-coalesce wrap: the fan-out wraps its loop in+ // withBaseHashFlushBatch and passes awaitInitialPush, so every peer's+ // initial-push base-hash stamp lands BEFORE the helper returns — no+ // drain needed. Under the old fire-and-forget path the push hadn't even+ // started yet, so getSyncBaseHash would be null here.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'U1' });+ vi.mocked(getPeers).mockResolvedValue([+ { instanceId: 'peer-a', name: 'A', enabled: true, syncCategories: { universe: true } },+ { instanceId: 'peer-b', name: 'B', enabled: true, syncCategories: { universe: true } },+ ]);+ const created = await autoSubscribeRecordToAllPeers('universe', 'u1');+ expect(created.map(c => c.peerId).sort()).toEqual(['peer-a', 'peer-b']);+ // Stamp is on disk immediately (the batch's terminal flush ran inside the+ // awaited fan-out), matching the pushed record's content hash.+ expect(await getSyncBaseHash('universe', 'u1')).toBe(contentHashForRecord('universe', { id: 'u1', name: 'U1' }));+ });});describe('autoSubscribePeerToAllRecords', () => {@@ -623,6 +647,19 @@ describe('peerSync', () => {expect(await autoSubscribePeerToAllRecords('peer-a', 'bogus')).toEqual([]);});+ it('persists every record base hash synchronously (awaitInitialPush coalesces the flush)', async () => {+ // Backfill subscribes N records to one peer; awaitInitialPush keeps each+ // record's stamp inside the flush batch so all N are persisted by the+ // time the helper returns — without per-record flushes and without a+ // post-hoc drain.+ vi.mocked(listUniverses).mockResolvedValue([{ id: 'u1', name: 'U1' }, { id: 'u2', name: 'U2' }]);+ vi.mocked(getUniverse).mockImplementation(async (id) => ({ id, name: id.toUpperCase() }));+ const created = await autoSubscribePeerToAllRecords('peer-a', 'universe');+ expect(created.map(c => c.recordId).sort()).toEqual(['u1', 'u2']);+ expect(await getSyncBaseHash('universe', 'u1')).toBe(contentHashForRecord('universe', { id: 'u1', name: 'U1' }));+ expect(await getSyncBaseHash('universe', 'u2')).toBe(contentHashForRecord('universe', { id: 'u2', name: 'U2' }));+ });+it('drops ephemeral records before computing the set-diff', async () => {// Ephemeral universes/series are local-only — backfill must not// create subscriptions for them, even when every other gate passes.