π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): drain the message write batcher before subagent writes (#17148)
Arvin Xu2f941d164a15
diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex 7f5fe5cdae4..b9a86c55be8 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -287,12 +287,45 @@ describe('MessageService', () => {});expect(result).toEqual({results: [- { id: 'missing-assistant', index: 0, success: false, type: 'createMessage' },+ {+ error: 'create failed',+ id: 'missing-assistant',+ index: 0,+ success: false,+ type: 'createMessage',+ },{ id: 'still-runs', index: 1, success: true, type: 'updateMessage' },],success: false,});});++ it('surfaces the driver cause of a failed write, not the drizzle query wrapper', async () => {+ // Drizzle wraps the driver error: its own message is the whole failed+ // statement + params, while the actionable part (violated constraint,+ // SQLSTATE) only lives on `cause`. A subagent row written ahead of its+ // parent lands here, and the caller needs to see *why* to act on it.+ const driverError = Object.assign(+ new Error('insert or update on table "messages" violates foreign key constraint'),+ { code: '23503', constraint: 'messages_parent_id_messages_id_fk' },+ );+ const drizzleError = Object.assign(new Error('Failed query: insert into "messages" ...'), {+ cause: driverError,+ });+ vi.mocked(mockMessageModel.create).mockRejectedValueOnce(drizzleError);++ const result = await messageService.batchMutate([+ {+ message: { content: '', id: 'orphan', parentId: 'not-yet-written', role: 'user' } as any,+ type: 'createMessage',+ },+ ]);++ expect(result.success).toBe(false);+ expect(result.results[0].error).toBe(+ 'messages_parent_id_messages_id_fk | 23503 | insert or update on table "messages" violates foreign key constraint',+ );+ });});describe('updateMetadata', () => {diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex 60609cad269..e9a07d085a8 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -37,6 +37,25 @@ const logMessageTiming = (const createModelTiming = (options: QueryOptions | undefined, prefix: string) =>createPrefixedTimingContext(toTimingContext(options), prefix);+/**+ * Reduce a failed write to something the caller can act on. Drizzle wraps driver+ * errors in a generic `Failed query: insert into ...` whose message is the whole+ * statement plus its params β too noisy to return, and it may carry message+ * content. The driver error underneath (`cause`) holds the actionable part: the+ * SQLSTATE and the violated constraint.+ */+const describeBatchMutateError = (error: unknown): string => {+ const cause = (error as { cause?: unknown } | undefined)?.cause;+ const driverError = (cause ?? error) as+ { code?: string; constraint?: string; message?: string } | undefined;++ const detail = [driverError?.constraint, driverError?.code, driverError?.message]+ .filter(Boolean)+ .join(' | ');++ return (detail || String(error)).slice(0, 300);+};+interface CreateMessageResult {id: string;messages: any[];@@ -153,6 +172,7 @@ export class MessageService {*/async batchMutate(operations: MessageBatchOperation[]): Promise<{results: {+ error?: string;id?: string;index: number;success: boolean;@@ -161,6 +181,7 @@ export class MessageService {success: boolean;}> {const results: {+ error?: string;id?: string;index: number;success: boolean;@@ -186,6 +207,7 @@ export class MessageService {} catch (error) {console.error('[MessageService] batchMutate operation failed:', error);results.push({+ error: describeBatchMutateError(error),id: operation.type === 'createMessage' ? operation.message.id : operation.id,index,success: false,diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex d42e4b9ed35..19b14e6848e 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -62,6 +62,7 @@ export type MessageBatchOperation =export interface MessageBatchMutationResult {results?: Array<{+ error?: string;id?: string;index: number;success: boolean;@@ -72,8 +73,12 @@ export interface MessageBatchMutationResult {export class MessageBatchMutationError extends Error {constructor(public readonly result: MessageBatchMutationResult) {- const failedCount = result.results?.filter((item) => !item.success).length;- super(`Message batch mutation failed for ${failedCount || 'unknown'} operation(s)`);+ const failed = result.results?.filter((item) => !item.success) ?? [];+ const reasons = [...new Set(failed.map((item) => item.error).filter(Boolean))];+ super(+ `Message batch mutation failed for ${failed.length || 'unknown'} operation(s)` ++ (reasons.length > 0 ? `: ${reasons.join('; ')}` : ''),+ );}}diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 0b4d840fb97..3e802b3aa75 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -70,6 +70,8 @@ import { labPreferSelectors } from '@/store/user/selectors';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';+import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';+import { createPendingCreateLedger } from './pendingCreateLedger';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */const generateThreadId = () => `thd_${createNanoId(16)()}`;@@ -394,47 +396,9 @@ interface SubagentStoreDispatcher {update: (id: string, value: Partial<UIChatMessage>) => void;}-const HETERO_MESSAGE_WRITE_BATCH_IDLE_MS = 5_000;-const HETERO_MESSAGE_WRITE_BATCH_MAX_OPS = 50;const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;const HETERO_TERMINAL_EVENT_GRACE_TIMEOUT_MS = 3_000;-type MessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateMessage' }>;-type ToolMessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateToolMessage' }>;--type QueuedMessageWriteOperation =- | (Extract<MessageBatchOperation, { type: 'createMessage' }> & {- ctx?: never;- onFailure?: (error: unknown) => void;- })- | (MessageUpdateOperation & {- ctx?: MessageQueryContext;- onFailure?: (error: unknown) => void;- })- | (ToolMessageUpdateOperation & {- ctx?: MessageQueryContext;- onFailure?: (error: unknown) => void;- });--const mergeMessageUpdateValue = (- previous: MessageUpdateOperation['value'],- next: MessageUpdateOperation['value'],-): MessageUpdateOperation['value'] => {- const metadata =- previous.metadata || next.metadata- ? {- ...(previous.metadata as Record<string, any> | undefined),- ...(next.metadata as Record<string, any> | undefined),- }- : undefined;-- return {- ...previous,- ...next,- ...(metadata ? { metadata } : {}),- };-};-const waitForPersistQueue = async (queue: Promise<void>,label: string,@@ -467,147 +431,19 @@ const waitForPersistQueue = async (return true;};-const createMessageWriteBatcher = (deps: {- batchMutate?: (operations: MessageBatchOperation[]) => Promise<any>;- createMessage: typeof messageService.createMessage;- updateMessage: typeof messageService.updateMessage;- updateToolMessage: typeof messageService.updateToolMessage;-}) => {- let operations: QueuedMessageWriteOperation[] = [];- let flushChain: Promise<void> = Promise.resolve();- let idleTimer: ReturnType<typeof setTimeout> | undefined;-- const clearIdleTimer = () => {- if (!idleTimer) return;- clearTimeout(idleTimer);- idleTimer = undefined;- };-- const notifyFailure = (operation: QueuedMessageWriteOperation, error: unknown) => {- operation.onFailure?.(error);- };-- const runIndividual = async (operation: QueuedMessageWriteOperation) => {- if (operation.type === 'createMessage') {- await deps.createMessage(operation.message);- return;- }-- if (operation.type === 'updateToolMessage') {- const result = await deps.updateToolMessage(operation.id, operation.value, operation.ctx);- if (result?.success === false) notifyFailure(operation, result);- return;- }-- const result = await deps.updateMessage(operation.id, operation.value, operation.ctx);- if (result?.success === false) notifyFailure(operation, result);- };-- const runBatch = async (batch: QueuedMessageWriteOperation[]) => {- if (deps.batchMutate) {- try {- const result = await deps.batchMutate(batch as unknown as MessageBatchOperation[]);- const failedIndexes = new Set<number>(- (result?.results ?? [])- .filter((item: { index: number; success: boolean }) => !item.success)- .map((item: { index: number }) => item.index),- );-- if (result?.success === false && failedIndexes.size === 0) {- for (const [index] of batch.entries()) failedIndexes.add(index);- }-- for (const index of failedIndexes) {- notifyFailure(batch[index], result);- }- return;- } catch (err) {- console.error('[HeterogeneousAgent] Failed to flush message write batch:', err);- for (const operation of batch) notifyFailure(operation, err);- return;- }- }-- for (const operation of batch) {- try {- await runIndividual(operation);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to flush message write operation:', err);- notifyFailure(operation, err);- }- }- };-- const flush = async (_reason: string) => {- clearIdleTimer();- flushChain = flushChain.then(async () => {- while (operations.length > 0) {- const batch = operations;- operations = [];- await runBatch(batch);- }- });- await flushChain;- };-- const scheduleIdleFlush = () => {- clearIdleTimer();- idleTimer = setTimeout(() => {- void flush('idle');- }, HETERO_MESSAGE_WRITE_BATCH_IDLE_MS);- };-- const enqueue = (operation: QueuedMessageWriteOperation) => {- const last = operations.at(-1);- if (- last?.type === 'updateMessage' &&- operation.type === 'updateMessage' &&- last.id === operation.id &&- !last.onFailure &&- !operation.onFailure- ) {- last.value = mergeMessageUpdateValue(last.value, operation.value);- } else {- operations.push(operation);- }-- if (operations.length >= HETERO_MESSAGE_WRITE_BATCH_MAX_OPS) {- void flush('max-ops');- } else {- scheduleIdleFlush();- }- };-- return {- enqueueCreateMessage: (- message: Extract<MessageBatchOperation, { type: 'createMessage' }>['message'],- onFailure?: (error: unknown) => void,- ) => enqueue({ message, onFailure, type: 'createMessage' }),- enqueueToolMessageUpdate: (- id: string,- value: ToolMessageUpdateOperation['value'],- ctx?: MessageQueryContext,- onFailure?: (error: unknown) => void,- ) => enqueue({ ctx, id, onFailure, type: 'updateToolMessage', value }),- enqueueUpdateMessage: (- id: string,- value: MessageUpdateOperation['value'],- ctx?: MessageQueryContext,- onFailure?: (error: unknown) => void,- ) => enqueue({ ctx, id, onFailure, type: 'updateMessage', value }),- flush,- };-};-interface MessageBatchMutationResult {- results?: Array<{ index: number; success: boolean }>;+ results?: Array<{ error?: string; index: number; success: boolean }>;success?: boolean;}class MessageBatchMutationError extends Error {constructor(public readonly result: MessageBatchMutationResult) {- const failedCount = result.results?.filter((item) => !item.success).length;- super(`messageService.batchMutate failed for ${failedCount || 'unknown'} operation(s)`);+ const failed = result.results?.filter((item) => !item.success) ?? [];+ const reasons = [...new Set(failed.map((item) => item.error).filter(Boolean))];+ super(+ `messageService.batchMutate failed for ${failed.length || 'unknown'} operation(s)` ++ (reasons.length > 0 ? `: ${reasons.join('; ')}` : ''),+ );}}@@ -822,21 +658,6 @@ export const executeHeterogeneousAgent = async (* be lost once the reducer clears `accContent` on terminal.*/const pendingMainFlush = new Map<string, Record<string, any>>();- /**- * 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']>();@@ -1043,6 +864,13 @@ export const executeHeterogeneousAgent = async (updateMessage: messageService.updateMessage,updateToolMessage: messageService.updateToolMessage,});++ /** Failed-create retry ledger + the FK-parent barrier for straight-through writes. */+ const pendingCreateLedger = createPendingCreateLedger({+ createMessage: messageService.createMessage,+ flush: messageWriteBatcher.flush,+ });+const enqueueMainToolResult = (toolCallId: string,content: string,@@ -1308,6 +1136,17 @@ export const executeHeterogeneousAgent = async (// caller already guards, but this function is a separate closure). All// subagent rows are topic-scoped.if (!context.topicId) return;++ // Both of these hang off the main assistant row, which may still be sitting in+ // the write batcher (or have failed to write at all). `createThread` is gated+ // as well: its own `sourceMessageId` has no FK, but letting it through against+ // a missing parent just buys an orphan thread whose seed `createMessage` fails+ // a moment later.+ if (intent.kind === 'createThread')+ await pendingCreateLedger.ensureParentPersisted(intent.sourceMessageId);+ if (intent.kind === 'createMessage')+ await pendingCreateLedger.ensureParentPersisted(intent.parentId);+switch (intent.kind) {case 'createThread': {try {@@ -1573,7 +1412,7 @@ export const executeHeterogeneousAgent = async (} as any;messageWriteBatcher.enqueueCreateMessage(messageToCreate, (err) => {console.error('[HeterogeneousAgent] Failed to create step assistant:', err);- pendingCreates.set(intent.messageId, messageToCreate);+ pendingCreateLedger.add(intent.messageId, messageToCreate);});get().internal_dispatchMessage({ id: intent.messageId, type: 'createMessage', value: messageToCreate },@@ -1690,7 +1529,7 @@ export const executeHeterogeneousAgent = async (const toolMsg = buildToolMessage(x);messageWriteBatcher.enqueueCreateMessage(toolMsg, (err) => {console.error('[HeterogeneousAgent] Failed to create tool message:', err);- pendingCreates.set(x.toolMessageId, toolMsg);+ pendingCreateLedger.add(x.toolMessageId, toolMsg);});toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);mainToolCallIds.add(x.payload.id);@@ -2135,14 +1974,7 @@ export const executeHeterogeneousAgent = async (// 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);- pendingCreates.delete(messageId);- } catch (err) {- console.error('[HeterogeneousAgent] Failed to replay message create:', err);- }- }+ await pendingCreateLedger.drain();for (const [messageId, update] of pendingMainFlush) {try {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.tsnew file mode 100644index 00000000000..5c4da0fd903--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.test.ts@@ -0,0 +1,176 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createMessageWriteBatcher } from './messageWriteBatcher';++const createDeps = () => ({+ batchMutate: vi.fn().mockResolvedValue({ results: [], success: true }),+ createMessage: vi.fn().mockResolvedValue({ id: 'msg-1' }),+ updateMessage: vi.fn().mockResolvedValue({ success: true }),+ updateToolMessage: vi.fn().mockResolvedValue({ success: true }),+});++const createRow = (id: string, parentId?: string) =>+ ({ content: '', id, parentId, role: 'assistant' }) as any;++describe('createMessageWriteBatcher', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useRealTimers();+ });++ it('holds writes until flushed, then sends them as one batch', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ batcher.enqueueCreateMessage(createRow('msg-a'));+ batcher.enqueueCreateMessage(createRow('msg-b'));++ expect(deps.batchMutate).not.toHaveBeenCalled();++ await batcher.flush('test');++ expect(deps.batchMutate).toHaveBeenCalledTimes(1);+ expect(deps.batchMutate.mock.calls[0][0]).toHaveLength(2);+ });++ it('flushing an empty queue is a no-op', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ await batcher.flush('test');++ expect(deps.batchMutate).not.toHaveBeenCalled();+ });++ /**+ * The semantic that made subagent rows die against `messages_parent_id_messages_id_fk`:+ * a failed create is reported ONLY through `onFailure`, and `flush` still resolves.+ * Awaiting a flush therefore proves nothing about whether the row landed β the+ * executor has to track failures itself (`pendingCreates`) and re-check before+ * writing anything that FKs to that row.+ */+ it('resolves the flush even when a create fails, reporting it only via onFailure', async () => {+ const deps = createDeps();+ deps.batchMutate.mockResolvedValue({+ results: [{ error: 'messages_parent_id_messages_id_fk', index: 0, success: false }],+ success: false,+ });+ const batcher = createMessageWriteBatcher(deps);+ const onFailure = vi.fn();++ batcher.enqueueCreateMessage(createRow('msg-parent'), onFailure);++ await expect(batcher.flush('test')).resolves.toBeUndefined();+ expect(onFailure).toHaveBeenCalledTimes(1);+ });++ it('reports every queued op when batchMutate throws outright', async () => {+ const deps = createDeps();+ const boom = new Error('network down');+ deps.batchMutate.mockRejectedValue(boom);+ const batcher = createMessageWriteBatcher(deps);+ const onFailureA = vi.fn();+ const onFailureB = vi.fn();++ batcher.enqueueCreateMessage(createRow('msg-a'), onFailureA);+ batcher.enqueueCreateMessage(createRow('msg-b'), onFailureB);++ await expect(batcher.flush('test')).resolves.toBeUndefined();++ expect(onFailureA).toHaveBeenCalledWith(boom);+ expect(onFailureB).toHaveBeenCalledWith(boom);+ });++ it('marks all ops failed when the batch reports failure without per-op indexes', async () => {+ const deps = createDeps();+ deps.batchMutate.mockResolvedValue({ success: false });+ const batcher = createMessageWriteBatcher(deps);+ const onFailure = vi.fn();++ batcher.enqueueCreateMessage(createRow('msg-a'), onFailure);++ await batcher.flush('test');++ expect(onFailure).toHaveBeenCalledTimes(1);+ });++ it('coalesces consecutive updates to the same row, deep-merging metadata', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ batcher.enqueueUpdateMessage('msg-a', { content: 'hel', metadata: { a: 1 } } as any);+ batcher.enqueueUpdateMessage('msg-a', { content: 'hello', metadata: { b: 2 } } as any);++ await batcher.flush('test');++ const ops = deps.batchMutate.mock.calls[0][0];+ expect(ops).toHaveLength(1);+ expect(ops[0].value).toMatchObject({ content: 'hello', metadata: { a: 1, b: 2 } });+ });++ it('does not coalesce updates that carry an onFailure ledger hook', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ batcher.enqueueUpdateMessage('msg-a', { content: 'one' } as any, undefined, vi.fn());+ batcher.enqueueUpdateMessage('msg-a', { content: 'two' } as any, undefined, vi.fn());++ await batcher.flush('test');++ expect(deps.batchMutate.mock.calls[0][0]).toHaveLength(2);+ });++ it('preserves enqueue order β which is FK dependency order', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ batcher.enqueueCreateMessage(createRow('assistant-1'));+ batcher.enqueueCreateMessage(createRow('tool-1', 'assistant-1'));+ batcher.enqueueCreateMessage(createRow('assistant-2', 'tool-1'));++ await batcher.flush('test');++ expect(deps.batchMutate.mock.calls[0][0].map((op: any) => op.message.id)).toEqual([+ 'assistant-1',+ 'tool-1',+ 'assistant-2',+ ]);+ });++ it('auto-flushes once the queue hits the max-ops ceiling', async () => {+ const deps = createDeps();+ const batcher = createMessageWriteBatcher(deps);++ for (let i = 0; i < 50; i += 1) batcher.enqueueCreateMessage(createRow(`msg-${i}`));+ await batcher.flush('test');++ expect(deps.batchMutate).toHaveBeenCalledTimes(1);+ expect(deps.batchMutate.mock.calls[0][0]).toHaveLength(50);+ });++ it('falls back to per-op writes when batchMutate is unavailable', async () => {+ const deps = { ...createDeps(), batchMutate: undefined };+ const batcher = createMessageWriteBatcher(deps as any);++ batcher.enqueueCreateMessage(createRow('msg-a'));+ batcher.enqueueUpdateMessage('msg-b', { content: 'x' } as any);++ await batcher.flush('test');++ expect(deps.createMessage).toHaveBeenCalledTimes(1);+ expect(deps.updateMessage).toHaveBeenCalledTimes(1);+ });++ it('surfaces a per-op failure through onFailure in the no-batchMutate fallback', async () => {+ const deps = { ...createDeps(), batchMutate: undefined };+ const boom = new Error('insert failed');+ deps.createMessage.mockRejectedValue(boom);+ const batcher = createMessageWriteBatcher(deps as any);+ const onFailure = vi.fn();++ batcher.enqueueCreateMessage(createRow('msg-a'), onFailure);++ await expect(batcher.flush('test')).resolves.toBeUndefined();+ expect(onFailure).toHaveBeenCalledWith(boom);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.tsnew file mode 100644index 00000000000..080429b1612--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/messageWriteBatcher.ts@@ -0,0 +1,188 @@+import type {+ MessageBatchOperation,+ MessageQueryContext,+ messageService,+} from '@/services/message';++export const HETERO_MESSAGE_WRITE_BATCH_IDLE_MS = 5_000;+export const HETERO_MESSAGE_WRITE_BATCH_MAX_OPS = 50;++type MessageUpdateOperation = Extract<MessageBatchOperation, { type: 'updateMessage' }>;+export type ToolMessageUpdateOperation = Extract<+ MessageBatchOperation,+ { type: 'updateToolMessage' }+>;++export type QueuedMessageWriteOperation =+ | (Extract<MessageBatchOperation, { type: 'createMessage' }> & {+ ctx?: never;+ onFailure?: (error: unknown) => void;+ })+ | (MessageUpdateOperation & {+ ctx?: MessageQueryContext;+ onFailure?: (error: unknown) => void;+ })+ | (ToolMessageUpdateOperation & {+ ctx?: MessageQueryContext;+ onFailure?: (error: unknown) => void;+ });++const mergeMessageUpdateValue = (+ previous: MessageUpdateOperation['value'],+ next: MessageUpdateOperation['value'],+): MessageUpdateOperation['value'] => {+ const metadata =+ previous.metadata || next.metadata+ ? {+ ...(previous.metadata as Record<string, any> | undefined),+ ...(next.metadata as Record<string, any> | undefined),+ }+ : undefined;++ return {+ ...previous,+ ...next,+ ...(metadata ? { metadata } : {}),+ };+};++/**+ * Write-behind queue for the hetero run's message rows: coalesces consecutive+ * updates to the same row and flushes them as one `batchMutate`.+ *+ * Failures are reported ONLY through each operation's `onFailure` β `flush`+ * resolves either way. Callers that depend on a row actually existing (an FK+ * parent, say) therefore cannot treat an awaited `flush` as proof it landed;+ * they must track the failures themselves. See `pendingCreates` in the executor.+ */+export const createMessageWriteBatcher = (deps: {+ batchMutate?: (operations: MessageBatchOperation[]) => Promise<any>;+ createMessage: typeof messageService.createMessage;+ updateMessage: typeof messageService.updateMessage;+ updateToolMessage: typeof messageService.updateToolMessage;+}) => {+ let operations: QueuedMessageWriteOperation[] = [];+ let flushChain: Promise<void> = Promise.resolve();+ let idleTimer: ReturnType<typeof setTimeout> | undefined;++ const clearIdleTimer = () => {+ if (!idleTimer) return;+ clearTimeout(idleTimer);+ idleTimer = undefined;+ };++ const notifyFailure = (operation: QueuedMessageWriteOperation, error: unknown) => {+ operation.onFailure?.(error);+ };++ const runIndividual = async (operation: QueuedMessageWriteOperation) => {+ if (operation.type === 'createMessage') {+ await deps.createMessage(operation.message);+ return;+ }++ if (operation.type === 'updateToolMessage') {+ const result = await deps.updateToolMessage(operation.id, operation.value, operation.ctx);+ if (result?.success === false) notifyFailure(operation, result);+ return;+ }++ const result = await deps.updateMessage(operation.id, operation.value, operation.ctx);+ if (result?.success === false) notifyFailure(operation, result);+ };++ const runBatch = async (batch: QueuedMessageWriteOperation[]) => {+ if (deps.batchMutate) {+ try {+ const result = await deps.batchMutate(batch as unknown as MessageBatchOperation[]);+ const failedIndexes = new Set<number>(+ (result?.results ?? [])+ .filter((item: { index: number; success: boolean }) => !item.success)+ .map((item: { index: number }) => item.index),+ );++ if (result?.success === false && failedIndexes.size === 0) {+ for (const [index] of batch.entries()) failedIndexes.add(index);+ }++ for (const index of failedIndexes) {+ notifyFailure(batch[index], result);+ }+ return;+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to flush message write batch:', err);+ for (const operation of batch) notifyFailure(operation, err);+ return;+ }+ }++ for (const operation of batch) {+ try {+ await runIndividual(operation);+ } catch (err) {+ console.error('[HeterogeneousAgent] Failed to flush message write operation:', err);+ notifyFailure(operation, err);+ }+ }+ };++ const flush = async (_reason: string) => {+ clearIdleTimer();+ flushChain = flushChain.then(async () => {+ while (operations.length > 0) {+ const batch = operations;+ operations = [];+ await runBatch(batch);+ }+ });+ await flushChain;+ };++ const scheduleIdleFlush = () => {+ clearIdleTimer();+ idleTimer = setTimeout(() => {+ void flush('idle');+ }, HETERO_MESSAGE_WRITE_BATCH_IDLE_MS);+ };++ const enqueue = (operation: QueuedMessageWriteOperation) => {+ const last = operations.at(-1);+ if (+ last?.type === 'updateMessage' &&+ operation.type === 'updateMessage' &&+ last.id === operation.id &&+ !last.onFailure &&+ !operation.onFailure+ ) {+ last.value = mergeMessageUpdateValue(last.value, operation.value);+ } else {+ operations.push(operation);+ }++ if (operations.length >= HETERO_MESSAGE_WRITE_BATCH_MAX_OPS) {+ void flush('max-ops');+ } else {+ scheduleIdleFlush();+ }+ };++ return {+ enqueueCreateMessage: (+ message: Extract<MessageBatchOperation, { type: 'createMessage' }>['message'],+ onFailure?: (error: unknown) => void,+ ) => enqueue({ message, onFailure, type: 'createMessage' }),+ enqueueToolMessageUpdate: (+ id: string,+ value: ToolMessageUpdateOperation['value'],+ ctx?: MessageQueryContext,+ onFailure?: (error: unknown) => void,+ ) => enqueue({ ctx, id, onFailure, type: 'updateToolMessage', value }),+ enqueueUpdateMessage: (+ id: string,+ value: MessageUpdateOperation['value'],+ ctx?: MessageQueryContext,+ onFailure?: (error: unknown) => void,+ ) => enqueue({ ctx, id, onFailure, type: 'updateMessage', value }),+ flush,+ };+};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.tsnew file mode 100644index 00000000000..121263aab92--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.test.ts@@ -0,0 +1,123 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createPendingCreateLedger } from './pendingCreateLedger';++const row = (id: string, parentId?: string) =>+ ({ content: '', id, parentId, role: 'assistant' }) as any;++describe('createPendingCreateLedger', () => {+ beforeEach(() => vi.clearAllMocks());++ describe('ensureParentPersisted', () => {+ it('flushes the write batcher before letting a straight-through write proceed', async () => {+ const flush = vi.fn().mockResolvedValue(undefined);+ const ledger = createPendingCreateLedger({ createMessage: vi.fn(), flush });++ await expect(ledger.ensureParentPersisted('msg-parent')).resolves.toBeUndefined();++ expect(flush).toHaveBeenCalledWith('before-subagent-write');+ });++ /**+ * The gap this ledger exists to close. `flush` resolves even when the create+ * inside it failed β the failure only lands here via `add`. Awaiting the flush+ * is therefore not proof the parent exists, so the ledger replays it.+ */+ it('replays a parent whose batched create failed, then proceeds', async () => {+ const createMessage = vi.fn().mockResolvedValue({ id: 'msg-parent' });+ const flush = vi.fn().mockResolvedValue(undefined);+ const ledger = createPendingCreateLedger({ createMessage, flush });++ // The batcher swallowed this create and reported it through onFailure.+ ledger.add('msg-parent', row('msg-parent'));++ await expect(ledger.ensureParentPersisted('msg-parent')).resolves.toBeUndefined();++ expect(createMessage).toHaveBeenCalledTimes(1);+ expect(ledger.has('msg-parent')).toBe(false);+ expect(ledger.size).toBe(0);+ });++ it('refuses to proceed when the parent still cannot be written', async () => {+ const createMessage = vi.fn().mockRejectedValue(new Error('still failing'));+ const flush = vi.fn().mockResolvedValue(undefined);+ const ledger = createPendingCreateLedger({ createMessage, flush });++ ledger.add('msg-parent', row('msg-parent'));++ // Better to abort the subagent write than to hit the FK error, skip the+ // state commit, and strand another Processing thread on the next retry.+ await expect(ledger.ensureParentPersisted('msg-parent')).rejects.toThrow(+ /missing FK parent msg-parent/,+ );+ expect(ledger.has('msg-parent')).toBe(true);+ });++ it('replays the whole ledger in dependency order, not just the named parent', async () => {+ const written: string[] = [];+ const createMessage = vi.fn().mockImplementation(async (m: any) => void written.push(m.id));+ const ledger = createPendingCreateLedger({+ createMessage,+ flush: vi.fn().mockResolvedValue(undefined),+ });++ // A signal assistant hangs off the run's last TOOL row, which itself hangs+ // off an earlier assistant β replaying only `assistant-2` would violate the FK.+ ledger.add('assistant-1', row('assistant-1'));+ ledger.add('tool-1', row('tool-1', 'assistant-1'));+ ledger.add('assistant-2', row('assistant-2', 'tool-1'));++ await ledger.ensureParentPersisted('assistant-2');++ expect(written).toEqual(['assistant-1', 'tool-1', 'assistant-2']);+ });++ it('does not block on an unrelated row that stays stuck in the ledger', async () => {+ const createMessage = vi.fn().mockRejectedValue(new Error('unrelated row is broken'));+ const ledger = createPendingCreateLedger({+ createMessage,+ flush: vi.fn().mockResolvedValue(undefined),+ });++ ledger.add('some-other-row', row('some-other-row'));++ // `msg-parent` was never in the ledger β it wrote fine through the batcher.+ await expect(ledger.ensureParentPersisted('msg-parent')).resolves.toBeUndefined();+ });++ it('is a no-op when the ledger is empty', async () => {+ const createMessage = vi.fn();+ const ledger = createPendingCreateLedger({+ createMessage,+ flush: vi.fn().mockResolvedValue(undefined),+ });++ await ledger.ensureParentPersisted('msg-parent');+ await ledger.ensureParentPersisted(undefined);++ expect(createMessage).not.toHaveBeenCalled();+ });+ });++ describe('drain', () => {+ it('keeps rows that fail again so a later pass can retry them', async () => {+ const createMessage = vi+ .fn()+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValueOnce({ id: 'msg-b' });+ const ledger = createPendingCreateLedger({+ createMessage,+ flush: vi.fn().mockResolvedValue(undefined),+ });++ ledger.add('msg-a', row('msg-a'));+ ledger.add('msg-b', row('msg-b'));++ await ledger.drain();++ expect(ledger.has('msg-a')).toBe(true);+ expect(ledger.has('msg-b')).toBe(false);+ expect(ledger.size).toBe(1);+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.tsnew file mode 100644index 00000000000..b0f6e23d5e3--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/pendingCreateLedger.ts@@ -0,0 +1,78 @@+import type { MessageBatchOperation } from '@/services/message';++type CreateMessageRow = Extract<MessageBatchOperation, { type: 'createMessage' }>['message'];++/**+ * 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.+ */+export const createPendingCreateLedger = (deps: {+ createMessage: (message: CreateMessageRow) => Promise<unknown>;+ /** The write batcher's flush. Resolves even when the writes inside it failed. */+ flush: (reason: string) => Promise<void>;+}) => {+ const pending = new Map<string, CreateMessageRow>();++ /**+ * 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);+ }+ }+ };++ return {+ add: (messageId: string, message: CreateMessageRow) => pending.set(messageId, message),++ drain,++ /**+ * Gate a straight-through write on its FK parent actually existing in the DB.+ *+ * The main row a subagent hangs off is only *enqueued* into the write batcher,+ * while subagent rows are written straight through β so without a barrier the+ * child can reach the DB before its parent and Postgres rejects it against+ * `messages_parent_id_messages_id_fk`.+ *+ * Draining the batcher is necessary but NOT sufficient: a create that fails+ * inside the batcher is reported only through its `onFailure` (which parks it+ * here) and `flush` resolves regardless, so an awaited flush says nothing about+ * whether the parent landed. Replay the ledger too, then refuse to proceed while+ * the parent is still missing β walking into the FK error would skip the run's+ * state commit and strand another `Processing` thread on every retry+ * (`threads.source_message_id` has no FK, so the thread create keeps succeeding).+ */+ ensureParentPersisted: async (parentId?: string) => {+ await deps.flush('before-subagent-write');++ if (pending.size > 0) await drain();++ if (parentId && pending.has(parentId)) {+ throw new Error(+ `[HeterogeneousAgent] refusing to write a row against missing FK parent ${parentId}`,+ );+ }+ },++ has: (messageId: string) => pending.has(messageId),++ get size() {+ return pending.size;+ },+ };+};