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

perf: serve brain sync pulls from a seq→byte-offset index instead of parsing the whole log (#5441)

[._.]/ Adam Eivy5e6e2a233048
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 118a97e5b0..4caae55e0c 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -3,10 +3,15 @@
*
* Append-only JSONL log tracking all brain mutations with monotonic sequence numbers.
* Used for peer-to-peer brain sync protocol.
+ *
+ * A `seq → byte offset` index is kept in module state so a peer pull reads only
+ * the window it asked for. Without it, every `GET /api/brain/sync?since=N` read
+ * and JSON-parsed the whole file — under the same mutex that guards every brain
+ * write — so one lagging peer stalled local writes once per sync cycle (#5441).
*/
-import { readFile, appendFile } from 'fs/promises';
-import { existsSync } from 'fs';
+import { readFile, appendFile, stat } from 'fs/promises';
+import { existsSync, createReadStream } from 'fs';
import { join } from 'path';
import { createMutex } from '../lib/asyncMutex.js';
import { ensureDir, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';
@@ -14,35 +19,97 @@ import { ensureDir, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.j
const DATA_DIR = PATHS.brain;
const SYNC_LOG_FILE = join(DATA_DIR, 'sync_log.jsonl');
+const NEWLINE = 0x0a;
+
const withLock = createMutex();
let currentSeq = 0;
+// Ascending `{ seq, offset }` for every indexed entry. `offset` is the byte
+// position of that entry's line within SYNC_LOG_FILE.
+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;
+let indexLoaded = false;
async function ensureBrainDir() {
await ensureDir(DATA_DIR);
}
/**
- * Load the last sequence number from the JSONL file at startup
+ * Yield every newline-terminated line of `path` starting at byte `start`, with
+ * the byte offset and byte length of each. Operates on raw buffers so multi-byte
+ * UTF-8 split across chunk boundaries can't corrupt the offset arithmetic, and
+ * so the offsets are real file positions rather than character counts.
+ *
+ * A trailing line with no newline (a crash mid-append) is not yielded — it is
+ * not a complete entry.
*/
-export async function initSyncLog() {
- await ensureBrainDir();
- if (!existsSync(SYNC_LOG_FILE)) {
- currentSeq = 0;
- console.log(`🔄 Sync log initialized at seq 0`);
- return;
+async function* streamLines(path, start = 0) {
+ const stream = createReadStream(path, { start });
+ let pending = null;
+ let offset = start;
+ for await (const chunk of stream) {
+ pending = pending ? Buffer.concat([pending, chunk]) : chunk;
+ let nl = pending.indexOf(NEWLINE);
+ while (nl !== -1) {
+ const byteLength = nl + 1;
+ yield { text: pending.subarray(0, nl).toString('utf8'), offset, byteLength };
+ offset += byteLength;
+ pending = pending.subarray(byteLength);
+ nl = pending.indexOf(NEWLINE);
+ }
}
+}
- const content = await readFile(SYNC_LOG_FILE, 'utf-8');
- const lines = content.trim().split('\n').filter(l => l.trim());
- if (lines.length === 0) {
- currentSeq = 0;
- console.log(`🔄 Sync log initialized at seq 0`);
- return;
+/**
+ * Rebuild `offsets` / `fileSize` / `currentSeq` by streaming the log once.
+ * Streaming rather than `readFile` keeps boot off a 2-3x file-size string.
+ */
+async function loadIndex() {
+ offsets = [];
+ fileSize = 0;
+ currentSeq = 0;
+ indexLoaded = true;
+ if (!existsSync(SYNC_LOG_FILE)) return;
+
+ for await (const { text, offset } of streamLines(SYNC_LOG_FILE)) {
+ const entry = safeJSONParse(text, null);
+ if (typeof entry?.seq !== 'number') continue;
+ offsets.push({ seq: entry.seq, offset });
+ currentSeq = entry.seq;
+ }
+ // 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;
+}
+
+async function ensureIndex() {
+ if (!indexLoaded) await loadIndex();
+}
+
+/**
+ * Index of the first entry with `seq > sinceSeq`, or -1 when none qualifies.
+ * `offsets` is ascending by construction (seq is monotonic and append-only).
+ */
+function firstIndexAfter(sinceSeq) {
+ let lo = 0;
+ let hi = offsets.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (offsets[mid].seq > sinceSeq) hi = mid;
+ else lo = mid + 1;
}
+ return lo < offsets.length ? lo : -1;
+}
- const lastEntry = safeJSONParse(lines[lines.length - 1], null);
- currentSeq = lastEntry?.seq ?? 0;
- console.log(`🔄 Sync log initialized at seq ${currentSeq} (${lines.length} entries)`);
+/**
+ * Load the last sequence number from the JSONL file at startup
+ */
+export async function initSyncLog() {
+ await ensureBrainDir();
+ indexLoaded = false;
+ await loadIndex();
+ console.log(`🔄 Sync log initialized at seq ${currentSeq} (${offsets.length} entries)`);
}
/**
@@ -58,6 +125,7 @@ export function getCurrentSeq() {
export async function appendChange(op, type, id, record, originInstanceId) {
return withLock(async () => {
await ensureBrainDir();
+ await ensureIndex();
currentSeq++;
const entry = {
seq: currentSeq,
@@ -68,7 +136,11 @@ export async function appendChange(op, type, id, record, originInstanceId) {
originInstanceId,
ts: new Date().toISOString()
};
- await appendFile(SYNC_LOG_FILE, JSON.stringify(entry) + '\n');
+ 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');
return entry;
});
}
@@ -80,6 +152,7 @@ export async function appendChanges(entries) {
if (!entries?.length) return [];
return withLock(async () => {
await ensureBrainDir();
+ await ensureIndex();
const startSeq = currentSeq;
const results = [];
const lines = [];
@@ -94,6 +167,10 @@ export async function appendChanges(entries) {
// (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;
+ }
return results;
});
}
@@ -101,29 +178,32 @@ export async function appendChanges(entries) {
/**
* Get changes since a given sequence number
*/
-// Mutex-guarded to prevent reading a partially-written file during compaction.
+// Mutex-guarded so a concurrent compactLog() can't move offsets under the read.
// Bounded by periodic compactLog() in syncOrchestrator.
export async function getChangesSince(sinceSeq, limit = 100) {
return withLock(async () => {
await ensureBrainDir();
+ await ensureIndex();
if (!existsSync(SYNC_LOG_FILE)) {
return { changes: [], maxSeq: currentSeq, hasMore: false };
}
- const content = await readFile(SYNC_LOG_FILE, 'utf-8');
- const lines = content.trim().split('\n').filter(l => l.trim());
- const changes = [];
+ const start = firstIndexAfter(sinceSeq);
+ const lastIndexedSeq = offsets.length > 0 ? offsets[offsets.length - 1].seq : null;
+ if (start === -1) {
+ return { changes: [], maxSeq: sinceSeq, hasMore: false };
+ }
- for (const line of lines) {
- const entry = safeJSONParse(line, null);
+ 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;
changes.push(entry);
if (changes.length >= limit) break;
}
const maxSeq = changes.length > 0 ? changes[changes.length - 1].seq : sinceSeq;
- const lastLineEntry = lines.length > 0 ? safeJSONParse(lines[lines.length - 1], null) : null;
- const hasMore = lastLineEntry ? maxSeq < lastLineEntry.seq : false;
+ const hasMore = lastIndexedSeq !== null ? maxSeq < lastIndexedSeq : false;
return { changes, maxSeq, hasMore };
});
@@ -135,6 +215,9 @@ export async function getChangesSince(sinceSeq, limit = 100) {
export async function compactLog(minSeq) {
return withLock(async () => {
await ensureBrainDir();
+ // Load first: the rebuild below marks the index loaded, so skipping this
+ // would strand currentSeq at 0 on an install that compacted before booting.
+ await ensureIndex();
if (!existsSync(SYNC_LOG_FILE)) return 0;
const content = await readFile(SYNC_LOG_FILE, 'utf-8');
@@ -148,11 +231,22 @@ export async function compactLog(minSeq) {
dropped++;
continue;
}
- kept.push(line);
+ kept.push({ line, seq: entry.seq });
}
- const newContent = kept.length > 0 ? kept.join('\n') + '\n' : '';
+ 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.
+ offsets = [];
+ let offset = 0;
+ for (const { line, seq } of kept) {
+ offsets.push({ seq, offset });
+ offset += Buffer.byteLength(line, 'utf8') + 1;
+ }
+ fileSize = offset;
+ indexLoaded = true;
+
console.log(`🔄 Compacted sync log: dropped ${dropped}, kept ${kept.length}`);
return dropped;
});
diff --git a/server/services/brainSyncLog.test.js b/server/services/brainSyncLog.test.js
index 348943ccca..f37499528b 100644
--- a/server/services/brainSyncLog.test.js
+++ b/server/services/brainSyncLog.test.js
@@ -1,30 +1,36 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-// Mock fs/promises and fs
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(),
- appendFile: vi.fn(),
- mkdir: vi.fn()
-}));
-vi.mock('fs', () => ({
- existsSync: vi.fn()
-}));
-vi.mock('../lib/asyncMutex.js', () => ({
- createMutex: () => async (fn) => fn()
-}));
-vi.mock('../lib/fileUtils.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
- ensureDir: vi.fn(),
- atomicWrite: vi.fn().mockResolvedValue(undefined),
- safeJSONParse: (str, fallback) => {
- try { return JSON.parse(str); } catch { return fallback; }
- },
- PATHS: { brain: '/tmp/test/brain' }
-}));
-
-import { readFile, appendFile, mkdir } from 'fs/promises';
-import { existsSync } from 'fs';
-import { atomicWrite } from '../lib/fileUtils.js';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+// The suite runs against a REAL temp data dir rather than a mocked `readFile`,
+// because the sync log is now served through a seq → byte-offset index: the
+// offsets are only meaningful against real bytes on disk (#5441).
+//
+// The temp dir is allocated lazily on first PATHS read — brainSyncLog captures
+// PATHS.brain at import time, before any top-level test assignment would run.
+// `var` + a function declaration are hoisted (no TDZ), so the hoisted vi.mock
+// factory can reference them safely.
+var tempRoot; // eslint-disable-line no-var
+function getTempRoot() {
+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'brainsynclog-test-'));
+ return tempRoot;
+}
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => getTempRoot() });
+});
+
+// Spy on createReadStream so the tests can assert WHICH bytes were read — that
+// is the whole point of the index, and it is invisible from the return value.
+vi.mock('fs', async () => {
+ const actual = await vi.importActual('fs');
+ return { ...actual, createReadStream: vi.fn(actual.createReadStream) };
+});
+
+import { createReadStream } from 'fs';
import {
initSyncLog,
getCurrentSeq,
@@ -34,32 +40,48 @@ import {
compactLog
} from './brainSyncLog.js';
+const syncLogPath = () => join(getTempRoot(), 'brain', 'sync_log.jsonl');
+
+/** Byte offset of the (1-based) nth line of the on-disk log. */
+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);
+};
+
+/** `start` passed to the most recent createReadStream call. */
+const lastReadStart = () => {
+ const calls = createReadStream.mock.calls;
+ return calls[calls.length - 1]?.[1]?.start;
+};
+
+const writeLog = (content) => {
+ mkdirSync(join(getTempRoot(), 'brain'), { recursive: true });
+ writeFileSync(syncLogPath(), content);
+};
+
+afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });
+
describe('brainSyncLog', () => {
- beforeEach(() => {
+ beforeEach(async () => {
+ rmSync(syncLogPath(), { force: true });
+ await initSyncLog();
vi.clearAllMocks();
- existsSync.mockReturnValue(true);
});
describe('getCurrentSeq', () => {
- it('returns 0 by default', () => {
- // getCurrentSeq returns module-level state; after import it starts at 0
- // (or whatever initSyncLog set it to)
- expect(typeof getCurrentSeq()).toBe('number');
+ it('returns 0 for a fresh log', () => {
+ expect(getCurrentSeq()).toBe(0);
});
});
describe('initSyncLog', () => {
it('sets seq to 0 when file does not exist', async () => {
- existsSync.mockReturnValue(false);
- mkdir.mockResolvedValue();
-
await initSyncLog();
expect(getCurrentSeq()).toBe(0);
});
it('parses last line for seq', async () => {
- existsSync.mockReturnValue(true);
- readFile.mockResolvedValue(
+ writeLog(
'{"seq":1,"op":"create","type":"people","id":"a"}\n{"seq":5,"op":"update","type":"ideas","id":"b"}\n'
);
@@ -68,32 +90,44 @@ describe('brainSyncLog', () => {
});
it('handles empty file content', async () => {
- existsSync.mockReturnValue(true);
- readFile.mockResolvedValue(' \n \n');
+ writeLog(' \n \n');
await initSyncLog();
expect(getCurrentSeq()).toBe(0);
});
it('handles malformed last line gracefully', async () => {
- existsSync.mockReturnValue(true);
- readFile.mockResolvedValue('not-json\n');
+ writeLog('not-json\n');
await initSyncLog();
expect(getCurrentSeq()).toBe(0);
});
- });
- describe('appendChange', () => {
- beforeEach(async () => {
- // Reset seq to 0
- existsSync.mockReturnValue(false);
- mkdir.mockResolvedValue();
+ it('recovers the last complete seq when the file ends in a partial line', async () => {
+ // A crash mid-append leaves an unterminated tail; boot must still report
+ // the last entry that was fully written.
+ writeLog('{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n{"seq":3,"op":"del');
+
await initSyncLog();
- existsSync.mockReturnValue(true);
- appendFile.mockResolvedValue();
+ expect(getCurrentSeq()).toBe(2);
});
+ it('appends after an unterminated tail without reusing its byte range', async () => {
+ writeLog('{"seq":1,"op":"create"}\n{"seq":2,"op":"upd');
+ await initSyncLog();
+
+ // seq 2 was never fully written, so it is not indexed and not reserved.
+ const entry = await appendChange('create', 'people', 'p1', { name: 'Alice' }, 'inst-1');
+ expect(entry.seq).toBe(2);
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(1);
+ expect(result.changes.map(c => c.seq)).toEqual([2]);
+ expect(result.changes[0].record).toEqual({ name: 'Alice' });
+ });
+ });
+
+ describe('appendChange', () => {
it('increments seq monotonically', async () => {
const e1 = await appendChange('create', 'people', 'id1', { name: 'Alice' }, 'inst-1');
const e2 = await appendChange('update', 'people', 'id1', { name: 'Bob' }, 'inst-1');
@@ -119,8 +153,7 @@ describe('brainSyncLog', () => {
it('appends JSON line to file', async () => {
await appendChange('delete', 'projects', 'p-1', null, 'inst-1');
- expect(appendFile).toHaveBeenCalledTimes(1);
- const written = appendFile.mock.calls[0][1];
+ const written = readFileSync(syncLogPath(), 'utf8');
expect(written.endsWith('\n')).toBe(true);
const parsed = JSON.parse(written.trim());
expect(parsed.op).toBe('delete');
@@ -128,14 +161,6 @@ describe('brainSyncLog', () => {
});
describe('appendChanges', () => {
- beforeEach(async () => {
- existsSync.mockReturnValue(false);
- mkdir.mockResolvedValue();
- await initSyncLog();
- existsSync.mockReturnValue(true);
- appendFile.mockResolvedValue();
- });
-
it('increments seq across all entries in the batch', async () => {
const entries = await appendChanges([
{ op: 'create', type: 'people', id: 'p1', record: { name: 'A' }, originInstanceId: 'inst-1' },
@@ -150,22 +175,13 @@ 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' },
{ op: 'delete', type: 'ideas', id: 'i1', record: null, originInstanceId: 'inst-2' }
]);
- const written = appendFile.mock.calls[0][1];
+ const written = readFileSync(syncLogPath(), 'utf8');
expect(written.endsWith('\n')).toBe(true);
const lines = written.trim().split('\n');
expect(lines).toHaveLength(2);
@@ -177,12 +193,12 @@ describe('brainSyncLog', () => {
const entries = await appendChanges([]);
expect(entries).toEqual([]);
- expect(appendFile).not.toHaveBeenCalled();
+ expect(getCurrentSeq()).toBe(0);
});
it('returns entries with correct shape', async () => {
const entries = await appendChanges([
- { op: 'create', type: 'links', id: 'l1', record: { url: 'http://x' }, originInstanceId: 'peer-3' }
+ { op: 'create', type: 'links', id: 'l1', record: { url: 'http://example.com' }, originInstanceId: 'peer-3' }
]);
expect(entries[0]).toMatchObject({
@@ -190,7 +206,7 @@ describe('brainSyncLog', () => {
op: 'create',
type: 'links',
id: 'l1',
- record: { url: 'http://x' },
+ record: { url: 'http://example.com' },
originInstanceId: 'peer-3',
ts: expect.any(String)
});
@@ -198,14 +214,11 @@ describe('brainSyncLog', () => {
});
describe('getChangesSince', () => {
- beforeEach(() => {
- existsSync.mockReturnValue(true);
- });
-
it('filters entries by sinceSeq', async () => {
- readFile.mockResolvedValue(
+ writeLog(
['{"seq":1,"op":"create"}', '{"seq":2,"op":"update"}', '{"seq":3,"op":"delete"}'].join('\n') + '\n'
);
+ await initSyncLog();
const result = await getChangesSince(1);
expect(result.changes).toHaveLength(2);
@@ -214,10 +227,10 @@ describe('brainSyncLog', () => {
});
it('respects limit parameter', async () => {
- const lines = Array.from({ length: 10 }, (_, i) =>
- JSON.stringify({ seq: i + 1, op: 'create' })
- ).join('\n') + '\n';
- readFile.mockResolvedValue(lines);
+ writeLog(
+ Array.from({ length: 10 }, (_, i) => JSON.stringify({ seq: i + 1, op: 'create' })).join('\n') + '\n'
+ );
+ await initSyncLog();
const result = await getChangesSince(0, 3);
expect(result.changes).toHaveLength(3);
@@ -225,7 +238,8 @@ describe('brainSyncLog', () => {
});
it('sets hasMore=false when all changes returned', async () => {
- readFile.mockResolvedValue('{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n');
+ writeLog('{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n');
+ await initSyncLog();
const result = await getChangesSince(0, 100);
expect(result.changes).toHaveLength(2);
@@ -233,42 +247,146 @@ describe('brainSyncLog', () => {
});
it('returns empty when file does not exist', async () => {
- existsSync.mockReturnValue(false);
-
const result = await getChangesSince(0);
expect(result.changes).toHaveLength(0);
expect(result.hasMore).toBe(false);
});
it('returns maxSeq from last returned change', async () => {
- readFile.mockResolvedValue('{"seq":5,"op":"create"}\n{"seq":10,"op":"update"}\n');
+ writeLog('{"seq":5,"op":"create"}\n{"seq":10,"op":"update"}\n');
+ await initSyncLog();
const result = await getChangesSince(0, 1);
expect(result.maxSeq).toBe(5);
});
+
+ it('reads only from the first entry after sinceSeq, never the head of the file', async () => {
+ for (let i = 0; i < 6; i++) {
+ await appendChange('create', 'people', `p${i}`, { name: `Person ${i}` }, 'inst-1');
+ }
+ const expectedStart = lineOffset(4);
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(4);
+
+ expect(result.changes.map(c => c.seq)).toEqual([5, 6]);
+ expect(createReadStream).toHaveBeenCalledTimes(1);
+ expect(lastReadStart()).toBe(expectedStart);
+ expect(expectedStart).toBeGreaterThan(0);
+ });
+
+ it('does not read the file at all when nothing is newer than sinceSeq', async () => {
+ await appendChange('create', 'people', 'p1', { name: 'Alice' }, 'inst-1');
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(1);
+
+ expect(result).toEqual({ changes: [], maxSeq: 1, hasMore: false });
+ expect(createReadStream).not.toHaveBeenCalled();
+ });
+
+ it('keeps offsets correct across multi-byte UTF-8 records', async () => {
+ await appendChange('create', 'captures', 'c1', { capturedText: '🧠 first — naïve' }, 'inst-1');
+ await appendChange('create', 'captures', 'c2', { capturedText: '🚀 second — résumé' }, 'inst-1');
+ await appendChange('create', 'captures', 'c3', { capturedText: '🎯 third' }, 'inst-1');
+ const expectedStart = lineOffset(1);
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(1);
+
+ expect(lastReadStart()).toBe(expectedStart);
+ expect(result.changes.map(c => c.seq)).toEqual([2, 3]);
+ expect(result.changes[0].record.capturedText).toBe('🚀 second — résumé');
+ expect(result.changes[1].record.capturedText).toBe('🎯 third');
+ });
+
+ it('serves entries appended after the index was built', async () => {
+ await appendChanges([
+ { op: 'create', type: 'people', id: 'p1', record: { name: 'A' }, originInstanceId: 'inst-1' },
+ { op: 'create', type: 'people', id: 'p2', record: { name: 'B' }, originInstanceId: 'inst-1' }
+ ]);
+ await appendChange('update', 'people', 'p2', { name: 'B2' }, 'inst-1');
+ const expectedStart = lineOffset(2);
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(2);
+
+ expect(lastReadStart()).toBe(expectedStart);
+ expect(result.changes.map(c => c.seq)).toEqual([3]);
+ expect(result.maxSeq).toBe(3);
+ expect(result.hasMore).toBe(false);
+ });
+
+ it('serializes concurrent appends so seqs and offsets stay consistent', async () => {
+ const appended = await Promise.all(
+ Array.from({ length: 5 }, (_, i) =>
+ appendChange('create', 'people', `p${i}`, { name: `Person ${i}` }, 'inst-1')
+ )
+ );
+
+ expect(appended.map(e => e.seq).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5]);
+
+ vi.clearAllMocks();
+ const all = await getChangesSince(0);
+ expect(all.changes.map(c => c.seq)).toEqual([1, 2, 3, 4, 5]);
+
+ // Every indexed offset must land exactly on its line's first byte.
+ for (let n = 0; n < 5; n++) {
+ vi.clearAllMocks();
+ const window = await getChangesSince(n);
+ expect(lastReadStart()).toBe(lineOffset(n));
+ expect(window.changes[0].seq).toBe(n + 1);
+ }
+ });
});
describe('compactLog', () => {
it('drops entries below minSeq', async () => {
- existsSync.mockReturnValue(true);
- readFile.mockResolvedValue(
- '{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n{"seq":3,"op":"delete"}\n'
- );
- atomicWrite.mockResolvedValue();
+ writeLog('{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n{"seq":3,"op":"delete"}\n');
+ await initSyncLog();
const dropped = await compactLog(2);
expect(dropped).toBe(1);
- expect(atomicWrite).toHaveBeenCalledTimes(1);
- const written = atomicWrite.mock.calls[0][1];
+ const written = readFileSync(syncLogPath(), 'utf8');
expect(written).toContain('"seq":2');
expect(written).toContain('"seq":3');
expect(written).not.toContain('"seq":1,');
});
it('returns 0 when file does not exist', async () => {
- existsSync.mockReturnValue(false);
const dropped = await compactLog(5);
expect(dropped).toBe(0);
});
+
+ it('serves reads from the rebuilt index immediately after compaction', async () => {
+ for (let i = 0; i < 5; i++) {
+ await appendChange('create', 'people', `p${i}`, { name: `Person ${i}` }, 'inst-1');
+ }
+
+ expect(await compactLog(3)).toBe(2);
+
+ vi.clearAllMocks();
+ const fromZero = await getChangesSince(0);
+ expect(fromZero.changes.map(c => c.seq)).toEqual([3, 4, 5]);
+ expect(lastReadStart()).toBe(0);
+
+ vi.clearAllMocks();
+ const fromThree = await getChangesSince(3);
+ expect(fromThree.changes.map(c => c.seq)).toEqual([4, 5]);
+ expect(lastReadStart()).toBe(lineOffset(1));
+ });
+
+ 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');
+ }
+ await compactLog(3);
+ await appendChange('create', 'people', 'p5', { name: 'Person 5' }, 'inst-1');
+
+ vi.clearAllMocks();
+ const result = await getChangesSince(4);
+ expect(lastReadStart()).toBe(lineOffset(2));
+ expect(result.changes.map(c => c.seq)).toEqual([5]);
+ });
});
});