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: keep accepted Brain changes relaying after a crash (#8316)

[._.]/ Adam Eivyf5c3cee4f24f
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 64203531a7..d2d9b0ba7f 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -1322,7 +1322,28 @@ export const deleteThread = (id) => remove('threads', id);
// signal (see emitRecordChanged) — it never leaves this instance.
/**
- * Apply a remote record to a store (last-writer-wins by updatedAt)
+ * The LWW rejection for an incoming op whose clock is not newer than ours.
+ *
+ * `local_current` means we already hold exactly the state the op carries — same
+ * LWW clock, same delete-ness — so the op is ALREADY APPLIED here (an echo, or a
+ * delta re-pulled after a crash between our save and our relay append). The
+ * wire-shape of our copy rides along so the caller can relay it if our sync log
+ * lacks it (#8316). Anything else is `local_newer`: a genuinely stale op.
+ */
+function rejectedAgainst(existing, record, incomingIsDelete) {
+ if (existing.updatedAt !== record.updatedAt || isTombstone(existing) !== incomingIsDelete) {
+ return { applied: false, reason: 'local_newer' };
+ }
+ const current = isTombstone(existing)
+ ? { updatedAt: existing.updatedAt, originInstanceId: existing.originInstanceId }
+ : { ...existing };
+ return { applied: false, reason: 'local_current', current };
+}
+
+/**
+ * Apply a remote record to a store (last-writer-wins by updatedAt).
+ * Rejections carry `reason` `local_newer` (stale op) or `local_current` (op
+ * already applied — `current` is our copy in wire shape); see rejectedAgainst.
*/
export async function applyRemoteRecord(type, id, record, op) {
const store = storeFor(type);
@@ -1347,7 +1368,7 @@ export async function applyRemoteRecord(type, id, record, op) {
// new as the incoming delete. The tombstone-vs-tombstone case makes a
// repeated delete idempotent → not relayed → the echo loop converges.
if (existing && existing.updatedAt >= record.updatedAt) {
- return { applied: false, reason: 'local_newer' };
+ return rejectedAgainst(existing, record, true);
}
// Tombstone in place even when no local record exists. A delete that
// arrives before we ever saw a create still leaves a marker, so a later
@@ -1369,7 +1390,7 @@ export async function applyRemoteRecord(type, id, record, op) {
// resurrection loop. A genuinely newer create (later updatedAt than the
// tombstone) still wins and legitimately revives the record.
if (existing && existing.updatedAt >= record.updatedAt) {
- return { applied: false, reason: 'local_newer' };
+ return rejectedAgainst(existing, record, record._deleted === true);
}
// Defense-in-depth: a create carrying `_deleted` (a future peer, or a
// direct caller bypassing brainSync's reroute) must persist as a proper
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 6acd7836a6..df68150657 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -35,6 +35,7 @@ vi.mock('./brainSyncLog.js', async () => {
import * as brainStorage from './brainStorage.js';
import * as brainSyncLog from './brainSyncLog.js';
+import { applyRemoteChanges } from './brainSync.js';
import { readJSONFile } from '../lib/fileUtils.js';
afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });
@@ -174,7 +175,8 @@ describe('brainStorage tombstones', () => {
'links', 'l1', { updatedAt: ISO('2026-01-01') }, 'delete'
);
expect(again.applied).toBe(false);
- expect(again.reason).toBe('local_newer');
+ // Same clock, same delete-ness: already applied, not stale.
+ expect(again.reason).toBe('local_current');
});
it('update() treats a tombstone as not-found', async () => {
@@ -207,6 +209,74 @@ describe('brainStorage tombstones', () => {
});
});
+// What a delta-only (legacy) peer pulling from this instance would receive for
+// one record: every sync-log entry after `sinceSeq` naming it.
+async function relayedEntries(sinceSeq, id) {
+ const { changes } = await brainSyncLog.getChangesSince(sinceSeq, 1000);
+ return changes.filter((c) => c.id === id);
+}
+
+describe('inbound brain changes keep relaying across a crash (#8316)', () => {
+ it('relays a saved-but-unrelayed change when the source re-serves it', async () => {
+ const sinceSeq = brainSyncLog.getCurrentSeq();
+ const changes = [
+ { op: 'create', type: 'ideas', id: 'relay-up', record: { title: 'From B', updatedAt: ISO('2026-03-01') }, originInstanceId: 'peer-b' },
+ { op: 'delete', type: 'ideas', id: 'relay-del', record: { updatedAt: ISO('2026-03-02') }, originInstanceId: 'peer-b' },
+ ];
+
+ // The records land, then the relay append is rejected: the call must fail
+ // so the caller keeps its source cursor rather than advancing past them.
+ brainSyncLog.appendChanges.mockRejectedValueOnce(new Error('disk full'));
+ await expect(applyRemoteChanges(changes)).rejects.toThrow('disk full');
+ expect(await brainStorage.getById('ideas', 'relay-up')).toMatchObject({ title: 'From B' });
+ expect((await rawRecord('ideas', 'relay-del'))._deleted).toBe(true);
+ expect(await relayedEntries(sinceSeq, 'relay-up')).toEqual([]);
+
+ // A restart rebuilds the log index from disk, then the source re-serves the
+ // same sequence. LWW skips the re-apply, but the op is relayed.
+ await brainSyncLog.initSyncLog();
+ const retry = await applyRemoteChanges(changes);
+ expect(retry.skipped).toBe(2);
+
+ const up = await relayedEntries(sinceSeq, 'relay-up');
+ expect(up).toHaveLength(1);
+ expect(up[0]).toMatchObject({ op: 'create', record: { title: 'From B', updatedAt: ISO('2026-03-01') } });
+ const del = await relayedEntries(sinceSeq, 'relay-del');
+ expect(del).toHaveLength(1);
+ expect(del[0]).toMatchObject({ op: 'delete', record: { updatedAt: ISO('2026-03-02') } });
+ });
+
+ it('retries a change whose relay already landed without a second log entry', async () => {
+ const sinceSeq = brainSyncLog.getCurrentSeq();
+ const change = { op: 'update', type: 'people', id: 'relay-once', record: { name: 'Bo', updatedAt: ISO('2026-04-01') }, originInstanceId: 'peer-b' };
+
+ await applyRemoteChanges([change]);
+ // Crash before the cursor save: restart, then the source re-serves it —
+ // twice, as another cycle would.
+ await brainSyncLog.initSyncLog();
+ await applyRemoteChanges([change]);
+ await applyRemoteChanges([change]);
+
+ expect(await relayedEntries(sinceSeq, 'relay-once')).toHaveLength(1);
+ });
+
+ it('neither applies nor relays a genuinely stale change', async () => {
+ const local = await brainStorage.create('ideas', { title: 'Local' });
+ const sinceSeq = brainSyncLog.getCurrentSeq();
+
+ const result = await applyRemoteChanges([
+ // Older clock than our copy.
+ { op: 'update', type: 'ideas', id: local.id, record: { title: 'Stale', updatedAt: ISO('2000-01-01') }, originInstanceId: 'peer-b' },
+ // Same clock, but a delete of a record we hold live — not our state.
+ { op: 'delete', type: 'ideas', id: local.id, record: { updatedAt: local.updatedAt }, originInstanceId: 'peer-b' },
+ ]);
+
+ expect(result.skipped).toBe(2);
+ expect(await brainStorage.getById('ideas', local.id)).toMatchObject({ title: 'Local', updatedAt: local.updatedAt });
+ expect(await relayedEntries(sinceSeq, local.id)).toEqual([]);
+ });
+});
+
describe('memory recency ordering', () => {
it('memoryRecencyMs prefers source clocks over storage clocks', () => {
// sourceUpdatedAt wins
diff --git a/server/services/brainSync.js b/server/services/brainSync.js
index 1183506051..870a0ea399 100644
--- a/server/services/brainSync.js
+++ b/server/services/brainSync.js
@@ -6,7 +6,21 @@
* Writes directly to storage without triggering brainEvents.
* Logs applied changes to the local sync log so they relay to other peers
* and sync status counts reflect received data. Echo prevention is handled
- * by the LWW dedup in applyRemoteRecord (same updatedAt = skip).
+ * by the LWW dedup in applyRemoteRecord (same updatedAt = skip) plus the
+ * sync log's operation dedup (a relay the log already carries is dropped).
+ *
+ * Crash safety (#8316): the record save and the relay append are two writes,
+ * so a crash (or a rejected append) between them leaves a record that is
+ * accepted here but absent from our outgoing log — invisible forever to a
+ * delta-only peer. Two rules close that gap:
+ * - A failed relay append THROWS, so the caller never advances its source
+ * cursor past a change it hasn't relayed; the source re-serves it.
+ * - A re-served change our state already reflects (`local_current`) is
+ * relayed again, deduplicated against the log — so the retry relays a
+ * change the crash stranded, and never mints a second entry for one that
+ * did land.
+ * The source cursor is therefore the durable receipt of an inbound change:
+ * it only moves once the relay is on disk.
*/
import * as brainStorage from './brainStorage.js';
@@ -24,6 +38,15 @@ const { BRAIN_ENTITY_TYPES } = brainStorage;
export async function applyRemoteChanges(changes) {
let inserted = 0, updated = 0, deleted = 0, skipped = 0;
const relayBatch = [];
+ const appliedRecords = [];
+ // An op our state already reflects: relay OUR copy (the state a pulling peer
+ // should converge to). The skipLogged append drops it when the log already
+ // carries it — the common echo case — so this never amplifies.
+ const relayIfCurrent = (result, op, type, id) => {
+ if (result.reason !== 'local_current') return;
+ const { current } = result;
+ relayBatch.push({ op, type, id, record: current, originInstanceId: current.originInstanceId });
+ };
for (const change of changes) {
let { op, type, id, record, originInstanceId } = change;
@@ -46,11 +69,14 @@ export async function applyRemoteChanges(changes) {
const result = await brainStorage.applyRemoteRecord(type, id, record, 'delete');
if (result.applied) {
deleted++;
- // Relay only APPLIED changes — a rejected (local_newer) op is NOT
- // re-appended, which is what stops the cross-peer echo amplification.
+ // Relay only applied (or already-reflected, below) changes — a stale
+ // (local_newer) op is NOT re-appended, which is what stops the
+ // cross-peer echo amplification.
relayBatch.push({ op, type, id, record, originInstanceId });
+ appliedRecords.push({ type, id });
} else {
skipped++;
+ relayIfCurrent(result, op, type, id);
}
} else if (op === 'create' || op === 'update') {
if (!record) { skipped++; continue; }
@@ -59,28 +85,39 @@ export async function applyRemoteChanges(changes) {
if (op === 'create') inserted++;
else updated++;
relayBatch.push({ op, type, id, record, originInstanceId });
+ appliedRecords.push({ type, id });
} else {
skipped++;
+ relayIfCurrent(result, op, type, id);
}
} else {
skipped++;
}
}
- // Batch-append all applied changes to the sync log in a single lock acquisition
+ // Batch-append all relays to the sync log in a single lock acquisition.
+ // skipLogged makes the append idempotent: a retried delta can't mint a second
+ // entry for an op the log already carries.
+ let appendError = null;
if (relayBatch.length > 0) {
- await brainSyncLog.appendChanges(relayBatch)
- .catch(err => console.error(`⚠️ Sync log batch append failed (${relayBatch.length} entries): ${err.message}`));
+ await brainSyncLog.appendChanges(relayBatch, { skipLogged: true }).catch((err) => {
+ appendError = err;
+ console.error(`❌ Brain sync relay append failed (${relayBatch.length} entries): ${err.message}`);
+ });
+ }
+ if (appliedRecords.length > 0) {
// Local-only signal so the memory bridge re-vectorizes synced-in records
// (issue #1080). applyRemoteRecord is event-silent to prevent cross-peer
// echo (#1077); this event drives ONLY local embedding and never feeds the
// sync log, so it can't amplify. Carries just {type, id} — the bridge
- // re-reads canonical state. Emitted on the relay batch (applied changes
- // only) so a rejected LWW op doesn't trigger a needless re-embed.
- brainEvents.emit('sync:applied', {
- records: relayBatch.map(({ type, id }) => ({ type, id })),
- });
+ // re-reads canonical state. Emitted for newly applied changes only, so
+ // a rejected or already-reflected op doesn't trigger a needless re-embed.
+ brainEvents.emit('sync:applied', { records: appliedRecords });
}
+ // The records are saved either way (and re-embedded above), but the relay is
+ // not — fail the call so the caller keeps its cursor and the source re-serves
+ // these changes; the retry relays them through the local_current path.
+ if (appendError) throw appendError;
console.log(`🔄 Brain sync applied: ${inserted} inserted, ${updated} updated, ${deleted} deleted, ${skipped} skipped`);
return { inserted, updated, deleted, skipped };
diff --git a/server/services/brainSync.test.js b/server/services/brainSync.test.js
index 460f59f335..4455bcc0bd 100644
--- a/server/services/brainSync.test.js
+++ b/server/services/brainSync.test.js
@@ -106,7 +106,7 @@ describe('brainSync', () => {
expect(appendChanges).toHaveBeenCalledWith([
{ op: 'create', type: 'people', id: 'p1', record: { name: 'A' }, originInstanceId: 'peer-1' }
- ]);
+ ], { skipLogged: true });
});
it('does not log skipped changes to sync log', async () => {
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 47b4aa6ef7..86b0132689 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -41,6 +41,26 @@ let appendedSinceCompaction = true;
// file, whether or not it dropped lines). A repeat call with an unchanged
// floor and nothing appended since can only reproduce the same result.
let lastCompactionFloor = null;
+// Operation identity (see opKey) of every entry in the log. Lets a relay append
+// skip an operation the log already carries, so a peer delta retried after a
+// crash — or re-pulled because its append failed — relays exactly once (#8316).
+let loggedOps = new Set();
+
+/**
+ * Identity of the state a log entry publishes: the record, its LWW clock, and
+ * whether it is a delete. Two entries with the same key are interchangeable to
+ * a pulling peer, so the second is redundant. Null for an unkeyable entry.
+ */
+function opKey(entry) {
+ const updatedAt = entry?.record?.updatedAt;
+ if (!entry?.type || !entry?.id || updatedAt == null) return null;
+ return `${entry.type}/${entry.id}@${updatedAt}${entry.op === 'delete' ? '#delete' : ''}`;
+}
+
+function trackLoggedOp(entry) {
+ const key = opKey(entry);
+ if (key) loggedOps.add(key);
+}
async function ensureBrainDir() {
await ensureDir(DATA_DIR);
@@ -78,6 +98,7 @@ async function* streamLines(path, start = 0) {
*/
async function loadIndex() {
offsets = [];
+ loggedOps = new Set();
fileSize = 0;
currentSeq = 0;
pendingNewline = false;
@@ -94,6 +115,7 @@ async function loadIndex() {
const entry = safeJSONParse(text, null);
if (typeof entry?.seq !== 'number') continue;
offsets.push({ seq: entry.seq, offset });
+ trackLoggedOp(entry);
currentSeq = entry.seq;
}
// Real byte size, not the offset past the last complete line: an unterminated
@@ -129,8 +151,9 @@ async function writeIndexedLines(lines) {
fileSize += 1;
pendingNewline = false;
}
- for (const { seq, text } of lines) {
+ for (const { seq, text, entry } of lines) {
offsets.push({ seq, offset: fileSize });
+ trackLoggedOp(entry);
fileSize += Buffer.byteLength(text, 'utf8') + 1;
}
}
@@ -184,15 +207,21 @@ export async function appendChange(op, type, id, record, originInstanceId) {
originInstanceId,
ts: new Date().toISOString()
};
- await writeIndexedLines([{ seq: entry.seq, text: JSON.stringify(entry) }]);
+ await writeIndexedLines([{ seq: entry.seq, text: JSON.stringify(entry), entry }]);
return entry;
});
}
/**
* Append multiple change entries in a single mutex-guarded batch (reduces lock contention)
+ *
+ * `skipLogged` makes the append idempotent for relays: an entry whose operation
+ * (record + updatedAt + delete-ness) the log already carries is dropped, as is
+ * a repeat within the batch. The check and the write share one lock hold, so a
+ * retried relay can never mint a second entry for the same operation (#8316).
+ * Returns only the entries actually written.
*/
-export async function appendChanges(entries) {
+export async function appendChanges(entries, { skipLogged = false } = {}) {
if (!entries?.length) return [];
return withLock(async () => {
await ensureBrainDir();
@@ -200,15 +229,22 @@ export async function appendChanges(entries) {
const startSeq = currentSeq;
const results = [];
const lines = [];
+ const batchKeys = new Set();
let nextSeq = startSeq;
for (const { op, type, id, record, originInstanceId } of entries) {
+ if (skipLogged) {
+ const key = opKey({ op, type, id, record });
+ if (key && (loggedOps.has(key) || batchKeys.has(key))) continue;
+ if (key) batchKeys.add(key);
+ }
nextSeq++;
const entry = { seq: nextSeq, op, type, id, record, originInstanceId, ts: new Date().toISOString() };
- lines.push({ seq: nextSeq, text: JSON.stringify(entry) });
+ lines.push({ seq: nextSeq, text: JSON.stringify(entry), entry });
results.push(entry);
}
// Reserve sequence numbers before write to avoid reuse on partial failure
// (matches appendChange semantics where currentSeq advances pre-write)
+ if (lines.length === 0) return results;
currentSeq = nextSeq;
await writeIndexedLines(lines);
return results;
@@ -417,10 +453,12 @@ export async function compactLog(minSeq = 0, { force = false } = {}) {
// Rebuild index offsets from what was written
offsets = [];
+ loggedOps = new Set();
let offset = 0;
- for (const { rawLine, seq } of kept) {
+ for (const { rawLine, seq, entry } of kept) {
if (typeof seq === 'number') {
offsets.push({ seq, offset });
+ trackLoggedOp(entry);
}
offset += Buffer.byteLength(rawLine, 'utf8') + 1;
}
diff --git a/server/services/brainSyncLog.test.js b/server/services/brainSyncLog.test.js
index 5369588092..408b8825b6 100644
--- a/server/services/brainSyncLog.test.js
+++ b/server/services/brainSyncLog.test.js
@@ -235,6 +235,33 @@ describe('brainSyncLog', () => {
expect(appendFile).not.toHaveBeenCalled();
});
+ it('skipLogged drops an op the log already carries, through a restart and a compaction (#8316)', async () => {
+ const v1 = { name: 'v1', updatedAt: '2026-01-01T00:00:00.000Z' };
+ const v2 = { name: 'v2', updatedAt: '2026-01-02T00:00:00.000Z' };
+ await appendChanges([
+ { op: 'create', type: 'people', id: 'p1', record: v1, originInstanceId: 'inst-1' },
+ { op: 'update', type: 'people', id: 'p1', record: v2, originInstanceId: 'inst-1' },
+ ]);
+ // Both rebuild the op index: a restart from disk, then a compaction that
+ // drops the superseded v1 entry.
+ await initSyncLog();
+ expect(await compactLog(0, { force: true })).toBe(1);
+ vi.clearAllMocks();
+
+ const relayOfV2 = { op: 'update', type: 'people', id: 'p1', record: v2, originInstanceId: 'peer-b' };
+ expect(await appendChanges([relayOfV2], { skipLogged: true })).toEqual([]);
+ expect(appendFile).not.toHaveBeenCalled();
+
+ // A delete at the same clock is a different op; a repeat within the batch is not.
+ const written = await appendChanges([
+ relayOfV2,
+ { op: 'delete', type: 'people', id: 'p1', record: { updatedAt: v2.updatedAt }, originInstanceId: 'peer-b' },
+ { op: 'delete', type: 'people', id: 'p1', record: { updatedAt: v2.updatedAt }, originInstanceId: 'peer-b' },
+ ], { skipLogged: true });
+ expect(written.map((e) => [e.seq, e.op])).toEqual([[3, 'delete']]);
+ expect(getCurrentSeq()).toBe(3);
+ });
+
it('returns entries with correct shape', async () => {
const entries = await appendChanges([
{ op: 'create', type: 'links', id: 'l1', record: { url: 'http://example.com' }, originInstanceId: 'peer-3' }