Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(memory): merge consolidation domains in small batches so long merges cannot end the run (#22596)

Arvin Xu62ec730c683e
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts
index 9925e270831..d08793d10da 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/consolidation.ts
@@ -7,8 +7,11 @@ import {
} from '@/database/models/userMemory/consolidation';
import { getServerDB } from '@/database/server';
import {
+ applyDomainRound,
CLASSIFY_BATCH,
MemoryConsolidationService,
+ mergeDomainRounds,
+ resolveDomain,
SYNTH_CHUNK,
toContextPlans,
} from '@/server/services/memory/userMemory/consolidation/service';
@@ -135,11 +138,33 @@ export const consolidationHandler = async (context: WorkflowContext) => {
// Counted from the database, so a resumed run merges its whole lineage's domains, not only
// the ones it classified itself.
const evidence = await queueEvidence();
+ // Domains an earlier attempt merged stay merged; only new keys need the model.
+ const saved: Record<string, string> = {};
const domainCounts: Record<string, number> = {};
- for (const e of evidence) domainCounts[e.key] = (domainCounts[e.key] ?? 0) + e.count;
- const domainMap = await runStep(context, `${STEP}:normalize`, () =>
- service().normalizeDomains(domainCounts),
- );
+ for (const e of evidence) {
+ if (e.domain) saved[e.key] = e.domain;
+ domainCounts[e.key] = (domainCounts[e.key] ?? 0) + e.count;
+ }
+ const hasNewDomains = Object.keys(domainCounts).some((key) => !saved[key]);
+ // Small merge calls, then again over their results until one call has seen every name, so
+ // the same domain cannot keep two spellings from two batches.
+ const domainRounds: Record<string, string>[] = [saved];
+ if (hasNewDomains)
+ domainRounds.push(
+ ...(await mergeDomainRounds(applyDomainRound(domainCounts, saved), (round, batch, counts) =>
+ runStep(context, `${STEP}:normalize:${round}:${batch}`, () =>
+ service().normalizeDomains(counts),
+ ),
+ )),
+ );
+ // Keeps the `normalize` step name: the DC console reads the final mapping from it.
+ const domainMap = await runStep(context, `${STEP}:normalize`, async () => {
+ const map = Object.fromEntries(
+ Object.keys(domainCounts).map((key) => [key, resolveDomain(key, domainRounds)]),
+ );
+ if (hasNewDomains) await service().model.saveQueueDomains(origin, map);
+ return map;
+ });
const groups = await runStep(context, `${STEP}:group`, async () => {
const queued = await service().model.listQueued(runId);
diff --git a/apps/server/src/services/memory/userMemory/consolidation/__tests__/normalizeDomains.test.ts b/apps/server/src/services/memory/userMemory/consolidation/__tests__/normalizeDomains.test.ts
new file mode 100644
index 00000000000..85d92149027
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/consolidation/__tests__/normalizeDomains.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyDomainRound,
+ batchDomains,
+ mergeDomainRounds,
+ NORMALIZE_BATCH,
+ resolveDomain,
+} from '../service';
+
+describe('domain merge batches', () => {
+ it('never puts more than one batch worth of keys in a merge call', () => {
+ const counts = Object.fromEntries(Array.from({ length: 615 }, (_, i) => [`product/d${i}`, 1]));
+ const batches = batchDomains(counts);
+
+ expect(batches.every((b) => Object.keys(b).length <= NORMALIZE_BATCH)).toBe(true);
+ expect(batches.flatMap((b) => Object.keys(b)).sort()).toEqual(Object.keys(counts).sort());
+ });
+
+ it('keeps similar domains together', () => {
+ const [first, second] = batchDomains({ 'a/x': 1, 'b/y': 1, 'a/w': 1, 'b/z': 1 }, 2);
+
+ expect(Object.keys(first)).toEqual(['a/w', 'a/x']);
+ expect(Object.keys(second)).toEqual(['b/y', 'b/z']);
+ });
+
+ it('moves the batch boundaries when a round is shifted', () => {
+ const [first] = batchDomains({ 'a/w': 1, 'a/x': 1, 'b/y': 1, 'b/z': 1 }, 2, 1);
+
+ expect(Object.keys(first)).toEqual(['a/x', 'b/y']);
+ });
+
+ it('sums merged domains and follows a key through every round', () => {
+ const round1 = { 'p/task-a': 'p/tasks', 'p/task-b': 'p/tasks' };
+ const round2 = { 'p/tasks': 'p/task-system' };
+
+ expect(applyDomainRound({ 'p/other': 1, 'p/task-a': 2, 'p/task-b': 3 }, round1)).toEqual({
+ 'p/other': 1,
+ 'p/tasks': 5,
+ });
+ expect(resolveDomain('p/task-a', [round1, round2])).toBe('p/task-system');
+ expect(resolveDomain('p/other', [round1, round2])).toBe('p/other');
+ });
+
+ const mergeAliases =
+ (calls: string[][]) =>
+ async (_round: number, _batch: number, counts: Record<string, number>) => {
+ const keys = Object.keys(counts);
+ calls.push(keys);
+ const out: Record<string, string> = {};
+ // Stands in for the model: two spellings of one domain merge only if it sees both.
+ if (keys.includes('project/task') && keys.includes('project/tasks')) {
+ out['project/task'] = 'project/tasks';
+ out['project/tasks'] = 'project/tasks';
+ }
+ return out;
+ };
+
+ it('compares domains that a batch boundary cut apart', async () => {
+ const counts: Record<string, number> = Object.fromEntries(
+ Array.from({ length: 79 }, (_, i) => [`a/d${i}`, 1]),
+ );
+ counts['project/task'] = 2;
+ counts['project/tasks'] = 3;
+ const calls: string[][] = [];
+
+ const rounds = await mergeDomainRounds(counts, mergeAliases(calls));
+
+ expect(calls[0]).not.toContain('project/tasks');
+ expect(resolveDomain('project/task', rounds)).toBe('project/tasks');
+ expect(resolveDomain('project/tasks', rounds)).toBe('project/tasks');
+ });
+
+ it('moves the boundaries once before accepting a mapping that merges nothing', async () => {
+ const counts = Object.fromEntries(Array.from({ length: 200 }, (_, i) => [`a/d${i}`, 1]));
+ const calls: string[][] = [];
+
+ const rounds = await mergeDomainRounds(counts, mergeAliases(calls));
+
+ // Round 1 keeps the sorted split, round 2 moves it, then the mapping is final.
+ expect(rounds).toHaveLength(2);
+ expect(calls).toHaveLength(6);
+ expect(calls[3]).not.toEqual(calls[0]);
+ });
+});
diff --git a/apps/server/src/services/memory/userMemory/consolidation/service.ts b/apps/server/src/services/memory/userMemory/consolidation/service.ts
index 9a1a10ebcfe..e5490034295 100644
--- a/apps/server/src/services/memory/userMemory/consolidation/service.ts
+++ b/apps/server/src/services/memory/userMemory/consolidation/service.ts
@@ -50,6 +50,11 @@ const log = debug('lobe-server:memory:consolidation');
export const CLASSIFY_BATCH = 20;
/** Memories per synthesis call; larger domains are synthesized in time-ordered chunks. */
export const SYNTH_CHUNK = 40;
+/**
+ * Domain keys per merge call. A call over 600+ keys took about 3 minutes, long enough for QStash to
+ * count the delivery as failed, redeliver it, and end the whole run once retries ran out.
+ */
+export const NORMALIZE_BATCH = 80;
/** The online step shows the model this many recalled contexts plus the most recently active. */
const ROUTE_TOP_CONTEXTS = 30;
const ROUTE_RECENT_CONTEXTS = 10;
@@ -323,6 +328,97 @@ export class MemoryConsolidationService {
}
}
+/**
+ * Split domain counts into merge batches, sorted by key so similar domains share a batch.
+ *
+ * `offset` rotates the sorted list before splitting, which moves the batch boundaries. Keys that
+ * were cut apart by a boundary β€” and so could never be compared in the same call β€” land together
+ * once the boundaries move.
+ */
+export const batchDomains = (
+ counts: Record<string, number>,
+ size = NORMALIZE_BATCH,
+ offset = 0,
+): Record<string, number>[] => {
+ const keys = Object.entries(counts).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ if (keys.length === 0) return [];
+ const start = offset % keys.length;
+ const ordered = start === 0 ? keys : [...keys.slice(start), ...keys.slice(0, start)];
+ const batches: Record<string, number>[] = [];
+ for (let i = 0; i < ordered.length; i += size)
+ batches.push(Object.fromEntries(ordered.slice(i, i + size)));
+ return batches;
+};
+
+/** Domain counts after one merge round; keys the round left out stay as they are. */
+export const applyDomainRound = (
+ counts: Record<string, number>,
+ round: Record<string, string>,
+): Record<string, number> => {
+ const out: Record<string, number> = {};
+ for (const [key, count] of Object.entries(counts)) {
+ const merged = round[key] ?? key;
+ out[merged] = (out[merged] ?? 0) + count;
+ }
+ return out;
+};
+
+/** Follow a domain through every merge round to its final name. */
+export const resolveDomain = (key: string, rounds: Record<string, string>[]) =>
+ rounds.reduce((current, round) => round[current] ?? current, key);
+
+/** Merge rounds one normalization may spend before it accepts the mapping it has built. */
+export const NORMALIZE_MAX_ROUNDS = 4;
+/** Half a batch: the smallest rotation that re-pairs the keys a batch boundary cut apart. */
+const BOUNDARY_SHIFT = Math.ceil(NORMALIZE_BATCH / 2);
+
+/**
+ * Merge domain names in batch-sized calls until one call has seen every name, or until a round
+ * that used a moved batch split also merges nothing.
+ *
+ * One round without a merge is not convergence: two spellings of one domain (`project/task` and
+ * `project/tasks`) that sit on opposite sides of a batch boundary never meet, and neither batch
+ * shrinks. So the boundaries are moved once before the mapping is accepted as final.
+ */
+export const mergeDomainRounds = async (
+ counts: Record<string, number>,
+ merge: (
+ round: number,
+ batch: number,
+ counts: Record<string, number>,
+ ) => Promise<Record<string, string>>,
+ maxRounds = NORMALIZE_MAX_ROUNDS,
+): Promise<Record<string, string>[]> => {
+ const rounds: Record<string, string>[] = [];
+ let current = counts;
+ let shift = 0;
+ for (let round = 0; round < maxRounds; round += 1) {
+ const batches = batchDomains(current, NORMALIZE_BATCH, shift);
+ if (batches.length === 0) break;
+ const merged: Record<string, string> = {};
+ for (const [batch, keys] of batches.entries()) {
+ // A lone key has nothing to merge with here; a moved split pairs it with its neighbours.
+ if (Object.keys(keys).length <= 1) continue;
+ Object.assign(merged, await merge(round, batch, keys));
+ }
+ const next = applyDomainRound(current, merged);
+ rounds.push(merged);
+ const shrank = Object.keys(next).length < Object.keys(current).length;
+ current = next;
+ // One call has now seen every name, so no alias can still be split across batches.
+ if (batches.length <= 1) break;
+ if (shrank) {
+ shift = 0;
+ continue;
+ }
+ // This split found nothing to merge. Only a round with moved boundaries can tell a real
+ // absence of aliases from aliases hiding on either side of a boundary.
+ if (shift !== 0) break;
+ shift = BOUNDARY_SHIFT;
+ }
+ return rounds;
+};
+
/** Turn a synthesis result into context plans, keeping only members from `allowed`. */
export const toContextPlans = (
result: SynthesisResult,
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
index ad255cb629d..8ad77bcee5b 100644
--- a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
@@ -409,10 +409,16 @@ describe('UserMemoryConsolidationModel', () => {
expect(evidence).toHaveLength(2);
expect(evidence).toEqual(
expect.arrayContaining([
- { contextId: filed.contextId, count: 1, key: 'product/tasks' },
- { contextId: null, count: 1, key: 'product/tasks' },
+ { contextId: filed.contextId, count: 1, domain: null, key: 'product/tasks' },
+ { contextId: null, count: 1, domain: null, key: 'product/tasks' },
]),
);
+
+ await model.saveQueueDomains('run_a', { 'product/tasks': 'product/task-system' });
+ expect((await model.listQueueEvidence('run_a')).map((e) => e.domain)).toEqual([
+ 'product/task-system',
+ 'product/task-system',
+ ]);
});
});
diff --git a/packages/database/src/models/userMemory/consolidation.ts b/packages/database/src/models/userMemory/consolidation.ts
index e6bea62077b..f8d06cba260 100644
--- a/packages/database/src/models/userMemory/consolidation.ts
+++ b/packages/database/src/models/userMemory/consolidation.ts
@@ -403,12 +403,13 @@ export class UserMemoryConsolidationModel {
*/
listQueueEvidence = async (
origin: string,
- ): Promise<{ contextId: string | null; count: number; key: string }[]> => {
+ ): Promise<{ contextId: string | null; count: number; domain: string | null; key: string }[]> => {
const queue = sql`${userMemories.metadata} -> 'consolidationQueue'`;
return this.db
.select({
contextId: userMemoriesDossiers.contextId,
count: sql<number>`count(*)::int`,
+ domain: sql<string | null>`${queue} ->> 'domain'`,
key: sql<string>`${queue} ->> 'key'`,
})
.from(userMemories)
@@ -427,7 +428,26 @@ export class UserMemoryConsolidationModel {
sql`${queue} ->> 'route' = 'evidence'`,
),
)
- .groupBy(userMemoriesDossiers.contextId, sql`${queue} ->> 'key'`);
+ .groupBy(userMemoriesDossiers.contextId, sql`${queue} ->> 'domain'`, sql`${queue} ->> 'key'`);
+ };
+
+ /** Remember merged domains on a queue lineage, so a resumed run does not merge them again. */
+ saveQueueDomains = async (origin: string, domains: Record<string, string>): Promise<void> => {
+ const queue = sql`${userMemories.metadata} -> 'consolidationQueue'`;
+ const map = sql`${JSON.stringify(domains)}::jsonb`;
+ await this.db
+ .update(userMemories)
+ .set({
+ metadata: sql`jsonb_set(${userMemories.metadata}, '{consolidationQueue,domain}', ${map} -> (${queue} ->> 'key'))`,
+ })
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ sql`COALESCE(${queue} ->> 'origin', ${queue} ->> 'runId') = ${origin}`,
+ sql`${queue} ->> 'route' = 'evidence'`,
+ sql`jsonb_exists(${map}, ${queue} ->> 'key')`,
+ ),
+ );
};
/** Mark legacy rows that consolidation saw but keeps in place (facts, preferences, noise). */