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

fix: cache brain reconcile checksum (#5212)

[._.]/ Adam Eivy5ea196b6a113
diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.js
index f87de0413a..2bb9593ad6 100644
--- a/server/services/brainReconcile.js
+++ b/server/services/brainReconcile.js
@@ -35,6 +35,30 @@ import * as brainSyncLog from './brainSyncLog.js';
const { BRAIN_ENTITY_TYPES } = brainStorage;
+// The checksum endpoint is polled on every peer sync cycle, so rebuilding it
+// from every record file on every request turns a lightweight comparison into
+// an O(N) disk walk. Cache the result until a persisted entity mutation fires.
+//
+// `checksumGeneration` is load-bearing: a mutation can land while buildRawMap
+// is awaiting disk reads. That in-flight result is still safe for its original
+// caller (the old implementation had the same point-in-time limitation), but
+// it must never populate the cache after the mutation invalidated it.
+let checksumGeneration = 0;
+let cachedChecksum = null;
+let checksumBuild = null;
+
+function invalidateChecksum() {
+ checksumGeneration += 1;
+ cachedChecksum = null;
+ checksumBuild = null;
+}
+
+for (const type of BRAIN_ENTITY_TYPES) {
+ brainEvents.on(`${type}:upserted`, invalidateChecksum);
+ brainEvents.on(`${type}:deleted`, invalidateChecksum);
+}
+brainEvents.on('record:changed', invalidateChecksum);
+
/**
* Build the canonical `{ type: { id: record } }` map across all brain stores,
* including tombstones. Types and ids are emitted in sorted order so the
@@ -116,7 +140,24 @@ function computeChecksum(rawMap) {
* peer fetches this first and only pulls the full snapshot on a mismatch.
*/
export async function getBrainChecksum() {
- return computeChecksum(await buildRawMap());
+ if (cachedChecksum !== null) return cachedChecksum;
+ if (checksumBuild?.generation === checksumGeneration) return checksumBuild.promise;
+
+ const generation = checksumGeneration;
+ const promise = buildRawMap().then(
+ (rawMap) => {
+ const checksum = computeChecksum(rawMap);
+ if (checksumGeneration === generation) cachedChecksum = checksum;
+ if (checksumBuild?.promise === promise) checksumBuild = null;
+ return checksum;
+ },
+ (error) => {
+ if (checksumBuild?.promise === promise) checksumBuild = null;
+ throw error;
+ },
+ );
+ checksumBuild = { generation, promise };
+ return promise;
}
/**
diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.js
index 4f290a2ac1..caead089aa 100644
--- a/server/services/brainReconcile.test.js
+++ b/server/services/brainReconcile.test.js
@@ -25,13 +25,64 @@ import { getBrainChecksum, getBrainSnapshot, applyBrainSnapshot } from './brainR
// Default: every store empty unless a test overrides a specific type.
function emptyStores(overrides = {}) {
brainStorage.getRawRecords.mockImplementation(async (type) => overrides[type] ?? {});
+ brainEvents.emit('record:changed', { type: 'people', id: 'test-reset' });
}
beforeEach(() => {
vi.clearAllMocks();
+ brainEvents.emit('record:changed', { type: 'people', id: 'test-reset' });
});
describe('brainReconcile checksum', () => {
+ it('reuses the cached checksum when no brain records changed', async () => {
+ emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' } } });
+
+ const first = await getBrainChecksum();
+ const readsAfterFirst = brainStorage.getRawRecords.mock.calls.length;
+ const second = await getBrainChecksum();
+
+ expect(second).toBe(first);
+ expect(readsAfterFirst).toBe(brainStorage.BRAIN_ENTITY_TYPES.length);
+ expect(brainStorage.getRawRecords).toHaveBeenCalledTimes(readsAfterFirst);
+ });
+
+ it.each(['links:upserted', 'links:deleted', 'record:changed'])(
+ 'invalidates the cached checksum on %s',
+ async (eventName) => {
+ emptyStores({ links: { a: { id: 'a', updatedAt: '2026-01-01T00:00:00.000Z', title: 'A' } } });
+ const before = await getBrainChecksum();
+
+ brainStorage.getRawRecords.mockImplementation(async (type) => type === 'links'
+ ? { a: { id: 'a', updatedAt: '2026-01-02T00:00:00.000Z', title: 'B' } }
+ : {});
+ brainEvents.emit(eventName, { type: 'links', id: 'a' });
+ const after = await getBrainChecksum();
+
+ expect(after).not.toBe(before);
+ expect(brainStorage.getRawRecords).toHaveBeenCalledTimes(
+ brainStorage.BRAIN_ENTITY_TYPES.length * 2,
+ );
+ },
+ );
+
+ it('does not cache a checksum invalidated while its disk scan is in flight', async () => {
+ let invalidated = false;
+ brainStorage.getRawRecords.mockImplementation(async () => {
+ if (!invalidated) {
+ invalidated = true;
+ brainEvents.emit('record:changed', { type: 'links', id: 'a' });
+ }
+ return {};
+ });
+
+ await getBrainChecksum();
+ await getBrainChecksum();
+
+ expect(brainStorage.getRawRecords).toHaveBeenCalledTimes(
+ brainStorage.BRAIN_ENTITY_TYPES.length * 2,
+ );
+ });
+
it('is deterministic regardless of record/type key order', async () => {
emptyStores({
links: {
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 669c698e6a..00e9587139 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -131,12 +131,12 @@ export const brainEvents = new EventEmitter();
* Announce a persisted entity-store change that did NOT emit the usual
* `${type}:upserted` / `${type}:deleted` event.
*
- * Two write paths are deliberately event-silent — `applyRemoteRecord` (peer
- * applies, silent to prevent the #1077 cross-peer echo loop) and
- * `upsertWithId({ emitEvent: false })` (the caller emits its own richer event).
- * Read-through consumers didn't care, but a derived in-memory projection does:
- * without this signal, brainSearchIndex would serve stale results forever after
- * an inbound sync (issue #3506).
+ * Some write paths are deliberately event-silent — `applyRemoteRecord` (peer
+ * applies, silent to prevent the #1077 cross-peer echo loop),
+ * `upsertWithId({ emitEvent: false })` (the caller emits its own richer event),
+ * tombstone pruning, and origin-instance backfill. Read-through consumers did
+ * not care, but derived in-memory state does: without this signal,
+ * brainSearchIndex or the reconcile checksum cache could stay stale.
*
* LOCAL-ONLY, like `sync:applied`: it carries no record payload, is never fed
* to the sync log, and is never relayed to a peer, so it cannot amplify an
@@ -1156,6 +1156,7 @@ export async function pruneTombstones(type, cutoffMs) {
const deletedAt = Date.parse(record.deletedAt ?? record.updatedAt ?? '');
if (Number.isFinite(deletedAt) && deletedAt < cutoffMs) {
await store.deleteOneNow(id);
+ emitRecordChanged(type, id);
return true;
}
return false;
@@ -1180,6 +1181,7 @@ export async function backfillOriginInstanceId() {
// Tombstones always carry originInstanceId; skip them and absent records.
if (!record || isTombstone(record) || record.originInstanceId) return false;
await store.saveOneNow(id, { ...record, originInstanceId: instanceId });
+ emitRecordChanged(type, id);
return true;
})));
return changes.filter(Boolean).length;
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 25045c0d4c..551509deb1 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -184,8 +184,12 @@ describe('brainStorage tombstones', () => {
const live = await brainStorage.create('memories', { content: 'alive' });
const cutoff = Date.parse(ISO('2021-01-01'));
+ const changed = vi.fn();
+ brainStorage.brainEvents.on('record:changed', changed);
const pruned = await brainStorage.pruneTombstones('memories', cutoff);
+ brainStorage.brainEvents.off('record:changed', changed);
expect(pruned).toBe(1); // only the 2020 tombstone
+ expect(changed).toHaveBeenCalledWith({ type: 'memories', id: 'old' });
expect(await rawRecord('memories', 'old')).toBeUndefined();
expect((await rawRecord('memories', freshCreated.id))._deleted).toBe(true);