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): split message write batches so a backlog is not rejected (#23297)

YuTengjing6432361443be
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 77a384cdf22..bb76926a122 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -907,12 +907,12 @@ export const executeHeterogeneousAgent = async (
batchMutate: (
messageService as { batchMutate?: (operations: MessageBatchOperation[]) => Promise<any> }
).batchMutate,
+ beforeBatch: () => pendingCreateLedger.retryNew(),
createMessage: messageService.createMessage,
onCreated: get().internal_confirmClientMessages,
updateMessage: messageService.updateMessage,
updateToolMessage: messageService.updateToolMessage,
});
-
/** Failed-create retry ledger + the FK-parent barrier for straight-through writes. */
const pendingCreateLedger = createPendingCreateLedger({
createMessage: messageService.createMessage,
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
index ee0c7d7e6f3..2688c94d6f9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts
@@ -1,6 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createMessageWriteBatcher } from './messageWriteBatcher';
+import {
+ createMessageWriteBatcher,
+ HETERO_MESSAGE_WRITE_BATCH_MAX_BYTES,
+} from './messageWriteBatcher';
const createDeps = () => ({
batchMutate: vi.fn().mockResolvedValue({ results: [], success: true }),
@@ -174,6 +177,71 @@ describe('createMessageWriteBatcher', () => {
expect(deps.batchMutate.mock.calls[0][0]).toHaveLength(50);
});
+ /**
+ * Production failure: while one request was in flight the queue grew past 200
+ * operations, the next flush sent the whole backlog, and the router rejected it
+ * (400), so every create in it was lost and their children hit
+ * `messages_parent_id_messages_id_fk`.
+ */
+ it('splits a backlog that piled up behind an in-flight request', async () => {
+ const deps = createDeps();
+ let release!: () => void;
+ deps.batchMutate.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = () => resolve({ results: [], success: true });
+ }),
+ );
+ const batcher = createMessageWriteBatcher(deps);
+
+ batcher.enqueueCreateMessage(createRow('first'));
+ const firstFlush = batcher.flush('test');
+ await vi.waitFor(() => expect(deps.batchMutate).toHaveBeenCalledTimes(1));
+
+ for (let i = 0; i < 260; i += 1) batcher.enqueueUpdateMessage(`msg-${i}`, { content: 'x' });
+ release();
+ await firstFlush;
+ await batcher.flush('test');
+
+ const sizes = deps.batchMutate.mock.calls.map((call) => call[0].length);
+ expect(sizes).toEqual([1, 50, 50, 50, 50, 50, 10]);
+ });
+
+ it('splits by serialized size so a request body stays under the budget', async () => {
+ const deps = createDeps();
+ const batcher = createMessageWriteBatcher(deps);
+ const content = 'x'.repeat(HETERO_MESSAGE_WRITE_BATCH_MAX_BYTES / 2);
+
+ batcher.enqueueUpdateMessage('msg-a', { content });
+ batcher.enqueueUpdateMessage('msg-b', { content });
+ batcher.enqueueUpdateMessage('msg-c', { content: 'small' });
+ await batcher.flush('test');
+
+ const ids = deps.batchMutate.mock.calls.map((call) => call[0].map((op: any) => op.id));
+ expect(ids).toEqual([['msg-a'], ['msg-b', 'msg-c']]);
+ });
+
+ it('runs beforeBatch ahead of every batch and keeps flushing when it throws', async () => {
+ const order: string[] = [];
+ const deps = {
+ ...createDeps(),
+ beforeBatch: vi.fn().mockImplementation(async () => {
+ order.push('before');
+ if (order.length === 1) throw new Error('retry failed');
+ }),
+ };
+ deps.batchMutate.mockImplementation(async (ops: any[]) => {
+ order.push(`batch:${ops.length}`);
+ return { results: [], success: true };
+ });
+ const batcher = createMessageWriteBatcher(deps);
+
+ for (let i = 0; i < 51; i += 1) batcher.enqueueUpdateMessage(`msg-${i}`, { content: 'x' });
+ await batcher.flush('test');
+
+ expect(order).toEqual(['before', 'batch:50', 'before', 'batch:1']);
+ });
+
it('falls back to per-op writes when batchMutate is unavailable', async () => {
const deps = { ...createDeps(), batchMutate: undefined };
const batcher = createMessageWriteBatcher(deps as any);
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
index 521c1087945..3f1f53c7421 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts
@@ -5,7 +5,30 @@ import type {
} from '@/services/message';
export const HETERO_MESSAGE_WRITE_BATCH_IDLE_MS = 5_000;
+/**
+ * Upper bound of ONE `batchMutate` request, not just the auto-flush trigger. The
+ * lambda router rejects a request over 200 operations as a whole (400), so a
+ * backlog sent in one piece lost every create in it.
+ */
export const HETERO_MESSAGE_WRITE_BATCH_MAX_OPS = 50;
+/**
+ * Serialized-payload budget of one `batchMutate` request. Vercel rejects request
+ * bodies over 4.5 MB (413) and tRPC may batch other procedures into the same HTTP
+ * request, so stay well below it. A single larger operation is still sent alone.
+ */
+export const HETERO_MESSAGE_WRITE_BATCH_MAX_BYTES = 2 * 1024 * 1024;
+
+const textEncoder = new TextEncoder();
+
+/** Byte size of the fields `messageService.batchMutate` actually sends. */
+const estimateOperationBytes = (operation: QueuedMessageWriteOperation) =>
+ textEncoder.encode(
+ JSON.stringify(
+ operation.type === 'createMessage'
+ ? { message: operation.message, type: operation.type }
+ : { id: operation.id, type: operation.type, value: operation.value },
+ ),
+ ).length;
type MessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateMessage' }>;
export type ToolMessageUpdateOperation = Extract<
@@ -57,13 +80,19 @@ const mergeMessageUpdateValue = (
*/
export const createMessageWriteBatcher = (deps: {
batchMutate?: (operations: MessageBatchOperation[]) => Promise<any>;
+ /**
+ * Runs before each batch is sent. The executor uses it to retry creates that
+ * just failed, so the next batch's children find their FK parent instead of
+ * failing one after another until the run's terminal replay.
+ */
+ beforeBatch?: () => Promise<void>;
createMessage: typeof messageService.createMessage;
/** Ids of rows whose create the server acknowledged. */
onCreated?: (ids: string[]) => void;
updateMessage: typeof messageService.updateMessage;
updateToolMessage: typeof messageService.updateToolMessage;
}) => {
- let operations: QueuedMessageWriteOperation[] = [];
+ const operations: QueuedMessageWriteOperation[] = [];
let flushChain: Promise<void> = Promise.resolve();
let idleTimer: ReturnType<typeof setTimeout> | undefined;
@@ -137,13 +166,38 @@ export const createMessageWriteBatcher = (deps: {
}
};
+ /**
+ * Take the next request's worth of operations off the queue. While a request is
+ * in flight the queue keeps growing, so the backlog must be split here rather
+ * than relying on the max-ops auto-flush to keep it small.
+ */
+ const takeBatch = () => {
+ let bytes = 0;
+ let count = 0;
+ for (const operation of operations) {
+ if (count >= HETERO_MESSAGE_WRITE_BATCH_MAX_OPS) break;
+ const size = estimateOperationBytes(operation);
+ if (count > 0 && bytes + size > HETERO_MESSAGE_WRITE_BATCH_MAX_BYTES) break;
+ bytes += size;
+ count += 1;
+ }
+ return operations.splice(0, count);
+ };
+
+ const runBeforeBatch = async () => {
+ try {
+ await deps.beforeBatch?.();
+ } catch (err) {
+ console.error('[HeterogeneousAgent] beforeBatch hook failed:', err);
+ }
+ };
+
const flush = async (_reason: string) => {
clearIdleTimer();
flushChain = flushChain.then(async () => {
while (operations.length > 0) {
- const batch = operations;
- operations = [];
- await runBatch(batch);
+ await runBeforeBatch();
+ await runBatch(takeBatch());
}
});
await flushChain;
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.test.ts
index 121263aab92..d162b3318b4 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.test.ts
@@ -99,6 +99,50 @@ describe('createPendingCreateLedger', () => {
});
});
+ describe('retryNew', () => {
+ it('replays a fresh failure once, then leaves a still-failing row to drain', async () => {
+ const createMessage = vi.fn().mockRejectedValue(new Error('index row too large'));
+ const ledger = createPendingCreateLedger({
+ createMessage,
+ flush: vi.fn().mockResolvedValue(undefined),
+ });
+
+ ledger.add('msg-a', row('msg-a'));
+ await ledger.retryNew();
+ await ledger.retryNew();
+
+ expect(createMessage).toHaveBeenCalledTimes(1);
+ expect(ledger.has('msg-a')).toBe(true);
+
+ await ledger.drain();
+ expect(createMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not create a row twice when replays overlap', async () => {
+ let release!: () => void;
+ const createMessage = vi.fn().mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ const ledger = createPendingCreateLedger({
+ createMessage,
+ flush: vi.fn().mockResolvedValue(undefined),
+ });
+
+ ledger.add('msg-a', row('msg-a'));
+ const first = ledger.retryNew();
+ const second = ledger.drain();
+ await vi.waitFor(() => expect(createMessage).toHaveBeenCalledTimes(1));
+ release();
+ await Promise.all([first, second]);
+
+ expect(createMessage).toHaveBeenCalledTimes(1);
+ expect(ledger.size).toBe(0);
+ });
+ });
+
describe('drain', () => {
it('keeps rows that fail again so a later pass can retry them', async () => {
const createMessage = vi
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts
index b0f6e23d5e3..88b3e7ff123 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts
@@ -19,28 +19,50 @@ export const createPendingCreateLedger = (deps: {
flush: (reason: string) => Promise<void>;
}) => {
const pending = new Map<string, CreateMessageRow>();
+ /** Rows replayed at least once; `retryNew` skips them so a row that fails deterministically is not re-sent before every batch. */
+ const retried = new Set<string>();
+ /**
+ * Replays run one at a time: the batcher's pre-batch retry and a subagent's
+ * `ensureParentPersisted` can overlap, and two passes over the same row would
+ * create it twice (`messages_pkey`).
+ */
+ let replayChain: Promise<void> = Promise.resolve();
+
+ const replay = (skipRetried: boolean) => {
+ replayChain = replayChain.then(async () => {
+ for (const [messageId, message] of pending) {
+ if (skipRetried && retried.has(messageId)) continue;
+ retried.add(messageId);
+ try {
+ await deps.createMessage(message);
+ pending.delete(messageId);
+ } catch (err) {
+ console.error('[HeterogeneousAgent] Failed to replay message create:', err);
+ }
+ }
+ });
+ return replayChain;
+ };
/**
* Replay the ledger in insertion order (= FK dependency order). Best-effort: a
* row that fails again stays in the ledger, so callers that need a specific row
* to exist must re-check afterwards rather than trust this to have emptied it.
*/
- const drain = async () => {
- for (const [messageId, message] of pending) {
- try {
- await deps.createMessage(message);
- pending.delete(messageId);
- } catch (err) {
- console.error('[HeterogeneousAgent] Failed to replay message create:', err);
- }
- }
- };
+ const drain = () => replay(false);
return {
add: (messageId: string, message: CreateMessageRow) => pending.set(messageId, message),
drain,
+ /**
+ * Replay only rows that have not been retried yet. Wired to the write batcher's
+ * `beforeBatch`, so a create that failed (a rejected request, a network error)
+ * lands before the next batch sends the children that FK to it.
+ */
+ retryNew: () => (pending.size > 0 ? replay(true) : Promise.resolve()),
+
/**
* Gate a straight-through write on its FK parent actually existing in the DB.
*