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: resume bounded Beeper account sweeps across runs (#8681)

[._.]/ Adam Eivy90d3b7ec3c88
diff --git a/scripts/migrations/413-beeper-account-continuation.js b/scripts/migrations/413-beeper-account-continuation.js
new file mode 100644
index 0000000000..41cd6d12ad
--- /dev/null
+++ b/scripts/migrations/413-beeper-account-continuation.js
@@ -0,0 +1,11 @@
+/**
+ * Register the machine-local Beeper account enumeration checkpoint (#8681).
+ * The file migration runner precedes DB initialization. As in migration 336,
+ * ensureSchema applies the additive, idempotent ALTER at boot; init-db.sql
+ * includes the column for fresh installs. NULL starts the walk at the head.
+ */
+export default {
+ async up() {
+ console.log('🫧 Beeper account continuation: chat_cursor added by ensureSchema at boot');
+ },
+};
diff --git a/server/lib/db/schema/beeper.js b/server/lib/db/schema/beeper.js
index 6a9c838d40..8e14fac5a4 100644
--- a/server/lib/db/schema/beeper.js
+++ b/server/lib/db/schema/beeper.js
@@ -29,10 +29,13 @@ export const beeperDdl = [
status TEXT NOT NULL DEFAULT '',
bridge_id TEXT NOT NULL DEFAULT '',
last_seen_at TIMESTAMPTZ,
+ chat_cursor TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ `ALTER TABLE beeper_accounts ADD COLUMN IF NOT EXISTS chat_cursor TEXT`,
+
// The ONE Beeper credential this install holds (#31). AES-256-GCM ciphertext
// via `server/lib/vaultCrypto.js` — never `settings.json`, never a plaintext
// file, never a log line. Single-row by construction (`id = 'default'`),
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 0be3ef6cfa..90d7aac2e2 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1732,6 +1732,7 @@ CREATE TABLE IF NOT EXISTS beeper_accounts (
status TEXT NOT NULL DEFAULT '',
bridge_id TEXT NOT NULL DEFAULT '',
last_seen_at TIMESTAMPTZ,
+ chat_cursor TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
diff --git a/server/services/beeperSync.db.test.js b/server/services/beeperSync.db.test.js
index fbfcbc558b..04851abc38 100644
--- a/server/services/beeperSync.db.test.js
+++ b/server/services/beeperSync.db.test.js
@@ -155,6 +155,28 @@ afterAll(async () => {
});
describe.skipIf(!runDb)('beeperSync against Postgres', () => {
+ it('persists account continuation across sweeps and resets it at end of list', async () => {
+ const visits = [];
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') {
+ const page = Number(parsed.searchParams.get('cursor') || 1);
+ visits.push(page);
+ return jsonResponse({ items: [], hasMore: page < 21, oldestCursor: String(page + 1) });
+ }
+ throw new Error('Unexpected endpoint');
+ }));
+ expect(await runBeeperSweep()).toMatchObject({ unfinishedAccounts: 1, enumerationComplete: false });
+ const checkpoint = await query('SELECT chat_cursor FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);
+ expect(checkpoint.rows[0].chat_cursor).toBe('21');
+ expect(await runBeeperSweep()).toMatchObject({ unfinishedAccounts: 0, enumerationComplete: true });
+ expect(visits.slice(20)).toEqual([1, 21]);
+ const completed = await query('SELECT chat_cursor FROM beeper_accounts WHERE account_id = $1', [ACCOUNT_ID]);
+ expect(completed.rows[0].chat_cursor).toBeNull();
+ });
+
it('writes account, conversation, message, attachment and cursor rows in one sweep', async () => {
installFetch({
chats: { items: [chatFixture('2026-09-02T10:00:00.000Z')], hasMore: false },
diff --git a/server/services/beeperSync.js b/server/services/beeperSync.js
index 380eab36ab..3a2a34870b 100644
--- a/server/services/beeperSync.js
+++ b/server/services/beeperSync.js
@@ -684,7 +684,7 @@ async function sweepChat({
* 502s on its messages, say) sitting at the top of the newest-first list would
* abort this account's whole walk on every single pass and starve every chat
* below it indefinitely. Its cursor and watermark are untouched by the failed
- * transaction, so it is retried next pass either way.
+ * transaction, so it is retried on a later traversal.
*
* A CAUGHT-UP CHAT DOES NOT END THE WALK, and that is the whole reason the
* truncation contract works. `sweepChat` withholds the watermark from a chat
@@ -698,20 +698,37 @@ async function sweepChat({
* to the top of the list.
*
* A caught-up page cannot terminate the walk either: older pages can contain
- * truncated, failed, or purged chats. Walk to the server's end or the page cap.
+ * truncated, failed, or purged chats. Persist progress at the page cap and
+ * resume next run, reserving one page to refresh the head. End-of-list resets
+ * the checkpoint so failed chats remain reachable on subsequent traversals.
*/
async function sweepAccount(account, clientOptions, observedAt, personIndex) {
const cursors = await readAccountCursors(account.accountId);
- let cursor;
+ const checkpoint = await query('SELECT chat_cursor FROM beeper_accounts WHERE account_id = $1', [account.accountId]);
+ let cursor = checkpoint.rows[0]?.chat_cursor || undefined;
+ let refreshHead = Boolean(cursor);
+ let continuationPending = true;
+ let cursorRestarts = 0;
let chatsSwept = 0;
let messagesWritten = 0;
let failedChats = 0;
for (let pageIndex = 0; pageIndex < MAX_CHAT_PAGES_PER_ACCOUNT; pageIndex++) {
+ const requestCursor = refreshHead ? undefined : cursor;
// eslint-disable-next-line no-await-in-loop -- cursor pagination is inherently sequential
const page = await listChatsPage({
- cursor, direction: 'before', accountIDs: [account.accountId], ...clientOptions,
+ cursor: requestCursor, direction: 'before', accountIDs: [account.accountId], ...clientOptions,
+ }).catch(async (err) => {
+ // A rejected pagination request can be retried from the head. Authentication,
+ // transport and server failures must retain the checkpoint, not erase it.
+ if (!requestCursor || !(err instanceof BeeperApiError) || ![400, 410, 422].includes(err.status)) throw err;
+ await query('UPDATE beeper_accounts SET chat_cursor = $2 WHERE account_id = $1', [account.accountId, null]);
+ cursor = undefined;
+ cursorRestarts++;
+ console.warn(`⚠️ ${LOG_PREFIX}: restarting rejected account pagination`);
+ return null;
});
+ if (!page) continue;
assertPagedShape(page, '/v1/chats');
for (const chat of page.items) {
@@ -730,12 +747,28 @@ async function sweepAccount(account, clientOptions, observedAt, personIndex) {
messagesWritten += result.messages;
}
- if (!page.hasMore) break;
- if (!page.oldestCursor || page.oldestCursor === cursor) break;
- cursor = page.oldestCursor;
+ // The head refresh spends one page of the same budget but never overwrites
+ // the historical checkpoint. Failed chats keep their own old watermarks and
+ // are retried on a later traversal without starving the rest of the account.
+ if (refreshHead) {
+ refreshHead = false;
+ continue;
+ }
+ if (page.hasMore && (!page.oldestCursor || page.oldestCursor === cursor)) {
+ throw new BeeperApiError('Beeper account pagination stalled without a usable next cursor', {
+ code: 'MALFORMED_RESPONSE', status: 502,
+ });
+ }
+ cursor = page.hasMore ? page.oldestCursor : null;
+ // Only advance after all work on this page was attempted. A crash or write
+ // failure replays this page through the existing idempotent message writes.
+ // eslint-disable-next-line no-await-in-loop -- checkpoint follows page work
+ await query('UPDATE beeper_accounts SET chat_cursor = $2 WHERE account_id = $1', [account.accountId, cursor]);
+ continuationPending = Boolean(page.hasMore);
+ if (!continuationPending) break;
}
- return { chatsSwept, messagesWritten, failedChats };
+ return { chatsSwept, messagesWritten, failedChats, continuationPending, cursorRestarts };
}
// A per-run re-entrancy guard: one sweep at a time, process-wide. The timer,
@@ -795,6 +828,8 @@ async function executeSweep(reason) {
let accountsDone = 0;
let failedAccounts = 0;
let failedChats = 0;
+ let unfinishedAccounts = 0;
+ let cursorRestarts = 0;
for (const account of accounts) {
// eslint-disable-next-line no-await-in-loop -- accounts are swept in order; each owns its own cursors
const result = await sweepAccount(account, clientOptions, observedAt, personIndex).catch((err) => {
@@ -806,6 +841,8 @@ async function executeSweep(reason) {
chats += result.chatsSwept;
messages += result.messagesWritten;
failedChats += result.failedChats;
+ unfinishedAccounts += Number(result.continuationPending);
+ cursorRestarts += result.cursorRestarts;
}
// #80: one account done, whether it succeeded or failed — "N of M" counts
// accounts attempted, not accounts that mirrored something.
@@ -835,6 +872,9 @@ async function executeSweep(reason) {
messages,
failedAccounts,
failedChats,
+ unfinishedAccounts,
+ enumerationComplete: unfinishedAccounts === 0 && failedAccounts === 0,
+ cursorRestarts,
durationMs,
};
} finally {
diff --git a/server/services/beeperSync.test.js b/server/services/beeperSync.test.js
index 5c1e08fb05..f5dd321154 100644
--- a/server/services/beeperSync.test.js
+++ b/server/services/beeperSync.test.js
@@ -15,10 +15,17 @@ const txCalls = [];
// rather than inside it.
const txWrites = [];
let storedCursorRows = [];
+let accountCheckpoint = null;
+let checkpointFailure = false;
let txFailPattern = null;
const queryMock = vi.fn(async (text, params) => {
dbCalls.push({ text, params });
+ if (/SELECT chat_cursor/.test(text)) return { rows: [{ chat_cursor: accountCheckpoint }] };
+ if (/UPDATE beeper_accounts SET chat_cursor/.test(text)) {
+ if (checkpointFailure) throw new Error('checkpoint write interrupted');
+ accountCheckpoint = params[1];
+ }
if (/FROM beeper_sync_cursors/.test(text)) return { rows: storedCursorRows };
if (/INSERT INTO beeper_conversations/.test(text)) return { rows: [{ id: `conv-${params[2]}` }] };
return { rows: [] };
@@ -132,6 +139,8 @@ beforeEach(() => {
txWrites.length = 0;
fetchedUrls.length = 0;
storedCursorRows = [];
+ accountCheckpoint = null;
+ checkpointFailure = false;
txFailPattern = null;
queryMock.mockClear();
withTransactionMock.mockClear();
@@ -1110,3 +1119,99 @@ describe('normalizers', () => {
expect(chatNeedsSweep({ lastActivity: '2026-09-01T00:00:00.000Z' }, { lastActivity: '2026-09-01T00:00:00.000Z' })).toBe(false);
});
});
+
+// Public sweep regressions: the persisted checkpoint outlives a service reload,
+// while the wire still receives a bounded newest-first head refresh each run.
+describe('account enumeration continuation', () => {
+ function installPagedAccount({ pages = 21, rejectCursor, failChat } = {}) {
+ const visits = [];
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const parsed = new URL(url);
+ if (parsed.pathname === '/v1/accounts') return jsonResponse(ACCOUNTS);
+ if (parsed.pathname === '/v1/bridges') return jsonResponse(BRIDGES);
+ if (parsed.pathname === '/v1/chats') {
+ const cursor = parsed.searchParams.get('cursor');
+ const page = cursor ? Number(cursor) : 1;
+ visits.push(page);
+ if (rejectCursor && cursor === rejectCursor.cursor) {
+ return { ok: false, status: rejectCursor.status, text: async () => JSON.stringify({ message: 'Invalid cursor' }) };
+ }
+ return jsonResponse({
+ items: [{ id: `chat-${page}`, accountID: 'acct-a', lastActivity: '2026-09-02T10:00:00.000Z', participants: { items: [] } }],
+ hasMore: page < pages, oldestCursor: String(page + 1),
+ });
+ }
+ const id = decodeURIComponent(parsed.pathname.split('/')[3]);
+ if (id === failChat) throw new Error('message fetch interrupted');
+ return jsonResponse({ items: [{ id: `msg-${id}`, chatID: id, accountID: 'acct-a', text: 'Example body' }], hasMore: false, newestCursor: `done-${id}` });
+ }));
+ return visits;
+ }
+
+ it.each([false, true])('reaches page 21 after restart with an existing backlog=%s and refreshes new head activity', async (backlog) => {
+ storedCursorRows = Array.from({ length: 20 }, (_, i) => ({
+ chat_id: `chat-${i + 1}`, cursor: `caught-up-${i + 1}`, last_activity: '2026-09-02T10:00:00.000Z',
+ }));
+ if (backlog) storedCursorRows.push({ chat_id: 'chat-21', cursor: 'unfinished', last_activity: '2026-08-01T00:00:00.000Z' });
+ const visits = installPagedAccount();
+ expect(await runBeeperSweep()).toMatchObject({ unfinishedAccounts: 1, enumerationComplete: false, messages: 0 });
+ expect(accountCheckpoint).toBe('21');
+ expect(visits).toEqual(Array.from({ length: 20 }, (_, i) => i + 1));
+ storedCursorRows[0].last_activity = '2026-08-01T00:00:00.000Z';
+ vi.resetModules();
+ const restarted = await import('./beeperSync.js');
+ expect(await restarted.runBeeperSweep()).toMatchObject({ unfinishedAccounts: 0, enumerationComplete: true, messages: 2 });
+ expect(visits.slice(20)).toEqual([1, 21]);
+ expect(accountCheckpoint).toBeNull();
+ expect(txWrites.filter(({ text }) => text.includes('INSERT INTO beeper_messages')).map(({ params }) => params[0])).toContain('msg-chat-21');
+ });
+
+ it('retains a failed page checkpoint and retries it on the next run', async () => {
+ accountCheckpoint = '21';
+ installPagedAccount({ rejectCursor: { cursor: '21', status: 404 } });
+ await expect(runBeeperSweep()).rejects.toMatchObject({ code: 'SWEEP_FAILED' });
+ expect(accountCheckpoint).toBe('21');
+ const visits = installPagedAccount();
+ expect(await runBeeperSweep()).toMatchObject({ enumerationComplete: true });
+ expect(visits).toEqual([1, 21]);
+ });
+
+ it('restarts a rejected cursor explicitly within the page budget', async () => {
+ accountCheckpoint = '99';
+ const visits = installPagedAccount({ rejectCursor: { cursor: '99', status: 400 } });
+ expect(await runBeeperSweep()).toMatchObject({ cursorRestarts: 1, enumerationComplete: false });
+ expect(visits).toHaveLength(20);
+ expect(visits.slice(0, 3)).toEqual([1, 99, 1]);
+ expect(accountCheckpoint).toBe('19');
+ });
+
+ it('replays committed page work after a checkpoint write interruption', async () => {
+ checkpointFailure = true;
+ installPagedAccount({ pages: 1 });
+ await expect(runBeeperSweep()).rejects.toMatchObject({ code: 'SWEEP_FAILED' });
+ expect(accountCheckpoint).toBeNull();
+ checkpointFailure = false;
+ expect(await runBeeperSweep()).toMatchObject({ enumerationComplete: true, messages: 1 });
+ const writes = txWrites.filter(({ text }) => text.includes('INSERT INTO beeper_messages'));
+ expect(writes).toHaveLength(2);
+ expect(writes[0].params[0]).toBe(writes[1].params[0]);
+ expect(writes.every(({ text }) => text.includes('ON CONFLICT'))).toBe(true);
+ });
+
+ it('revisits failed chats after finishing the traversal instead of permanently skipping them', async () => {
+ installPagedAccount({ failChat: 'chat-2' });
+ expect(await runBeeperSweep()).toMatchObject({ failedChats: 1, unfinishedAccounts: 1 });
+ const visits = installPagedAccount();
+ await runBeeperSweep();
+ await runBeeperSweep();
+ expect(visits.slice(0, 4)).toEqual([1, 21, 1, 2]);
+ expect(txWrites.some(({ text, params }) => text.includes('INSERT INTO beeper_messages') && params[0] === 'msg-chat-2')).toBe(true);
+ });
+
+ it('reports a stalled hasMore page as a failure and preserves its checkpoint', async () => {
+ accountCheckpoint = '21';
+ installFetch({ chatPages: [{ items: [], hasMore: true, oldestCursor: '21' }] });
+ await expect(runBeeperSweep()).rejects.toMatchObject({ code: 'SWEEP_FAILED' });
+ expect(accountCheckpoint).toBe('21');
+ });
+});