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.

✨ feat(memory): resume a stopped consolidation run instead of starting over (#22007)

Arvin Xu822ca98856a9
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 4890bcbc086..9925e270831 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
@@ -73,28 +73,55 @@ export const consolidationHandler = async (context: WorkflowContext) => {
const pending = await runStep(context, `${STEP}:list-pending`, async () => {
const s = service();
- const [items, consolidated] = await Promise.all([
+ const [items, consolidated, resumable] = await Promise.all([
s.model.listPendingLegacyContexts(),
s.model.listConsolidated(),
+ s.model.findResumableQueue(),
]);
+ const contextIds = new Set(consolidated.contexts.map((c) => c.id));
+ // A stopped run left evidence queued: continue its queue in the mode it was built in.
+ // Incremental queues are keyed by target context (or `new:<title>`), backfill by domain.
+ const resumedMode = resumable
+ ? resumable.keys.some((k) => k?.startsWith('new:') || contextIds.has(k))
+ ? ('incremental' as const)
+ : ('backfill' as const)
+ : undefined;
return {
ids: items.map((i) => i.id),
- mode: consolidated.contexts.length === 0 ? ('backfill' as const) : ('incremental' as const),
+ mode:
+ resumedMode ?? (contextIds.size === 0 ? ('backfill' as const) : ('incremental' as const)),
+ resume: resumable ? { fromRunId: resumable.runId, origin: resumable.origin } : undefined,
};
});
if (pending.ids.length === 0) return { ...empty, mode: pending.mode };
+ const origin = pending.resume?.origin ?? runId;
+ const resume = pending.resume;
+ // Take the stopped run's queue over; what is left to classify / route is everything else.
+ const adopted = resume
+ ? await runStep(context, `${STEP}:adopt-queue`, async () => {
+ const s = service();
+ await s.model.adoptQueue(resume.fromRunId, resume.origin, runId);
+ return (await s.model.listQueued(runId)).map((q) => q.id);
+ })
+ : [];
+ const adoptedIds = new Set(adopted);
+ const toClassify = pending.ids.filter((id) => !adoptedIds.has(id));
+ // Domain mix and contexts built so far by this queue lineage (earlier attempts included).
+ const queueEvidence = async () =>
+ runStep(context, `${STEP}:queue-evidence`, () => service().model.listQueueEvidence(origin));
+
// ---------- stage 1: decide route + queue key ----------
if (pending.mode === 'backfill') {
- const domainCounts: Record<string, number> = {};
- for (let i = 0; i < pending.ids.length; i += CLASSIFY_BATCH) {
- const batch = pending.ids.slice(i, i + CLASSIFY_BATCH);
- const counts = await runStep(context, `${STEP}:classify:${i / CLASSIFY_BATCH}`, async () => {
+ for (let i = 0; i < toClassify.length; i += CLASSIFY_BATCH) {
+ const batch = toClassify.slice(i, i + CLASSIFY_BATCH);
+ await runStep(context, `${STEP}:classify:${i / CLASSIFY_BATCH}`, async () => {
const s = service();
const items = await s.classify(batch);
await s.model.enqueue(
runId,
items.map((x) => ({ id: x.id, key: x.domain || 'misc', route: x.route })),
+ origin,
);
const routed: Record<string, ConsolidationRoute> = {};
for (const x of items) if (x.route !== 'evidence') routed[x.id] = x.route;
@@ -104,8 +131,12 @@ export const consolidationHandler = async (context: WorkflowContext) => {
if (x.route === 'evidence') out[x.domain || 'misc'] = (out[x.domain || 'misc'] ?? 0) + 1;
return out;
});
- for (const [k, n] of Object.entries(counts)) domainCounts[k] = (domainCounts[k] ?? 0) + n;
}
+ // 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();
+ 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),
);
@@ -117,9 +148,14 @@ export const consolidationHandler = async (context: WorkflowContext) => {
return out;
});
+ // Contexts earlier attempts built per merged domain: a resumed run extends them.
+ const builtByDomain: Record<string, Set<string>> = {};
+ for (const e of evidence)
+ if (e.contextId) (builtByDomain[domainMap[e.key] ?? e.key] ??= new Set()).add(e.contextId);
+
let contexts = 0;
for (const [d, [domain, ids]] of Object.entries(groups).entries()) {
- let domainContexts: string[] = [];
+ let domainContexts: string[] = [...(builtByDomain[domain] ?? [])];
for (let c = 0; c * SYNTH_CHUNK < ids.length; c += 1) {
const chunk = ids.slice(c * SYNTH_CHUNK, (c + 1) * SYNTH_CHUNK);
const known = domainContexts;
@@ -133,8 +169,8 @@ export const consolidationHandler = async (context: WorkflowContext) => {
return { contexts, mode: 'backfill', processed: pending.ids.length, runId };
}
- for (let i = 0; i < pending.ids.length; i += ROUTE_BATCH) {
- const batch = pending.ids.slice(i, i + ROUTE_BATCH);
+ for (let i = 0; i < toClassify.length; i += ROUTE_BATCH) {
+ const batch = toClassify.slice(i, i + ROUTE_BATCH);
await runStep(context, `${STEP}:route:${i / ROUTE_BATCH}`, async () => {
const s = service();
const [items, consolidated] = await Promise.all([
@@ -172,7 +208,7 @@ export const consolidationHandler = async (context: WorkflowContext) => {
entries.push({ id: item.id, key, route: r.route });
if (r.route !== 'evidence') routed[item.id] = r.route;
}
- await s.model.enqueue(runId, entries);
+ await s.model.enqueue(runId, entries, origin);
await s.markRouted(routed);
return entries.length;
});
@@ -185,10 +221,16 @@ export const consolidationHandler = async (context: WorkflowContext) => {
return out;
});
let contexts = 0;
+ // A resumed queue may have filed part of a `new:` group already; keep extending those contexts.
+ const builtByKey: Record<string, string[]> = {};
+ if (resume)
+ for (const e of await queueEvidence())
+ if (e.contextId) (builtByKey[e.key] ??= []).push(e.contextId);
+
for (const [g, [key, ids]] of Object.entries(groups).entries()) {
const isNew = key.startsWith('new:');
// Later chunks of one group must see the contexts earlier chunks created, as in backfill.
- let groupContexts: string[] = isNew ? [] : [key];
+ let groupContexts: string[] = isNew ? [...new Set(builtByKey[key] ?? [])] : [key];
const touched = new Set<string>();
for (let c = 0; c * SYNTH_CHUNK < ids.length; c += 1) {
const chunk = ids.slice(c * SYNTH_CHUNK, (c + 1) * SYNTH_CHUNK);
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
index 03db457d2c8..ed2b9ab9df5 100644
--- a/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/consolidation.test.ts
@@ -404,6 +404,42 @@ describe('UserMemoryConsolidationModel', () => {
expect(reverted.blockedBy).toBeUndefined();
expect(await model.listPendingLegacyContexts()).toHaveLength(2);
});
+
+ it('lets a new run adopt the queue a stopped run left, keeping its lineage', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler cron mode', '2026-06-01');
+ await model.enqueue('run_a', [
+ { id: a.context.id, key: 'product/tasks', route: 'evidence' },
+ { id: b.context.id, key: 'product/tasks', route: 'evidence' },
+ ]);
+ const filed = await model.applyContextPlan('run_a', {
+ dossiers: [{ memberIds: [a.context.id], now: 'v1', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ title: 'Task system',
+ });
+ // run_a stops here: b is still queued.
+ expect(await model.findResumableQueue()).toEqual({
+ count: 1,
+ keys: ['product/tasks'],
+ origin: 'run_a',
+ runId: 'run_a',
+ });
+
+ expect(await model.adoptQueue('run_a', 'run_a', 'run_b')).toBe(1);
+ expect((await model.listQueued('run_b')).map((q) => q.id)).toEqual([b.context.id]);
+ expect(await model.findResumableQueue()).toMatchObject({ origin: 'run_a', runId: 'run_b' });
+
+ const evidence = await model.listQueueEvidence('run_a');
+ expect(evidence).toHaveLength(2);
+ expect(evidence).toEqual(
+ expect.arrayContaining([
+ { contextId: filed.contextId, count: 1, key: 'product/tasks' },
+ { contextId: null, count: 1, key: 'product/tasks' },
+ ]),
+ );
+ });
});
describe('deriveContextStatus', () => {
diff --git a/packages/database/src/models/userMemory/consolidation.ts b/packages/database/src/models/userMemory/consolidation.ts
index fa5dfd3ed06..e6bea62077b 100644
--- a/packages/database/src/models/userMemory/consolidation.ts
+++ b/packages/database/src/models/userMemory/consolidation.ts
@@ -290,6 +290,8 @@ export class UserMemoryConsolidationModel {
enqueue = async (
runId: string,
entries: { id: string; key: string; route: ConsolidationRoute }[],
+ /** The run whose queue this continues (see `adoptQueue`); the run itself when it is new. */
+ origin: string = runId,
) => {
if (entries.length === 0) return;
const items = await this.getLegacyContextsByIds(entries.map((e) => e.id));
@@ -302,7 +304,7 @@ export class UserMemoryConsolidationModel {
.update(userMemories)
.set({
metadata: sql`coalesce(${userMemories.metadata}, '{}'::jsonb) || ${JSON.stringify({
- consolidationQueue: { key: e.key, route: e.route, runId },
+ consolidationQueue: { key: e.key, origin, route: e.route, runId },
})}::jsonb`,
})
.where(and(eq(userMemories.id, memoryId), eq(userMemories.userId, this.userId)));
@@ -335,6 +337,99 @@ export class UserMemoryConsolidationModel {
return rows;
};
+ /**
+ * The newest queue a stopped run left behind: evidence it classified (or routed) but never
+ * synthesized. A new run adopts it instead of starting over. `origin` is the run that first
+ * built the queue, kept across resumes; rows queued before `origin` existed fall back to `runId`.
+ */
+ findResumableQueue = async (): Promise<{
+ count: number;
+ keys: string[];
+ origin: string;
+ runId: string;
+ } | null> => {
+ const queue = sql`${userMemories.metadata} -> 'consolidationQueue'`;
+ const [row] = await this.db
+ .select({
+ count: sql<number>`count(*)::int`,
+ keys: sql<string[]>`array_agg(DISTINCT ${queue} ->> 'key')`,
+ origin: sql<string>`COALESCE(${queue} ->> 'origin', ${queue} ->> 'runId')`,
+ runId: sql<string>`${queue} ->> 'runId'`,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, legacyParentJoin)
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ isNull(userMemoriesContexts.synthesizedAt),
+ eq(userMemories.userId, this.userId),
+ isNull(userMemories.state),
+ notConsolidated,
+ sql`${queue} ->> 'route' = 'evidence'`,
+ ),
+ )
+ .groupBy(
+ sql`COALESCE(${queue} ->> 'origin', ${queue} ->> 'runId')`,
+ sql`${queue} ->> 'runId'`,
+ )
+ .orderBy(sql`max(${userMemories.updatedAt}) DESC`)
+ .limit(1);
+ return row ?? null;
+ };
+
+ /** Move a stopped run's unsynthesized queue to `runId`, keeping the queue's origin. */
+ adoptQueue = async (fromRunId: string, origin: string, runId: string): Promise<number> => {
+ const rows = await this.db
+ .update(userMemories)
+ .set({
+ metadata: sql`jsonb_set(${userMemories.metadata}, '{consolidationQueue}', (${userMemories.metadata} -> 'consolidationQueue') || ${JSON.stringify({ origin, runId })}::jsonb)`,
+ })
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ isNull(userMemories.state),
+ notConsolidated,
+ sql`${userMemories.metadata} -> 'consolidationQueue' ->> 'runId' = ${fromRunId}`,
+ ),
+ )
+ .returning({ id: userMemories.id });
+ return rows.length;
+ };
+
+ /**
+ * Every evidence row of a queue lineage (all runs sharing `origin`), by queue key, with the
+ * context it was filed into (null while waiting). Resumed runs read the domain mix and the
+ * contexts earlier attempts built from it.
+ */
+ listQueueEvidence = async (
+ origin: string,
+ ): Promise<{ contextId: string | null; count: number; key: string }[]> => {
+ const queue = sql`${userMemories.metadata} -> 'consolidationQueue'`;
+ return this.db
+ .select({
+ contextId: userMemoriesDossiers.contextId,
+ count: sql<number>`count(*)::int`,
+ key: sql<string>`${queue} ->> 'key'`,
+ })
+ .from(userMemories)
+ .leftJoin(
+ userMemoriesActivities,
+ and(
+ sql`${userMemoriesActivities.id} = ${userMemories.metadata} -> 'consolidation' ->> 'activityId'`,
+ eq(userMemoriesActivities.userId, this.userId),
+ ),
+ )
+ .leftJoin(userMemoriesDossiers, eq(userMemoriesDossiers.id, userMemoriesActivities.dossierId))
+ .where(
+ and(
+ eq(userMemories.userId, this.userId),
+ sql`COALESCE(${queue} ->> 'origin', ${queue} ->> 'runId') = ${origin}`,
+ sql`${queue} ->> 'route' = 'evidence'`,
+ ),
+ )
+ .groupBy(userMemoriesDossiers.contextId, sql`${queue} ->> 'key'`);
+ };
+
/** Mark legacy rows that consolidation saw but keeps in place (facts, preferences, noise). */
markRouted = async (runId: string, routes: Record<string, ConsolidationRoute>) => {
const ids = Object.keys(routes);