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 the sync-log index consistent across crash fragments, failed writes, and seq-less lines (#5441)

[._.]/ Adam Eivy665e255a2f4b
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 4caae55e0c..e3a00ed9f1 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -29,6 +29,9 @@ let offsets = [];
// Byte length of the file as this module last observed it — the offset the next
// appended line will land at.
let fileSize = 0;
+// The file ends mid-line (a crash during a previous append). The next append
+// must terminate that fragment first, or it would swallow the new entry.
+let pendingNewline = false;
let indexLoaded = false;
async function ensureBrainDir() {
@@ -69,10 +72,13 @@ async function loadIndex() {
offsets = [];
fileSize = 0;
currentSeq = 0;
+ pendingNewline = false;
indexLoaded = true;
if (!existsSync(SYNC_LOG_FILE)) return;
- for await (const { text, offset } of streamLines(SYNC_LOG_FILE)) {
+ let terminatedBytes = 0;
+ for await (const { text, offset, byteLength } of streamLines(SYNC_LOG_FILE)) {
+ terminatedBytes = offset + byteLength;
const entry = safeJSONParse(text, null);
if (typeof entry?.seq !== 'number') continue;
offsets.push({ seq: entry.seq, offset });
@@ -81,12 +87,39 @@ async function loadIndex() {
// Real byte size, not the offset past the last complete line: an unterminated
// tail still occupies bytes, so the next append lands after it.
fileSize = (await stat(SYNC_LOG_FILE)).size;
+ pendingNewline = fileSize > terminatedBytes;
}
async function ensureIndex() {
if (!indexLoaded) await loadIndex();
}
+/**
+ * Write `lines` to the log and index them at the offsets they landed on.
+ *
+ * A crash fragment left by a previous append is terminated first, so the new
+ * entries stay on lines of their own — otherwise the fragment would swallow the
+ * first one and a later boot would re-mint its seq for a different record.
+ *
+ * On a failed (possibly partial) write the index is marked stale rather than
+ * advanced: `fileSize` can no longer be trusted, so the next call rescans.
+ */
+async function writeIndexedLines(lines) {
+ const payload = (pendingNewline ? '\n' : '') + lines.map(({ text }) => text).join('\n') + '\n';
+ await appendFile(SYNC_LOG_FILE, payload).catch((err) => {
+ indexLoaded = false;
+ throw err;
+ });
+ if (pendingNewline) {
+ fileSize += 1;
+ pendingNewline = false;
+ }
+ for (const { seq, text } of lines) {
+ offsets.push({ seq, offset: fileSize });
+ fileSize += Buffer.byteLength(text, 'utf8') + 1;
+ }
+}
+
/**
* Index of the first entry with `seq > sinceSeq`, or -1 when none qualifies.
* `offsets` is ascending by construction (seq is monotonic and append-only).
@@ -136,11 +169,7 @@ export async function appendChange(op, type, id, record, originInstanceId) {
originInstanceId,
ts: new Date().toISOString()
};
- const line = JSON.stringify(entry) + '\n';
- await appendFile(SYNC_LOG_FILE, line);
- // Index after the write so a failed append can't skew every later offset.
- offsets.push({ seq: entry.seq, offset: fileSize });
- fileSize += Buffer.byteLength(line, 'utf8');
+ await writeIndexedLines([{ seq: entry.seq, text: JSON.stringify(entry) }]);
return entry;
});
}
@@ -160,17 +189,13 @@ export async function appendChanges(entries) {
for (const { op, type, id, record, originInstanceId } of entries) {
nextSeq++;
const entry = { seq: nextSeq, op, type, id, record, originInstanceId, ts: new Date().toISOString() };
- lines.push(JSON.stringify(entry));
+ lines.push({ seq: nextSeq, text: JSON.stringify(entry) });
results.push(entry);
}
// Reserve sequence numbers before write to avoid reuse on partial failure
// (matches appendChange semantics where currentSeq advances pre-write)
currentSeq = nextSeq;
- await appendFile(SYNC_LOG_FILE, lines.join('\n') + '\n');
- for (const [i, line] of lines.entries()) {
- offsets.push({ seq: results[i].seq, offset: fileSize });
- fileSize += Buffer.byteLength(line, 'utf8') + 1;
- }
+ await writeIndexedLines(lines);
return results;
});
}
@@ -197,7 +222,9 @@ export async function getChangesSince(sinceSeq, limit = 100) {
const changes = [];
for await (const { text } of streamLines(SYNC_LOG_FILE, offsets[start].offset)) {
const entry = safeJSONParse(text, null);
- if (!entry || entry.seq <= sinceSeq) continue;
+ // A line without a numeric seq is unsequenceable — shipping it would set
+ // the peer's cursor to undefined on the next maxSeq.
+ if (typeof entry?.seq !== 'number' || entry.seq <= sinceSeq) continue;
changes.push(entry);
if (changes.length >= limit) break;
}
@@ -237,14 +264,18 @@ export async function compactLog(minSeq) {
const newContent = kept.length > 0 ? kept.map(k => k.line).join('\n') + '\n' : '';
await atomicWrite(SYNC_LOG_FILE, newContent);
- // Rebuild the index from what we just wrote — the offsets all moved.
+ // Rebuild the index from what we just wrote — the offsets all moved. A kept
+ // line without a numeric seq keeps its bytes but stays OUT of the index:
+ // a non-numeric seq in the array would break firstIndexAfter's binary
+ // search and hide every entry before it from peers.
offsets = [];
let offset = 0;
for (const { line, seq } of kept) {
- offsets.push({ seq, offset });
+ if (typeof seq === 'number') offsets.push({ seq, offset });
offset += Buffer.byteLength(line, 'utf8') + 1;
}
fileSize = offset;
+ pendingNewline = false;
indexLoaded = true;
console.log(`🔄 Compacted sync log: dropped ${dropped}, kept ${kept.length}`);
diff --git a/server/services/brainSyncLog.test.js b/server/services/brainSyncLog.test.js
index f37499528b..20df7df6c3 100644
--- a/server/services/brainSyncLog.test.js
+++ b/server/services/brainSyncLog.test.js
@@ -30,7 +30,15 @@ vi.mock('fs', async () => {
return { ...actual, createReadStream: vi.fn(actual.createReadStream) };
});
+// appendFile is spied (not stubbed) so the one-write-per-batch contract stays
+// assertable while the bytes still land on disk for the offset assertions.
+vi.mock('fs/promises', async () => {
+ const actual = await vi.importActual('fs/promises');
+ return { ...actual, appendFile: vi.fn(actual.appendFile) };
+});
+
import { createReadStream } from 'fs';
+import { appendFile } from 'fs/promises';
import {
initSyncLog,
getCurrentSeq,
@@ -42,10 +50,16 @@ import {
const syncLogPath = () => join(getTempRoot(), 'brain', 'sync_log.jsonl');
-/** Byte offset of the (1-based) nth line of the on-disk log. */
+/**
+ * Byte offset at which line n+1 starts, found by locating newlines in the raw
+ * bytes. Deliberately NOT `Buffer.byteLength(line) + 1` summing: that is the
+ * production arithmetic, so it could not catch a shared miscount.
+ */
const lineOffset = (n) => {
- const lines = readFileSync(syncLogPath(), 'utf8').split('\n').slice(0, n);
- return lines.reduce((sum, line) => sum + Buffer.byteLength(line, 'utf8') + 1, 0);
+ const buf = readFileSync(syncLogPath());
+ let at = -1;
+ for (let i = 0; i < n; i++) at = buf.indexOf(0x0a, at + 1);
+ return at + 1;
};
/** `start` passed to the most recent createReadStream call. */
@@ -124,6 +138,15 @@ describe('brainSyncLog', () => {
const result = await getChangesSince(1);
expect(result.changes.map(c => c.seq)).toEqual([2]);
expect(result.changes[0].record).toEqual({ name: 'Alice' });
+
+ // …and the entry must survive a restart. If the append had been
+ // concatenated onto the fragment, the merged line would not parse and
+ // seq 2 would be re-minted for a different record on the next write.
+ await initSyncLog();
+ expect(getCurrentSeq()).toBe(2);
+ const afterRestart = await getChangesSince(1);
+ expect(afterRestart.changes.map(c => c.seq)).toEqual([2]);
+ expect(afterRestart.changes[0].record).toEqual({ name: 'Alice' });
});
});
@@ -175,6 +198,15 @@ describe('brainSyncLog', () => {
expect(getCurrentSeq()).toBe(3);
});
+ it('makes a single appendFile call for the entire batch', async () => {
+ await appendChanges([
+ { op: 'create', type: 'people', id: 'p1', record: { name: 'A' }, originInstanceId: 'inst-1' },
+ { op: 'update', type: 'people', id: 'p2', record: { name: 'B' }, originInstanceId: 'inst-1' }
+ ]);
+
+ expect(appendFile).toHaveBeenCalledTimes(1);
+ });
+
it('writes newline-separated JSON entries ending with newline', async () => {
await appendChanges([
{ op: 'create', type: 'people', id: 'p1', record: { name: 'A' }, originInstanceId: 'inst-1' },
@@ -194,6 +226,7 @@ describe('brainSyncLog', () => {
expect(entries).toEqual([]);
expect(getCurrentSeq()).toBe(0);
+ expect(appendFile).not.toHaveBeenCalled();
});
it('returns entries with correct shape', async () => {
@@ -376,6 +409,19 @@ describe('brainSyncLog', () => {
expect(lastReadStart()).toBe(lineOffset(1));
});
+ it('keeps a retained line with no seq out of the index', async () => {
+ // A seq-less line is retained in the file (it is not below minSeq), but
+ // indexing it would put a non-number into the ascending seq array and
+ // break the binary search — hiding every earlier entry from peers.
+ writeLog('{"seq":1,"op":"create"}\n{"note":"no seq"}\n{"seq":3,"op":"delete"}\n');
+ await initSyncLog();
+
+ expect(await compactLog(0)).toBe(0);
+
+ expect((await getChangesSince(0)).changes.map(c => c.seq)).toEqual([1, 3]);
+ expect((await getChangesSince(1)).changes.map(c => c.seq)).toEqual([3]);
+ });
+
it('keeps appending at the right offset after compaction', async () => {
for (let i = 0; i < 4; i++) {
await appendChange('create', 'people', `p${i}`, { name: `Person ${i}` }, 'inst-1');