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: skip repeated daily Beeper touchpoint writes within batches (#9878)

Adam Eivy8a751d026794
diff --git a/server/services/beeperTribe.db.test.js b/server/services/beeperTribe.db.test.js
index c28f66a534..b65ff8f416 100644
--- a/server/services/beeperTribe.db.test.js
+++ b/server/services/beeperTribe.db.test.js
@@ -21,8 +21,9 @@
* file is not auto-globbed). Every fixture uses placeholder names/handles per
* root AGENTS.md Sensitive Data & Privacy — no real handle, name, or phone.
*/
-import { describe, it, expect, afterAll } from 'vitest';
+import { describe, it, expect, afterAll, vi } from 'vitest';
import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+import * as database from '../lib/db.js';
import { requireDbOrSkip } from '../lib/dbTestGate.js';
import * as tribe from './tribe.js';
import * as tribeIdentities from './tribeIdentities.js';
@@ -597,4 +598,46 @@ describe.skipIf(!runDb)('beeperTribe (#34)', () => {
const after = await tribe.listTouchpoints(rosterOnly.id);
expect(after).toHaveLength(0);
});
+
+ it('uses 20 transactions for 20 chats with 25 daily messages while retaining database idempotency', async () => {
+ await makeAccount();
+ const person = await makePerson('Example Batch Sender');
+ const batches = [];
+ for (let i = 0; i < 20; i++) {
+ // eslint-disable-next-line no-await-in-loop -- fixture setup before transaction counting
+ const conversationId = await makeConversation(`${nonce}-batch-${i}`);
+ // eslint-disable-next-line no-await-in-loop -- fixture setup
+ await beeperTribe.upsertParticipant({
+ conversationId, sourceUserId: 'batch-sender', handle: '', observedVia: 'message-sender',
+ });
+ // eslint-disable-next-line no-await-in-loop -- fixture setup
+ await beeperTribe.linkParticipant({ conversationId, sourceUserId: 'batch-sender', personId: person.id });
+ batches.push(Array.from({ length: 25 }, () => ({
+ conversationId, senderId: 'batch-sender',
+ sentAt: '2026-10-03T12:00:00.000Z', network: 'whatsapp',
+ })));
+ }
+ const transactions = vi.spyOn(database, 'withTransaction');
+ try {
+ const first = await beeperTribe.logSenderTouchpoints(batches[0]);
+ const contactAfterFirst = await query('SELECT last_contact_on, channel, updated_at FROM tribe_people WHERE id = $1', [person.id]);
+ const remaining = await Promise.all(batches.slice(1).map((batch) => beeperTribe.logSenderTouchpoints(batch)));
+ const totals = [first, ...remaining].reduce((total, result) => ({
+ matched: total.matched + result.matched, created: total.created + result.created,
+ }), { matched: 0, created: 0 });
+ expect(totals).toEqual({ matched: 500, created: 1 });
+ expect(transactions).toHaveBeenCalledTimes(20);
+ expect((await query('SELECT last_contact_on, channel, updated_at FROM tribe_people WHERE id = $1', [person.id])).rows)
+ .toEqual(contactAfterFirst.rows);
+ const touchpoints = await tribe.listTouchpoints(person.id);
+ expect(touchpoints).toHaveLength(1);
+ expect(touchpoints[0]).toMatchObject({
+ channel: 'Beeper (whatsapp)', source: 'message',
+ metadata: { network: 'whatsapp', conversationId: batches[0][0].conversationId },
+ });
+ } finally {
+ transactions.mockRestore();
+ }
+ });
+
});
diff --git a/server/services/beeperTribe.js b/server/services/beeperTribe.js
index 65384e5aaa..939df321e6 100644
--- a/server/services/beeperTribe.js
+++ b/server/services/beeperTribe.js
@@ -577,10 +577,11 @@ export async function logSenderTouchpoints(candidates = []) {
// Memoize the participant -> person resolution per (conversationId,
// senderId) within this batch, so a burst of messages from the same sender
- // resolves once, not per message. Day-level dedupe is NOT reimplemented
- // here: tribe.autoCreateTouchpoint's (person_id, dedupe_key) partial unique
- // index already collapses a same-day repeat into a harmless no-op insert.
+ // resolves once, not per message. Completed person/day attempts are also
+ // reused within this batch; the database unique index remains authoritative
+ // across batches and concurrent syncs.
const personCache = new Map();
+ const completedTouchpoints = new Set();
let created = 0;
let matched = 0;
for (const c of candidates) {
@@ -605,15 +606,19 @@ export async function logSenderTouchpoints(candidates = []) {
const day = Number.isNaN(parsedSentAt.getTime())
? String(c.sentAt).slice(0, 10)
: parsedSentAt.toISOString().slice(0, 10);
+ const dedupeKey = `beeper:${day}`;
+ const touchpointKey = JSON.stringify([personId, dedupeKey]);
+ if (completedTouchpoints.has(touchpointKey)) continue;
// eslint-disable-next-line no-await-in-loop -- same reason as above
const touchpoint = await tribe.autoCreateTouchpoint(personId, {
happenedAt: c.sentAt,
channel: c.channel || (c.network ? `Beeper (${c.network})` : 'Beeper'),
summary: '',
source: 'message',
- dedupeKey: `beeper:${day}`,
+ dedupeKey,
metadata: { network: c.network || '', conversationId: c.conversationId },
});
+ completedTouchpoints.add(touchpointKey);
if (touchpoint) created++;
}
return { created, matched };
diff --git a/server/services/beeperTribe.test.js b/server/services/beeperTribe.test.js
index 5652aab09e..f418f343e9 100644
--- a/server/services/beeperTribe.test.js
+++ b/server/services/beeperTribe.test.js
@@ -787,3 +787,81 @@ describe('unlinkIdentity (#99)', () => {
expect(db.participants.get(pKey(CONVERSATION, 'user-1')).tribe_person_id).toBeNull();
});
});
+
+
+describe('logSenderTouchpoints batch deduplication', () => {
+ const candidate = (overrides = {}) => ({
+ conversationId: CONVERSATION, senderId: 'user-1',
+ sentAt: '2026-10-03T12:00:00.000Z', network: 'discord', ...overrides,
+ });
+
+ beforeEach(() => {
+ tribeService.autoCreateTouchpoint.mockReset();
+ seedParticipant({ tribePersonId: CACHED_PERSON });
+ });
+
+ it.each([null, { id: 'example-touchpoint' }])('attempts 25 repeated candidates once, including a confirmed duplicate (%j)', async (touchpoint) => {
+ tribeService.autoCreateTouchpoint.mockResolvedValue(touchpoint);
+ const first = candidate({ sentAt: new Date('2026-10-03T12:00:00.000Z'), channel: 'Example channel' });
+ const batch = [first, ...Array.from({ length: 24 }, () => candidate({ channel: 'Later channel' }))];
+
+ expect(await beeperTribe.logSenderTouchpoints(batch)).toEqual({
+ matched: 25, created: touchpoint ? 1 : 0,
+ });
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledTimes(1);
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledWith(CACHED_PERSON, {
+ happenedAt: first.sentAt, channel: 'Example channel', summary: '',
+ source: 'message', dedupeKey: 'beeper:2026-10-03',
+ metadata: { network: 'discord', conversationId: CONVERSATION },
+ });
+ });
+
+ it('shares a person/day across sender identities while keeping people and UTC days separate', async () => {
+ seedParticipant({ sourceUserId: 'alias', tribePersonId: CACHED_PERSON });
+ seedParticipant({ sourceUserId: 'other', tribePersonId: CLAIMING_PERSON });
+ tribeService.autoCreateTouchpoint.mockResolvedValue({ id: 'example-touchpoint' });
+ const result = await beeperTribe.logSenderTouchpoints([
+ candidate(), candidate({ senderId: 'alias' }),
+ candidate({ senderId: 'other' }),
+ candidate({ sentAt: '2026-10-04T01:00:00.000Z' }),
+ candidate({ sentAt: '2026-10-03T23:30:00-02:00' }),
+ ]);
+ expect(result).toEqual({ matched: 5, created: 3 });
+ expect(tribeService.autoCreateTouchpoint.mock.calls.map(([personId, data]) => [personId, data.dedupeKey]))
+ .toEqual([
+ [CACHED_PERSON, 'beeper:2026-10-03'],
+ [CLAIMING_PERSON, 'beeper:2026-10-03'],
+ [CACHED_PERSON, 'beeper:2026-10-04'],
+ ]);
+ });
+
+ it('ignores deleted and unmatched people without suppressing a later matched sender', async () => {
+ db.people.get(CLAIMING_PERSON).deleted = true;
+ seedParticipant({ sourceUserId: 'deleted', tribePersonId: CLAIMING_PERSON });
+ tribeService.autoCreateTouchpoint.mockResolvedValue(null);
+ expect(await beeperTribe.logSenderTouchpoints([
+ candidate({ senderId: 'deleted' }), candidate({ senderId: 'unknown' }), candidate(),
+ ])).toEqual({ matched: 1, created: 0 });
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledTimes(1);
+ });
+
+ it('propagates failed writes and retries through the database boundary in a later invocation', async () => {
+ tribeService.autoCreateTouchpoint.mockRejectedValueOnce(new Error('example database failure'));
+ const batch = [candidate(), candidate()];
+ await expect(beeperTribe.logSenderTouchpoints(batch)).rejects.toThrow('example database failure');
+ tribeService.autoCreateTouchpoint.mockResolvedValue(null);
+ expect(await beeperTribe.logSenderTouchpoints(batch)).toEqual({ matched: 2, created: 0 });
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledTimes(2);
+ });
+
+ it('consults the database once per batch across 20 batches of 25 messages', async () => {
+ tribeService.autoCreateTouchpoint.mockResolvedValue(null)
+ .mockResolvedValueOnce({ id: 'example-touchpoint' });
+ const batch = Array.from({ length: 25 }, () => candidate());
+ const results = await Promise.all(Array.from({ length: 20 }, () => beeperTribe.logSenderTouchpoints(batch)));
+ expect(results.reduce((total, result) => ({
+ matched: total.matched + result.matched, created: total.created + result.created,
+ }), { matched: 0, created: 0 })).toEqual({ matched: 500, created: 1 });
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledTimes(20);
+ });
+});