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(hetero-agent): restore tools/model from DB at ingest refresh to fix multi-replica parent_id breaks (#14897)

Arvin Xub52ff529497c
diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index da6827ce80e..a2860664a90 100644
--- a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -294,6 +294,47 @@ export class HeterogeneousPersistenceHandler {
state.accumulatedReasoning = dbReasoning;
}
+ // Same multi-replica concern for `tools[]` and `lastModel`/`lastProvider`.
+ //
+ // Why this is necessary: `handleStepStart` computes the new assistant's
+ // parentId from `state.toolState.payloads` and copies model/provider from
+ // `state.lastModel` / `state.lastProvider`. Those are populated by
+ // `persistMainToolBatch` and `handleTurnMetadata` respectively β€” both
+ // run on whichever replica drains the relevant event. When the replica
+ // driving the next step boundary is NOT the one that drained the prior
+ // step's tools_calling / step_complete, the in-memory state is empty:
+ // - parentId falls back to `state.currentAssistantMessageId`, so the
+ // new turn chains off the previous assistant instead of the tool
+ // message (observed in prod: 4/11 step boundaries in one topic).
+ // - model/provider are written as null on the new assistant.
+ //
+ // Adopt the DB view as authoritative whenever it carries more resolved
+ // state than memory. `tools[]` is rewritten end-to-end on every Phase-3
+ // backfill, so it's safe to replace wholesale rather than merge by id β€”
+ // the same-batch transient where mem has a tool DB hasn't seen yet does
+ // not happen at refresh time (refresh runs before the event loop).
+ const dbTools = (refreshed?.tools ?? []) as ChatToolPayload[];
+ const dbResolvedToolCount = dbTools.filter((t) => !!t.result_msg_id).length;
+ const memResolvedToolCount = state.toolState.payloads.filter((t) => !!t.result_msg_id).length;
+ if (
+ dbTools.length > state.toolState.payloads.length ||
+ dbResolvedToolCount > memResolvedToolCount
+ ) {
+ state.toolState = {
+ payloads: [...dbTools],
+ // Only treat tool ids whose `result_msg_id` is already filled in as
+ // persisted. Phase 1 of `persistToolBatch` writes `tools[]` before
+ // creating the `role:'tool'` row (Phase 2), so a refresh that lands
+ // between the two would see an unresolved id. Marking that id as
+ // persisted would cause a subsequent retry of the same tools_calling
+ // event to skip the create (Phase 2) entirely β€” leaving the tool
+ // permanently without a tool message / result_msg_id.
+ persistedIds: new Set(dbTools.filter((t) => !!t.result_msg_id).map((t) => t.id)),
+ };
+ }
+ if (!state.lastModel && refreshed?.model) state.lastModel = refreshed.model;
+ if (!state.lastProvider && refreshed?.provider) state.lastProvider = refreshed.provider;
+
for (const event of params.events) {
const key = eventKey(event);
if (state.processedKeys.has(key)) {
@@ -419,7 +460,14 @@ export class HeterogeneousPersistenceHandler {
const restoredContent = (currentMsg?.content ?? '') as string;
const restoredReasoning = (currentMsg?.reasoning as { content?: string } | null)?.content ?? '';
const restoredTools = (currentMsg?.tools ?? []) as ChatToolPayload[];
- const restoredPersistedIds = new Set(restoredTools.map((t) => t.id));
+ // Phase 1 of `persistToolBatch` writes `tools[]` BEFORE the tool message
+ // row is created (Phase 2 sets `result_msg_id`). Only ids that already
+ // carry a `result_msg_id` are truly persisted β€” restoring an unresolved
+ // id into `persistedIds` would make a retry of the same tools_calling
+ // event skip the Phase 2 create, orphaning the tool forever.
+ const restoredPersistedIds = new Set(
+ restoredTools.filter((t) => !!t.result_msg_id).map((t) => t.id),
+ );
state = {
accumulatedContent: restoredContent,
@@ -482,7 +530,13 @@ export class HeterogeneousPersistenceHandler {
state.accumulatedReasoning = restoredReasoning;
state.toolState = {
payloads: restoredTools,
- persistedIds: new Set(restoredTools.map((tool) => tool.id)),
+ // Same `persistedIds` invariant as `loadOrCreateState`: only ids with a
+ // backfilled `result_msg_id` count as persisted. An unresolved id (Phase
+ // 1 written, Phase 2 not yet) must remain re-createable so a retry on
+ // this replica can complete the tool message.
+ persistedIds: new Set(
+ restoredTools.filter((tool) => !!tool.result_msg_id).map((tool) => tool.id),
+ ),
};
log(
@@ -541,11 +595,19 @@ export class HeterogeneousPersistenceHandler {
const { model, provider, usage } = event.data ?? {};
if (model) state.lastModel = model;
if (provider) state.lastProvider = provider;
- if (!usage) return;
- await this.deps.messageModel.update(state.currentAssistantMessageId, {
- metadata: { usage },
- });
+ // Persist model/provider/usage to DB so a replica that didn't drain this
+ // event can still recover lastModel/lastProvider via the ingest-refresh
+ // path. Previously only `metadata.usage` was written, which left
+ // model/provider in-memory only β€” and the next step boundary on a
+ // different replica created assistants with model=null/provider=null.
+ const update: Record<string, any> = {};
+ if (usage) update.metadata = { usage };
+ if (model) update.model = model;
+ if (provider) update.provider = provider;
+ if (Object.keys(update).length === 0) return;
+
+ await this.deps.messageModel.update(state.currentAssistantMessageId, update);
}
/**
diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 3bf07cf6b15..59ab5164eec 100644
--- a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -499,6 +499,201 @@ describe('HeterogeneousPersistenceHandler', () => {
const toolMsg = [...h.messages.values()].find((m) => m.role === 'tool');
expect(newAssistants[0].parentId).toBe(toolMsg?.id);
});
+
+ it('chains off the tool message even when the prior tools_calling landed on a DIFFERENT replica (multi-replica recovery)', async () => {
+ // Reproduces the prod bug: the in-memory state.toolState gets RESET at
+ // the end of every handleStepStart. If the next step's tools_calling
+ // event then lands on a different replica, this replica's toolState
+ // stays empty, and the FOLLOWING step boundary computes parentId from
+ // that empty state β†’ falls back to currentAssistantMessageId β†’
+ // new assistant chains off the previous ASSISTANT rather than the
+ // previous TOOL message.
+ //
+ // Fix: `ingest()` refresh adopts `tools[]` from DB as authoritative
+ // whenever DB has more resolved tools than memory.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Track topic.metadata so updateMetadata({heteroCurrentMsgId}) becomes
+ // observable to subsequent findById calls β€” the default harness mock is
+ // a no-op which would mask the bug behind a sync-rollback artifact.
+ const metaState: FakeTopicMetadata = {
+ runningOperation: { assistantMessageId: 'asst-init', operationId: 'op-1' },
+ };
+ h.topicModel.findById.mockImplementation(async (id: string) => {
+ if (id !== 'topic-1') return null;
+ return { agentId: null, id, metadata: { ...metaState } };
+ });
+ h.topicModel.updateMetadata.mockImplementation(async (_id: string, patch: any) => {
+ Object.assign(metaState, patch);
+ });
+
+ // ── Batch 1: this replica drains step 1's stream_start ──
+ // No tools yet on this asst β†’ handleStepStart chains step 1 off
+ // 'asst-init' (correct, since asst-init had no tools).
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step1Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init',
+ )!;
+ expect(step1Asst).toBeDefined();
+ expect(step1Asst.parentId).toBe('asst-init');
+
+ // ── Simulate "another replica drained step 1's tools_calling + result" ──
+ // The other replica would have:
+ // 1. Created a tool message
+ // 2. Rewritten step1Asst.tools[] with result_msg_id pointing at it
+ // Both writes hit DB. THIS replica's in-memory state.toolState stays []
+ // (reset by handleStepStart) and has no idea this happened.
+ h.messages.set('tool-other-replica', {
+ agentId: null,
+ content: 'result body',
+ id: 'tool-other-replica',
+ parentId: step1Asst.id,
+ role: 'tool',
+ tool_call_id: 'tc-1',
+ topicId: 'topic-1',
+ });
+ h.messages.set(step1Asst.id, {
+ ...h.messages.get(step1Asst.id)!,
+ model: 'claude-sonnet-4-6',
+ provider: 'claude-code',
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'tc-1',
+ identifier: 'bash',
+ result_msg_id: 'tool-other-replica',
+ type: 'default',
+ },
+ ],
+ });
+
+ // ── Batch 2: step 2 stream_start lands back on THIS replica ──
+ // Pre-fix: state.toolState.payloads is still [] β†’ lastToolMsgId is
+ // undefined β†’ stepParentId falls back to step1Asst.id (BUG).
+ // Post-fix: ingest() refresh reads step1Asst.tools from DB β†’ toolState
+ // gets the tool with result_msg_id β†’ handleStepStart chains correctly.
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 2, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const step2Asst = [...h.messages.values()].find(
+ (m) => m.role === 'assistant' && m.id !== 'asst-init' && m.id !== step1Asst.id,
+ );
+ expect(step2Asst).toBeDefined();
+ expect(step2Asst!.parentId).toBe('tool-other-replica');
+ // And the new assistant should inherit model/provider that the other
+ // replica wrote β€” refresh also restores lastModel/lastProvider so we
+ // no longer create assistants with model=null/provider=null on the
+ // replica that didn't drain step_complete.
+ expect(step2Asst!.model).toBe('claude-sonnet-4-6');
+ expect(step2Asst!.provider).toBe('claude-code');
+ });
+
+ it('handleTurnMetadata persists model/provider to DB so other replicas can recover lastModel/lastProvider', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('step_complete', 0, {
+ model: 'claude-sonnet-4-6',
+ phase: 'turn_metadata',
+ provider: 'claude-code',
+ usage: { inputTokens: 10, outputTokens: 5 },
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Was previously `{ metadata: { usage } }` only β€” now extended to also
+ // carry model/provider so a replica picking up the next step boundary
+ // can read them back from DB even if it never drained this event.
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-init', {
+ metadata: { usage: { inputTokens: 10, outputTokens: 5 } },
+ model: 'claude-sonnet-4-6',
+ provider: 'claude-code',
+ });
+ });
+
+ it('retry recovers an unresolved tool that another replica only Phase-1 registered (no false-positive persistedIds)', async () => {
+ // Race: another replica wrote `assistant.tools[]` (Phase 1) but its
+ // Phase 2 β€” creating the `role:'tool'` row + backfilling
+ // `result_msg_id` β€” hasn't landed yet (or threw). The BatchIngester
+ // then retries the SAME tools_calling event onto THIS replica.
+ //
+ // If `persistedIds` includes the unresolved id, `persistToolBatch`
+ // filters it out of `freshForCreate`, skips the create, and rewrites
+ // `tools[]` unchanged β†’ the tool is orphaned (never gets a tool
+ // message, never gets `result_msg_id`). Fix: only mark ids whose
+ // `result_msg_id` is filled in as persisted.
+ const h = createHarness({
+ assistantMessageId: 'asst-init',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // Pre-populate the initial assistant with a Phase-1-only tool entry
+ // (no `result_msg_id`), simulating the other replica's mid-flight write.
+ h.messages.set('asst-init', {
+ ...h.messages.get('asst-init')!,
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-unresolved',
+ identifier: 'bash',
+ type: 'default',
+ // NOTE: no result_msg_id β€” Phase 2 has not run yet.
+ },
+ ],
+ });
+
+ // Retry of the same tools_calling event lands on this replica.
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, {
+ chunkType: 'tools_calling',
+ toolsCalling: [
+ {
+ apiName: 'Bash',
+ arguments: '{"cmd":"ls"}',
+ id: 'tc-unresolved',
+ identifier: 'bash',
+ type: 'default',
+ },
+ ],
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ // The tool message must have been created (Phase 2 completed via retry)
+ // and assistant.tools[0].result_msg_id must point at it.
+ const toolMsgs = [...h.messages.values()].filter((m) => m.role === 'tool');
+ expect(toolMsgs).toHaveLength(1);
+ expect(toolMsgs[0].tool_call_id).toBe('tc-unresolved');
+
+ const asst = h.messages.get('asst-init')!;
+ expect(asst.tools).toHaveLength(1);
+ expect(asst.tools![0].result_msg_id).toBe(toolMsgs[0].id);
+ });
});
describe('subagent threads', () => {