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

address review (codex): repair alias participants before persisting the learned set

[._.]/ Adam Eivy18fe5866cae7
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 7665c31bc7..963fea609d 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -270,10 +270,24 @@ export async function syncAccount(accountId, io, options = {}) {
// so repair exactly those rows once, right when the set changes.
const previousAliases = account.sendAsAliases;
account.sendAsAliases = sendAsAliases;
- await updateSendAsAliases(accountId, sendAsAliases).catch((err) =>
- console.error(`📧 Send-as alias persist failed for account ${accountId}: ${err.message}`));
- await repairActivityAliasParticipants(account, previousAliases, sendAsAliases).catch((err) =>
- console.error(`🗓️ Activity alias backfill failed for account ${accountId}: ${err.message}`));
+ // ORDER IS LOAD-BEARING: repair BEFORE persisting the new set. The repair is
+ // triggered by the delta between the stored set and this sync's set, so if we
+ // persisted first and the repair then failed transiently, the next sync would
+ // see an UNCHANGED set, compute an empty delta, and never retry — the stale
+ // rows would stay broken forever. Leaving the old set stored on failure means
+ // the next sync recomputes the same delta and tries again. The cost is that a
+ // failed repair also defers the persist by one sync interval; the in-memory
+ // set is already updated above, so THIS sync's activity ingest still excludes
+ // every owner address either way.
+ let repaired = true;
+ await repairActivityAliasParticipants(account, previousAliases, sendAsAliases).catch((err) => {
+ repaired = false;
+ console.error(`🗓️ Activity alias backfill failed for account ${accountId} — deferring alias persist so the next sync retries: ${err.message}`);
+ });
+ if (repaired) {
+ await updateSendAsAliases(accountId, sendAsAliases).catch((err) =>
+ console.error(`📧 Send-as alias persist failed for account ${accountId}: ${err.message}`));
+ }
}
// Populate the human-activity timeline (#2150) — secondary effect, must NOT
diff --git a/server/services/messageSyncAliasBackfill.test.js b/server/services/messageSyncAliasBackfill.test.js
index 8ad42c2de7..ac0eb2f624 100644
--- a/server/services/messageSyncAliasBackfill.test.js
+++ b/server/services/messageSyncAliasBackfill.test.js
@@ -28,11 +28,19 @@ vi.mock('../lib/fileUtils.js', () => ({
vi.mock('./messageAccounts.js', () => ({
getAccount: vi.fn(),
- updateSyncStatus: vi.fn(),
+ updateSyncStatus: vi.fn(() => Promise.resolve()),
markSentIngested: vi.fn(() => Promise.resolve()),
updateSendAsAliases: vi.fn(() => Promise.resolve()),
}));
+vi.mock('./messageGmailSync.js', () => ({ syncGmail: vi.fn() }));
+
+// tribe.js is loaded dynamically by logMessageTouchpoints; stub it so the sync
+// path doesn't need a live Postgres.
+vi.mock('./tribe.js', () => ({
+ autoLogTouchpoints: vi.fn().mockResolvedValue({ created: 0, matched: 0 }),
+}));
+
// Keep the REAL pure helpers (notably `newlyLearnedAliases` — re-stating it in a
// mock would test the mock) and stub only the DB-touching entry points.
const stripParticipantsForAccount = vi.fn(() => Promise.resolve(2));
@@ -42,7 +50,10 @@ vi.mock('./humanActivity.js', async (importOriginal) => ({
recordEvents: vi.fn(() => Promise.resolve({ recorded: 0, skipped: 0 })),
}));
-const { repairActivityAliasParticipants } = await import('./messageSync.js');
+const { repairActivityAliasParticipants, syncAccount } = await import('./messageSync.js');
+const { getAccount, updateSendAsAliases } = await import('./messageAccounts.js');
+const { syncGmail } = await import('./messageGmailSync.js');
+const { tryReadFile } = await import('../lib/fileUtils.js');
const account = { id: 'acct-1', type: 'gmail', email: '[email protected]' };
@@ -74,3 +85,62 @@ describe('repairActivityAliasParticipants (#2855)', () => {
expect(stripParticipantsForAccount).toHaveBeenCalledWith('acct-2', 'message', ['[email protected]']);
});
});
+
+// Regression: the ORDER of repair-vs-persist inside syncAccount (#2855).
+//
+// Persisting the learned alias set before the repair succeeds makes a transient
+// repair failure PERMANENT: the stored set never changes again, so every later
+// sync computes an empty delta and the stale rows are never retried. The repair
+// must therefore run first, and the persist must be skipped when it fails.
+describe('syncAccount alias repair/persist ordering (#2855)', () => {
+ const ACCT = '22222222-2222-2222-2222-222222222222';
+ const mockIo = { emit: vi.fn() };
+
+ const runSync = async ({ storedAliases, fetchedAliases }) => {
+ getAccount.mockResolvedValue({
+ id: ACCT, name: 'Gmail', type: 'gmail', email: '[email protected]',
+ enabled: true, sendAsAliases: storedAliases,
+ });
+ tryReadFile.mockResolvedValue(JSON.stringify({ syncCursor: null, messages: [] }));
+ syncGmail.mockResolvedValue({ messages: [], sentMessages: [], status: 'success', sendAsAliases: fetchedAliases });
+ return syncAccount(ACCT, mockIo);
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ stripParticipantsForAccount.mockResolvedValue(2);
+ });
+
+ it('repairs BEFORE persisting, so the persist reflects a completed repair', async () => {
+ const order = [];
+ stripParticipantsForAccount.mockImplementation(() => { order.push('repair'); return Promise.resolve(1); });
+ updateSendAsAliases.mockImplementation(() => { order.push('persist'); return Promise.resolve(); });
+
+ await runSync({ storedAliases: [], fetchedAliases: ['[email protected]'] });
+
+ expect(order).toEqual(['repair', 'persist']);
+ expect(stripParticipantsForAccount).toHaveBeenCalledWith(ACCT, 'gmail', ['[email protected]']);
+ });
+
+ it('does NOT persist the new alias set when the repair fails, so the next sync retries', async () => {
+ stripParticipantsForAccount.mockRejectedValue(new Error('transient DB failure'));
+
+ const result = await runSync({ storedAliases: [], fetchedAliases: ['[email protected]'] });
+
+ // The failure must not fail the sync — it is a secondary effect.
+ expect(result.status).toBe('success');
+ // …and critically, the alias set stays unpersisted: leaving the stored set at
+ // its old value is what keeps the delta non-empty on the next sync. Persisting
+ // here would zero the delta forever and strand the stale rows.
+ expect(updateSendAsAliases).not.toHaveBeenCalled();
+ });
+
+ it('still persists when there is nothing to repair (alias removed → empty delta)', async () => {
+ await runSync({ storedAliases: ['[email protected]', '[email protected]'], fetchedAliases: ['[email protected]'] });
+
+ expect(stripParticipantsForAccount).not.toHaveBeenCalled();
+ // A removal changes the set without producing newly-learned aliases — the
+ // persist must still happen or the removal would never be recorded.
+ expect(updateSendAsAliases).toHaveBeenCalledWith(ACCT, ['[email protected]']);
+ });
+});