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(message): report a zero-row update as a failed write (#16983)

Arvin Xu62b3c045cef9
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.ts
index 300d9ba1919..2bb2372a8e2 100644
--- a/packages/database/src/models/__tests__/messages/message.update.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts
@@ -101,6 +101,32 @@ describe('MessageModel Update Tests', () => {
expect(result[0].content).toBe('message 1');
});
+ it('should report success when a row was actually updated', async () => {
+ await serverDB
+ .insert(messages)
+ .values([{ id: '1', userId, role: 'user', content: 'message 1' }]);
+
+ const result = await messageModel.update('1', { content: 'updated message' });
+
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should report failure when no message matches the id', async () => {
+ const result = await messageModel.update('does-not-exist', { content: 'updated message' });
+
+ expect(result).toEqual({ success: false });
+ });
+
+ it('should report failure when the message belongs to another user', async () => {
+ await serverDB
+ .insert(messages)
+ .values([{ id: '1', userId: otherUserId, role: 'user', content: 'message 1' }]);
+
+ const result = await messageModel.update('1', { content: 'updated message' });
+
+ expect(result).toEqual({ success: false });
+ });
+
it('should update message tools', async () => {
// Create test data
await serverDB.insert(messages).values([
@@ -560,6 +586,22 @@ describe('MessageModel Update Tests', () => {
expect(dbResult[0].content).toBe('updated content');
});
+ it('should report failure when no tool message matches the id', async () => {
+ const result = await messageModel.updateToolMessage('tool-msg-missing', {
+ content: 'updated content',
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it('should report failure when a plugin-only patch matches no plugin row', async () => {
+ const result = await messageModel.updateToolMessage('tool-msg-missing', {
+ pluginState: { key: 'value' },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
it('should update metadata only and merge with existing', async () => {
await serverDB.insert(messages).values({
id: 'tool-msg-2',
@@ -745,7 +787,8 @@ describe('MessageModel Update Tests', () => {
content: 'hacked content',
});
- expect(result.success).toBe(true);
+ // Ownership filters the row out, so the patch lands nowhere β€” a lost write.
+ expect(result.success).toBe(false);
// Verify content was NOT updated
const dbResult = await serverDB
@@ -780,15 +823,13 @@ describe('MessageModel Update Tests', () => {
});
it('should return success false on error', async () => {
- // Don't create any message - this should cause the transaction to succeed
- // but not update anything (which is still success)
+ // The transaction itself succeeds, but the update matches no row. Batched
+ // writers key their retry ledger off `success`, so this must not be true.
const result = await messageModel.updateToolMessage('non-existent-id', {
content: 'content',
});
- // The method returns success: true even for non-existent messages
- // because the update query doesn't fail, it just doesn't match any rows
- expect(result.success).toBe(true);
+ expect(result.success).toBe(false);
});
it('should handle empty params gracefully', async () => {
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 1ce5aceef93..3eb165b3478 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2213,6 +2213,10 @@ export class MessageModel {
metadata || usageToWrite
? { ...metadata, ...(usageToWrite && { usage: usageToWrite }) }
: undefined;
+ // A patch that matches no row is a lost write, not a no-op: the caller asked
+ // to persist content onto `id` and it went nowhere. Batched writers key their
+ // retry ledger off this flag, so reporting success here silently drops data.
+ let matchedRow = false;
try {
await runTimedStage(
timing,
@@ -2269,6 +2273,8 @@ export class MessageModel {
{ hasMetadata: !!metadataPatch, valueKeys: Object.keys(message) },
);
+ matchedRow = !!updated;
+
if (
updated?.topicId && // When this write carries token usage (assistant finalize / hetero
// step), recompute the topic's denormalized usage rollup from its
@@ -2291,6 +2297,11 @@ export class MessageModel {
},
);
+ if (!matchedRow) {
+ console.error(`Update message error: no message matched id ${id}`);
+ return { success: false };
+ }
+
return { success: true };
} catch (error) {
console.error('Update message error:', error);
@@ -2427,6 +2438,10 @@ export class MessageModel {
): Promise<{ success: boolean }> => {
const { content, metadata, pluginState, pluginError } = params;
+ // `undefined` while no branch has looked for the row yet; see `update` above
+ // for why a write that matches nothing must not report success.
+ let matchedRow: boolean | undefined;
+
try {
await this.db.transaction(async (trx) => {
// Update messages table (content, metadata)
@@ -2446,10 +2461,13 @@ export class MessageModel {
}
if (Object.keys(messageUpdateData).length > 0) {
- await trx
+ const [updated] = await trx
.update(messages)
.set(messageUpdateData)
- .where(and(eq(messages.id, id), this.ownership()));
+ .where(and(eq(messages.id, id), this.ownership()))
+ .returning({ id: messages.id });
+
+ matchedRow = !!updated;
}
}
@@ -2459,6 +2477,10 @@ export class MessageModel {
where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),
});
+ // A plugin-only patch never touches `messages`, so the plugin row is
+ // the only evidence the tool message exists.
+ if (matchedRow === undefined) matchedRow = !!pluginItem;
+
if (pluginItem) {
const pluginUpdateData: Record<string, any> = {};
@@ -2480,6 +2502,11 @@ export class MessageModel {
}
});
+ if (matchedRow === false) {
+ console.error(`Update tool message error: no tool message matched id ${id}`);
+ return { success: false };
+ }
+
return { success: true };
} catch (error) {
console.error('Update tool message error:', error);
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 2d797fa5c3b..3b671437758 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1122,6 +1122,96 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ // ────────────────────────────────────────────────────
+ // Lost-write recovery β€” the tpc_mMYve6mAIT4J incident
+ // ────────────────────────────────────────────────────
+
+ describe('lost-write recovery (FK cascade)', () => {
+ /**
+ * End-to-end replay of the original incident against a fake table that
+ * enforces the two invariants the real `messages` table does:
+ * - `parent_id` is a FK: a create whose parent row is absent throws 23503.
+ * - an update whose id matches no row reports `success: false` (a lost
+ * write, not a no-op) β€” the semantic this PR restored.
+ *
+ * A single transient `createMessage` failure orphans the seed of a spine
+ * chain (`asst β†’ asst β†’ asst …`); every later assistant then fails the FK,
+ * and every content flush in between lands on a row that does not exist.
+ * The fix must recover ALL of it: replay the creates in dependency order,
+ * then replay the content the zero-row updates stashed.
+ */
+ const makeFakeTable = (seedId: string) => {
+ const rows = new Map<string, any>([[seedId, { content: '', id: seedId, role: 'assistant' }]]);
+ let firstAssistantBlipped = false;
+
+ const create = async (params: any) => {
+ // Seed the cascade: the first fresh assistant create fails once, exactly
+ // like the single dropped write that started the real incident.
+ if (params.role === 'assistant' && !firstAssistantBlipped) {
+ firstAssistantBlipped = true;
+ throw new Error('transient write failure');
+ }
+ if (params.parentId && !rows.has(params.parentId)) {
+ throw new Error(`FK violation: parent ${params.parentId} is absent`);
+ }
+ rows.set(params.id, { ...params, content: params.content ?? '' });
+ return { id: params.id };
+ };
+
+ const update = async (id: string, value: any) => {
+ const row = rows.get(id);
+ if (!row) return { success: false };
+ Object.assign(row, value);
+ return { success: true };
+ };
+
+ return { create, rows, update };
+ };
+
+ it('recovers every assistant + its content after a create failure cascades down the spine', async () => {
+ const store = createMockStore({
+ dbMessagesMap: {
+ 'main_agent-1_topic-1': [
+ { content: '', id: 'ast-initial', role: 'assistant', topicId: 'topic-1' },
+ ],
+ },
+ });
+ const table = makeFakeTable('ast-initial');
+ mockCreateMessage.mockImplementation(table.create);
+ mockUpdateMessage.mockImplementation(table.update);
+
+ // msg_01 reuses the seed; msg_02..04 are fresh spine assistants, each
+ // parented off the previous one β€” so orphaning msg_02 takes 03 and 04 too.
+ const texts = {
+ msg_01: 'seed turn answer',
+ msg_02: 'first fresh turn',
+ msg_03: 'second fresh turn',
+ msg_04: 'final answer that must survive',
+ };
+ await runWithEvents(
+ [
+ ccInit(),
+ ccText('msg_01', texts.msg_01),
+ ccText('msg_02', texts.msg_02),
+ ccText('msg_03', texts.msg_03),
+ ccText('msg_04', texts.msg_04),
+ ccResult(),
+ ],
+ { store },
+ );
+
+ // Every assistant turn is present AND carries its text β€” no empty shells,
+ // nothing dropped. This is the exact assertion that fails pre-fix: the
+ // content updates "succeeded" against absent rows, so the ledger that
+ // would have replayed them stayed empty.
+ const persistedContent = [...table.rows.values()]
+ .filter((r) => r.role === 'assistant')
+ .map((r) => r.content)
+ .sort();
+ expect(persistedContent).toEqual(Object.values(texts).sort());
+ });
+ });
+
// ────────────────────────────────────────────────────
// Error handling
// ────────────────────────────────────────────────────
@@ -4409,6 +4499,55 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ it('replays a tool-parented signal assistant only after its tool row lands', async () => {
+ // A signal turn parents off the run's last TOOL row, not the spine. So a
+ // create ledger that drains every assistant before any tool row retries
+ // the signal assistant while its parent is still missing, burns its only
+ // retry on a guaranteed FK violation, and drops the turn.
+ const persisted = new Set<string>(['ast-initial']);
+ let toolCreateBlips = 1;
+ mockCreateMessage.mockImplementation(async (params: any) => {
+ // One transient failure on the tool row β€” the seed of the cascade.
+ if (params.role === 'tool' && toolCreateBlips > 0) {
+ toolCreateBlips -= 1;
+ throw new Error('transient write failure');
+ }
+ // Everything else obeys `messages.parent_id`, like the real table does.
+ if (params.parentId && !persisted.has(params.parentId)) {
+ throw new Error(`FK violation: parent ${params.parentId} is not present`);
+ }
+ persisted.add(params.id);
+ return { id: params.id };
+ });
+
+ await runWithEvents([
+ ccInit(),
+ ccMessageStart('msg_01'),
+ ccToolUse('msg_01', 'toolu_mon_0', 'Monitor', { shell: 'every 1s' }),
+ ccTaskStarted('task_a', 'toolu_mon_0'),
+ ccToolResult('toolu_mon_0', 'Monitor started'),
+ // Natural confirmation turn β€” parents off the spine.
+ ccMessageStart('msg_02'),
+ ccText('msg_02', 'Monitor started.'),
+ // Monitor pushed stdout β†’ signal callback, parents off the tool row.
+ ccMessageStart('msg_03'),
+ ccText('msg_03', 'tick 1'),
+ ccResult(),
+ ]);
+
+ const toolCreate = mockCreateMessage.mock.calls.find(([p]: any) => p.role === 'tool');
+ const signalCreate = mockCreateMessage.mock.calls.find(
+ ([p]: any) => p.role === 'assistant' && p.metadata?.signal,
+ );
+ expect(toolCreate).toBeDefined();
+ expect(signalCreate).toBeDefined();
+ expect(signalCreate![0].parentId).toBe(toolCreate![0].id);
+
+ // Both rows must exist once the run settles, or the signal turn is lost.
+ expect(persisted.has(toolCreate![0].id)).toBe(true);
+ expect(persisted.has(signalCreate![0].id)).toBe(true);
+ });
+
it('does NOT stamp metadata.signal on turns following a tool_result (main-chain follow-up)', async () => {
const idCounter = { tool: 0, assistant: 0 };
mockCreateMessage.mockImplementation(async (params: any) => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index c3a6695a6d5..5b09b0362a9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -787,10 +787,28 @@ export const executeHeterogeneousAgent = async (
* be lost once the reducer clears `accContent` on terminal.
*/
const pendingMainFlush = new Map<string, Record<string, any>>();
- const pendingMainCreates = new Map<
+ /**
+ * Retry ledger for every failed row create β€” assistants AND tool rows, in one
+ * Map on purpose. `messages.parent_id` is a real FK and the parent graph is
+ * not layered: a tool row hangs off its assistant, but a signal/reactive
+ * assistant hangs off the run's last TOOL row (see `computeTurnParentId`).
+ * Splitting the ledger by role would replay a tool-parented assistant before
+ * its parent tool row and lose the turn. Enqueue order IS dependency order β€”
+ * the reducer can only name a parent it has already emitted a create for β€”
+ * and `Map` preserves insertion order, so one in-order drain is correct with
+ * no knowledge of which parent kind any given row uses.
+ */
+ const pendingCreates = new Map<
string,
Extract<MessageBatchOperation, { type: 'createMessage' }>['message']
>();
+ /** Retry ledger for tool result content / plugin state. */
+ const pendingToolFlush = new Map<string, ToolMessageUpdateOperation['value']>();
+
+ /** Later intents carry a superset of the payload, so a shallow merge wins. */
+ const stashMainFlush = (messageId: string, update: Record<string, any>) => {
+ pendingMainFlush.set(messageId, { ...pendingMainFlush.get(messageId), ...update });
+ };
/** Serializes async persist operations so ordering is stable. */
let persistQueue: Promise<void> = Promise.resolve();
/**
@@ -1004,16 +1022,15 @@ export const executeHeterogeneousAgent = async (
return;
}
- messageWriteBatcher.enqueueToolMessageUpdate(
- toolMsgId,
- {
- content,
- pluginError: isError ? { message: content } : undefined,
- pluginState,
- },
- messageWriteCtx,
- (err) => console.error('[HeterogeneousAgent] Failed to update tool message content:', err),
- );
+ const toolUpdate = {
+ content,
+ pluginError: isError ? { message: content } : undefined,
+ pluginState,
+ };
+ messageWriteBatcher.enqueueToolMessageUpdate(toolMsgId, toolUpdate, messageWriteCtx, (err) => {
+ console.error('[HeterogeneousAgent] Failed to update tool message content:', err);
+ pendingToolFlush.set(toolMsgId, { ...pendingToolFlush.get(toolMsgId), ...toolUpdate });
+ });
};
const applyInterventionRequest = async (data: AgentInterventionRequestData): Promise<boolean> => {
const toolMsgId = toolMsgIdByCallId.get(data.toolCallId);
@@ -1446,7 +1463,7 @@ export const executeHeterogeneousAgent = async (
} as any;
messageWriteBatcher.enqueueCreateMessage(messageToCreate, (err) => {
console.error('[HeterogeneousAgent] Failed to create step assistant:', err);
- pendingMainCreates.set(intent.messageId, messageToCreate);
+ pendingCreates.set(intent.messageId, messageToCreate);
});
get().internal_dispatchMessage(
{ id: intent.messageId, type: 'createMessage', value: messageToCreate },
@@ -1472,10 +1489,7 @@ export const executeHeterogeneousAgent = async (
messageWriteCtx,
(err) => {
console.error('[HeterogeneousAgent] Failed to flush main assistant:', err);
- pendingMainFlush.set(intent.messageId, {
- ...pendingMainFlush.get(intent.messageId),
- ...update,
- });
+ stashMainFlush(intent.messageId, update);
},
);
// Mirror ONLY model/provider into the store: content/reasoning already
@@ -1542,13 +1556,21 @@ export const executeHeterogeneousAgent = async (
} as any;
};
+ // The ledger always carries the phase-3 shape: by the time it replays,
+ // the tool rows exist, and stashing the phase-1 shape would let a stale
+ // `tools[]` (no `result_msg_id`) clobber a phase-3 write that landed.
+ const finalAssistantUpdate = buildUpdate(true);
+
// Phase 1: pre-register assistant.tools[] (no result_msg_id yet) so the
// conversation-flow parser finds matching ids the moment tool rows land.
messageWriteBatcher.enqueueUpdateMessage(
intent.assistantMessageId,
buildUpdate(false),
messageWriteCtx,
- (err) => console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err),
+ (err) => {
+ console.error('[HeterogeneousAgent] Failed to pre-register main tools:', err);
+ stashMainFlush(intent.assistantMessageId, finalAssistantUpdate);
+ },
);
// Phase 2: create rows for new tools with their pre-allocated ids and
@@ -1556,7 +1578,10 @@ export const executeHeterogeneousAgent = async (
for (const x of intent.tools) {
if (!x.isNew) continue;
const toolMsg = buildToolMessage(x);
- messageWriteBatcher.enqueueCreateMessage(toolMsg);
+ messageWriteBatcher.enqueueCreateMessage(toolMsg, (err) => {
+ console.error('[HeterogeneousAgent] Failed to create tool message:', err);
+ pendingCreates.set(x.toolMessageId, toolMsg);
+ });
toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);
mainToolCallIds.add(x.payload.id);
get().internal_dispatchMessage(
@@ -1566,12 +1591,14 @@ export const executeHeterogeneousAgent = async (
}
// Phase 3: backfill result_msg_id on assistant.tools[].
- const finalAssistantUpdate = buildUpdate(true);
messageWriteBatcher.enqueueUpdateMessage(
intent.assistantMessageId,
finalAssistantUpdate,
messageWriteCtx,
- (err) => console.error('[HeterogeneousAgent] Failed to finalize main tools:', err),
+ (err) => {
+ console.error('[HeterogeneousAgent] Failed to finalize main tools:', err);
+ stashMainFlush(intent.assistantMessageId, finalAssistantUpdate);
+ },
);
get().internal_dispatchMessage(
{
@@ -1618,8 +1645,14 @@ export const executeHeterogeneousAgent = async (
...(intent.model && { model: intent.model }),
...(intent.provider && { provider: intent.provider }),
};
- messageWriteBatcher.enqueueUpdateMessage(intent.messageId, update, messageWriteCtx, (err) =>
- console.error('[HeterogeneousAgent] Failed to record main usage:', err),
+ messageWriteBatcher.enqueueUpdateMessage(
+ intent.messageId,
+ update,
+ messageWriteCtx,
+ (err) => {
+ console.error('[HeterogeneousAgent] Failed to record main usage:', err);
+ stashMainFlush(intent.messageId, update);
+ },
);
// Same payload into the store so usage + model/provider render live β€”
// the subagent interpreter's `recordUsage` already does this via
@@ -1975,12 +2008,15 @@ export const executeHeterogeneousAgent = async (
const queueDrained = await waitForPersistQueue(persistQueue, 'terminal');
if (queueDrained) {
- for (const [messageId, messageToCreate] of pendingMainCreates) {
+ // Order is load-bearing: rows first, in the order they were enqueued
+ // (that is their FK dependency order), then the content patches β€”
+ // an update against a row that does not exist yet matches zero rows.
+ for (const [messageId, messageToCreate] of pendingCreates) {
try {
await messageService.createMessage(messageToCreate);
- pendingMainCreates.delete(messageId);
+ pendingCreates.delete(messageId);
} catch (err) {
- console.error('[HeterogeneousAgent] Failed to replay main assistant create:', err);
+ console.error('[HeterogeneousAgent] Failed to replay message create:', err);
}
}
@@ -1993,6 +2029,21 @@ export const executeHeterogeneousAgent = async (
}
}
+ for (const [messageId, update] of pendingToolFlush) {
+ try {
+ const result = await messageService.updateToolMessage(messageId, update, {
+ agentId: context.agentId,
+ topicId: context.topicId,
+ });
+ if (result?.success === false) {
+ throw new Error(`updateToolMessage returned success=false for ${messageId}`);
+ }
+ pendingToolFlush.delete(messageId);
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to replay tool flush:', err);
+ }
+ }
+
// Replay any subagent flush that failed transiently mid-stream, pinned
// to its original in-thread assistant (NOT the terminal row).
for (const [threadId, pending] of pendingSubagentFlush) {