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: recover hetero persistence state across Vercel replicas (#14539)

LiJiand0b938a0cb5e
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 5b92e918386..6303f1e8d0e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -72,6 +72,14 @@ export interface ChatTopicMetadata {
* Cron job ID that triggered this topic creation (if created by scheduled task)
*/
cronJobId?: string;
+ /**
+ * Scoped pointer to the currently active assistant message for a running
+ * heterogeneous agent operation. Includes `operationId` so cold-start
+ * replicas only use the value when it belongs to the current operation β€”
+ * preventing a stale pointer from a previous run from corrupting a new one.
+ * Updated on every step boundary.
+ */
+ heteroCurrentMsgId?: { msgId: string; operationId: string };
/**
* Persistent session id for a heterogeneous agent.
* Saved after each turn so the next message in the same topic can resume
diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 5298a7af98c..af43a93988f 100644
--- a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -253,6 +253,11 @@ export class HeterogeneousPersistenceHandler {
await this.handleEvent(state, event);
state.processedKeys.add(key);
}
+
+ // Flush accumulated content after every batch so a subsequent replica
+ // picking up this operation always sees the latest content in the DB,
+ // even if it never processes a step boundary or terminal event.
+ await this.flushBatchContent(state);
}
/**
@@ -324,22 +329,48 @@ export class HeterogeneousPersistenceHandler {
throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);
}
+ // Prefer the latest step's assistant message id (written by handleStepStart)
+ // over the initial placeholder β€” so a new replica after a step boundary uses
+ // the correct message rather than the stale initial one.
+ // Guard: only use heteroCurrentMsgId when it belongs to THIS operation.
+ // A stale value from a previous run must not override the new operation's
+ // seeded assistantMessageId (P1 fix).
+ const stored = topic.metadata?.heteroCurrentMsgId;
+ const currentAssistantMessageId =
+ stored?.operationId === running.operationId
+ ? (stored.msgId ?? running.assistantMessageId)
+ : running.assistantMessageId;
+
+ // Restore toolMsgIdByCallId from the DB so tool_results that arrive on a
+ // different replica than their tool_use can still be matched and persisted.
+ const toolPlugins = await this.deps.messageModel.listMessagePluginsByTopic(topicId);
+ const toolMsgIdByCallId = new Map<string, string>();
+ for (const plugin of toolPlugins) {
+ if (plugin.toolCallId) toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);
+ }
+
state = {
accumulatedContent: '',
accumulatedReasoning: '',
agentId: topic.agentId ?? null,
- currentAssistantMessageId: running.assistantMessageId,
+ currentAssistantMessageId,
lastModel: undefined,
lastProvider: undefined,
operationId,
processedKeys: new Set(),
subagentRuns: new Map(),
- toolMsgIdByCallId: new Map(),
+ toolMsgIdByCallId,
toolState: { payloads: [], persistedIds: new Set() },
topicId,
};
operationStates.set(operationId, state);
- log('created state for operation %s on topic %s', operationId, topicId);
+ log(
+ 'created state for operation %s on topic %s msgId=%s tools=%d',
+ operationId,
+ topicId,
+ currentAssistantMessageId,
+ toolMsgIdByCallId.size,
+ );
return state;
}
@@ -435,8 +466,18 @@ export class HeterogeneousPersistenceHandler {
role: 'assistant',
topicId: state.topicId,
});
- state.currentAssistantMessageId = newMsg.id;
+ // Persist BEFORE advancing in-memory state (P2 fix). If this write fails
+ // transiently and the event is retried, state is still at the previous step
+ // so handleStepStart re-creates the new message with the correct parent
+ // rather than chaining off the partially-created one. The first attempt's
+ // empty message becomes an orphan but does not corrupt the turn chain.
+ await this.deps.topicModel.updateMetadata(state.topicId, {
+ heteroCurrentMsgId: { msgId: newMsg.id, operationId: state.operationId },
+ });
+
+ // Advance state only after the DB write lands.
+ state.currentAssistantMessageId = newMsg.id;
state.accumulatedContent = '';
state.accumulatedReasoning = '';
state.toolState = { payloads: [], persistedIds: new Set() };
@@ -577,6 +618,20 @@ export class HeterogeneousPersistenceHandler {
}
}
+ /**
+ * Write accumulated content/reasoning to DB after every ingest batch.
+ * This ensures a subsequent replica always finds the latest text in the DB
+ * even if the current replica never processes a step-boundary or terminal
+ * event (which are the normal flush triggers).
+ */
+ private async flushBatchContent(state: OperationState): Promise<void> {
+ if (!state.accumulatedContent && !state.accumulatedReasoning) return;
+ const update: Record<string, any> = {};
+ if (state.accumulatedContent) update.content = state.accumulatedContent;
+ if (state.accumulatedReasoning) update.reasoning = { content: state.accumulatedReasoning };
+ await this.deps.messageModel.update(state.currentAssistantMessageId, update);
+ }
+
private toChatMessageError(data: unknown): ChatMessageError {
if (typeof data === 'object' && data && 'message' in data) {
const message =
diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
index d0aa8973cf9..944a8667007 100644
--- a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
@@ -121,6 +121,7 @@ const createHarness = (
return { success: true };
},
),
+ listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
const threadModel = {
@@ -149,6 +150,7 @@ const createHarness = (
id: topicId,
metadata: { runningOperation: { assistantMessageId, operationId } },
})),
+ updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
};
const handler = new HeterogeneousPersistenceHandler({
@@ -306,8 +308,10 @@ describe('HeterogeneousPersistenceHandler β€” event branch coverage', () => {
buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'there' }),
]);
- // No update yet β€” text is held in accumulator
- expect(h.messageModel.update).not.toHaveBeenCalled();
+ // Text is flushed to DB at end of each batch (multi-replica fix)
+ expect(h.messageModel.update).toHaveBeenCalledWith(h.assistantMessageId, {
+ content: 'hi there',
+ });
});
it('main-side reasoning accumulates separately from text', async () => {
diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
index 0717f28d361..db1ddfe519b 100644
--- a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
@@ -181,6 +181,7 @@ const createHarness = () => {
});
return { success: true };
}),
+ listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
const threadModel = {
@@ -202,6 +203,7 @@ const createHarness = () => {
runningOperation: { assistantMessageId: 'asst-fixture', operationId: 'op-fixture' },
},
})),
+ updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
};
const handler = new HeterogeneousPersistenceHandler({
diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 94f7738f5a1..0e852c9ea87 100644
--- a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -101,6 +101,7 @@ const createHarness = (params: {
return { success: true };
},
),
+ listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
const threadModel = {
@@ -138,6 +139,7 @@ const createHarness = (params: {
},
};
}),
+ updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
};
const handler = new HeterogeneousPersistenceHandler({
@@ -190,8 +192,8 @@ describe('HeterogeneousPersistenceHandler', () => {
});
expect(h.topicModel.findById).toHaveBeenCalledWith('topic-1');
- // Text chunks accumulate; nothing flushed until step boundary or finish
- expect(h.messageModel.update).not.toHaveBeenCalled();
+ // Text chunks accumulate; flushed to DB at end of each batch (multi-replica fix)
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-seeded', { content: 'hello world' });
});
it('throws when the topic has no matching runningOperation', async () => {
@@ -394,8 +396,8 @@ describe('HeterogeneousPersistenceHandler', () => {
topicId: 'topic-1',
});
- // Phase 1 (update-asst) β†’ Phase 2 (create-tool) β†’ Phase 3 (update-asst)
- expect(order).toEqual(['update-asst', 'create-tool', 'update-asst']);
+ // Phase 1 (update-asst) β†’ Phase 2 (create-tool) β†’ Phase 3 (update-asst) β†’ batch flush (update-asst)
+ expect(order).toEqual(['update-asst', 'create-tool', 'update-asst', 'update-asst']);
// Tool message exists with content from tool_result + correct tool_call_id
const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
diff --git a/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index 4ff9258e058..5db27b32ab4 100644
--- a/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -31,7 +31,10 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
// Real handler so we exercise the persistSessionId path end-to-end
const handler = new HeterogeneousPersistenceHandler({
- messageModel: { update: vi.fn(async () => ({ success: true })) } as any,
+ messageModel: {
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
threadModel: {} as any,
topicModel: { findById, updateMetadata } as any,
});
@@ -83,7 +86,10 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
}));
const handler = new HeterogeneousPersistenceHandler({
- messageModel: { update: vi.fn(async () => ({ success: true })) } as any,
+ messageModel: {
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
threadModel: {} as any,
topicModel: { findById, updateMetadata } as any,
});
@@ -131,7 +137,10 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
}));
const handler = new HeterogeneousPersistenceHandler({
- messageModel: { update: vi.fn(async () => ({ success: true })) } as any,
+ messageModel: {
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
threadModel: {} as any,
topicModel: { findById, updateMetadata } as any,
});
@@ -186,7 +195,10 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
}));
const handler = new HeterogeneousPersistenceHandler({
- messageModel: { update: vi.fn(async () => ({ success: true })) } as any,
+ messageModel: {
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
threadModel: {} as any,
topicModel: { findById, updateMetadata } as any,
});
@@ -244,7 +256,10 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
}));
const handler = new HeterogeneousPersistenceHandler({
- messageModel: { update: vi.fn(async () => ({ success: true })) } as any,
+ messageModel: {
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
threadModel: {} as any,
topicModel: { findById, updateMetadata } as any,
});