Skip to content

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

feat([conflict-journal-push-flush-coalesce]): coalesce per-push base-hash flushes via flush-batch scope

[._.]/ Adam Eivy940eed7b32c2
diff --git a/server/lib/README.md b/server/lib/README.md
index 86a0c54ff0..35180e2abb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -95,7 +95,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |
-| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store. `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from `pruneTombstonedUniverses`/`pruneTombstonedSeries`) so the side store doesn't grow without bound. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
+| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from `pruneTombstonedUniverses`/`pruneTombstonedSeries`) so the side store doesn't grow without bound. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index a27e2416f8..22cdbe9b8d 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -125,6 +125,10 @@ let _baseHashes = null; // Map<`${kind}:${id}`, sha256>
let _loadPromise = null;
let _baseDirty = false;
let _flushTail = Promise.resolve();
+// >0 while a `withBaseHashFlushBatch` scope is active. Defers the disk write so
+// an await-separated multi-record push loop (peer:online convergence) collapses
+// N `sync_base_hashes.json` rewrites into one at the batch's terminal flush.
+let _flushBatchDepth = 0;
const baseKey = (kind, id) => `${kind}:${id}`;
@@ -169,8 +173,15 @@ export async function deleteSyncBaseHash(kind, id) {
}
/** Persist the base-hash map if dirty. Serialized so concurrent flushes can't
- * interleave file writes. Call once after a merge's write loop. */
+ * interleave file writes. Call once after a merge's write loop.
+ *
+ * Inside a `withBaseHashFlushBatch` scope the write is deferred: the in-memory
+ * stamps stay coalesced (`_baseDirty`) and the single disk write fires when the
+ * outermost batch closes. Callers still get a thenable (`_flushTail`) so any
+ * `await flushBaseHashes()` resolves immediately rather than blocking inside
+ * the batch. */
export function flushBaseHashes() {
+ if (_flushBatchDepth > 0) return _flushTail;
if (!_baseDirty) return _flushTail;
_flushTail = _flushTail.then(async () => {
if (!_baseDirty) return;
@@ -185,6 +196,35 @@ export function flushBaseHashes() {
return _flushTail;
}
+/**
+ * Run `fn` with base-hash disk writes coalesced into ONE flush at the end.
+ *
+ * The base-hash map already coalesces SYNCHRONOUS bursts (the `_baseDirty` flag
+ * means a run of `setSyncBaseHash` calls before a single `flushBaseHashes` pays
+ * one write). What it can't collapse on its own is an AWAIT-SEPARATED loop: the
+ * `peer:online` convergence walk (`retryPendingPushesForPeer`) pushes N records
+ * in sequence, and each push's fire-and-forget `flushBaseHashes()` lands on the
+ * settled `_flushTail` from the previous record — so a 50-record convergence
+ * rewrites `sync_base_hashes.json` 50 times. Wrapping the loop in this scope
+ * defers every interior flush; the single terminal write captures all N stamps.
+ *
+ * Re-entrant (depth-counted) so nested scopes collapse to the outermost batch,
+ * and the terminal flush runs in `finally` so a thrown/rejected `fn` still
+ * persists whatever stamps landed before it failed. Unlike a `setTimeout`
+ * debounce (tried and reverted — the unref'd timer leaked into `peerSync.test.js`'s
+ * settle-waits and made the suite flaky), this is deterministic: the flush is
+ * tied to the scope boundary, not a wall-clock timer, so tests just `await` it.
+ */
+export async function withBaseHashFlushBatch(fn) {
+ _flushBatchDepth += 1;
+ try {
+ return await fn();
+ } finally {
+ _flushBatchDepth -= 1;
+ if (_flushBatchDepth === 0) await flushBaseHashes();
+ }
+}
+
// ---- conflict detection + journaling ----
/**
@@ -383,5 +423,6 @@ export function __resetBaseHashCacheForTests() {
_loadPromise = null;
_baseDirty = false;
_flushTail = Promise.resolve();
+ _flushBatchDepth = 0;
_store = null;
}
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
index ae0884cbc9..8396d6f414 100644
--- a/server/lib/conflictJournal.test.js
+++ b/server/lib/conflictJournal.test.js
@@ -6,8 +6,25 @@ import { makePathsProxy } from './mockPathsDataRoot.js';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'conflict-journal-test-'));
-vi.mock('./fileUtils.js', async (importOriginal) =>
- makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+// Shared counter for base-hash file writes (delegating spy below). Hoisted so
+// the vi.mock factory can reference it. The flush-batch tests assert N stamps
+// collapse to ONE sync_base_hashes.json rewrite.
+const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));
+
+vi.mock('./fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: TEST_DATA_ROOT,
+ overrides: {
+ // Count base-hash rewrites, then delegate to the real writer so on-disk
+ // state stays correct for every other assertion in this suite.
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ },
+ });
+});
const cj = await import('./conflictJournal.js');
@@ -322,3 +339,68 @@ describe('conflictJournal — mediaCollection scalar-subset hashing', () => {
expect(entries[0].diffSummary.some((d) => d.field === 'items' || d.field === 'updatedAt')).toBe(false);
});
});
+
+describe('conflictJournal — withBaseHashFlushBatch coalescing', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
+ });
+
+ it('collapses N await-separated stamp+flush cycles into ONE file write', async () => {
+ // Simulate the peer:online convergence loop: stamp record i, flush (deferred
+ // by the batch), then "await the network" before the next record.
+ await cj.withBaseHashFlushBatch(async () => {
+ for (let i = 0; i < 10; i++) {
+ await cj.setSyncBaseHash('universe', `u-${i}`, cj.contentHashForRecord('universe', uni({ id: `u-${i}`, starterPrompt: `p-${i}` })));
+ await cj.flushBaseHashes(); // no-op inside the batch
+ await Promise.resolve(); // yield, as an inter-push await would
+ }
+ });
+ // Exactly one terminal write for all 10 stamps.
+ expect(writeCounter.baseHash).toBe(1);
+ // …and every stamp persisted.
+ for (let i = 0; i < 10; i++) {
+ expect(await cj.getSyncBaseHash('universe', `u-${i}`)).toBe(cj.contentHashForRecord('universe', uni({ id: `u-${i}`, starterPrompt: `p-${i}` })));
+ }
+ });
+
+ it('without a batch, the same loop writes once per stamp', async () => {
+ for (let i = 0; i < 5; i++) {
+ await cj.setSyncBaseHash('universe', `u-${i}`, cj.contentHashForRecord('universe', uni({ id: `u-${i}`, starterPrompt: `p-${i}` })));
+ await cj.flushBaseHashes();
+ }
+ expect(writeCounter.baseHash).toBe(5);
+ });
+
+ it('nested batches collapse to the outermost (one write)', async () => {
+ await cj.withBaseHashFlushBatch(async () => {
+ await cj.setSyncBaseHash('universe', 'u-a', cj.contentHashForRecord('universe', uni({ id: 'u-a' })));
+ await cj.withBaseHashFlushBatch(async () => {
+ await cj.setSyncBaseHash('universe', 'u-b', cj.contentHashForRecord('universe', uni({ id: 'u-b' })));
+ await cj.flushBaseHashes();
+ });
+ // Inner scope closed but depth is still >0 → no write yet.
+ expect(writeCounter.baseHash).toBe(0);
+ });
+ expect(writeCounter.baseHash).toBe(1);
+ });
+
+ it('flushes whatever stamps landed even when the batch body throws', async () => {
+ await expect(cj.withBaseHashFlushBatch(async () => {
+ await cj.setSyncBaseHash('universe', 'u-x', cj.contentHashForRecord('universe', uni({ id: 'u-x' })));
+ throw new Error('push blew up mid-loop');
+ })).rejects.toThrow('push blew up mid-loop');
+ // The terminal flush ran in `finally`, so the pre-throw stamp persisted.
+ expect(writeCounter.baseHash).toBe(1);
+ expect(await cj.getSyncBaseHash('universe', 'u-x')).toBe(cj.contentHashForRecord('universe', uni({ id: 'u-x' })));
+ });
+
+ it('no write when no stamp landed inside the batch', async () => {
+ await cj.withBaseHashFlushBatch(async () => {
+ await Promise.resolve(); // did nothing dirty
+ });
+ expect(writeCounter.baseHash).toBe(0);
+ });
+});
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 025e77bfc2..54233f69a1 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -46,7 +46,7 @@ import { peerFetch } from '../../lib/peerHttpClient.js';
import { getOrComputeImageSha256, sidecarGenParamsHash } from '../../lib/assetHash.js';
import { generateThumbnail } from '../../lib/ffmpeg.js';
import { sanitizeRecordForWire } from '../../lib/syncWire.js';
-import { setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';
+import { setSyncBaseHash, contentHashForRecord, flushBaseHashes, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';
import { collectAssetReferences } from './exporter.js';
import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';
import { pullSidecarForImage } from './sidecarSync.js';
@@ -1003,9 +1003,14 @@ export async function pushRecordToPeer(sub, options = {}) {
// shared-state base for the two journaled kinds. This is the symmetric
// convergence point to the receiver advancing its base in mergeXxxFromSync —
// it keeps a peer's echo (reverse-subscription push-back) from later looking
- // like a divergence. Best-effort; never block the push result on it — the
- // stamp + filesystem flush run fire-and-forget so a slow disk can't delay the
- // push loop. The `.catch()` keeps the rejection from escaping as unhandled.
+ // like a divergence. Best-effort; never block the push result on a slow DISK
+ // — only the filesystem flush runs fire-and-forget. The in-memory stamps ARE
+ // awaited: `setSyncBaseHash` just mutates the cached map (no disk I/O), so
+ // awaiting it costs nothing once the map is loaded, and it guarantees
+ // `_baseDirty` is set before this push returns. That matters under
+ // `withBaseHashFlushBatch` — the batch's terminal flush only writes when a
+ // stamp landed, so a stamp still pending when the batch closed would be lost
+ // until the next flush. The `.catch()` keeps a rejection from escaping.
if (PEER_SUBSCRIBABLE_KINDS.includes(sub.recordKind) && payload.record) {
// For mediaCollection, contentHashForRecord hashes only the scalar subset
// (items are union-merged on the receiver, so the post-push collections are
@@ -1025,9 +1030,11 @@ export async function pushRecordToPeer(sub, options = {}) {
if (issue?.id) stamps.push(setSyncBaseHash('issue', issue.id, contentHashForRecord('issue', issue)));
}
}
- Promise.all(stamps)
- .then(() => flushBaseHashes())
- .catch((err) => console.log(`⚠️ peerSync: base-hash stamp after push failed: ${err?.message || err}`));
+ await Promise.all(stamps).catch((err) => console.log(`⚠️ peerSync: base-hash stamp after push failed: ${err?.message || err}`));
+ // Non-blocking disk write. Inside a flush batch this is a no-op (the batch's
+ // terminal flush coalesces every record's stamps into one rewrite); outside
+ // a batch it fires async exactly as before.
+ flushBaseHashes().catch((err) => console.log(`⚠️ peerSync: base-hash flush after push failed: ${err?.message || err}`));
}
return {
pushed: true,
@@ -2056,16 +2063,22 @@ export async function retryPendingPushesForPeer(peerId) {
// the network call for any sub whose content is unchanged — we still
// "walked" the sub but never pushed it.
let pushed = 0;
- for (const sub of subs) {
- // peer:online fired — re-probe schema-blocked subs immediately (peer
- // may have upgraded since the last 409). Edit-triggered pushes still
- // respect the cooldown.
- const result = await pushRecordToPeer(sub, { bypassSchemaCooldown: true }).catch((err) => {
- console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);
- return null;
- });
- if (result?.pushed) pushed += 1;
- }
+ // Coalesce the per-push base-hash flushes: this loop pushes every subscribed
+ // record in sequence, and each push would otherwise rewrite
+ // sync_base_hashes.json once. The flush batch defers them into a single
+ // terminal write covering all N records' stamps.
+ await withBaseHashFlushBatch(async () => {
+ for (const sub of subs) {
+ // peer:online fired — re-probe schema-blocked subs immediately (peer
+ // may have upgraded since the last 409). Edit-triggered pushes still
+ // respect the cooldown.
+ const result = await pushRecordToPeer(sub, { bypassSchemaCooldown: true }).catch((err) => {
+ console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);
+ return null;
+ });
+ if (result?.pushed) pushed += 1;
+ }
+ });
return { walked: subs.length, pushed };
}