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(database): serialize topic.metadata updates to prevent lost-update stranding hetero tasks (#16285)

Arvin Xu7ab97fad56e5
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 4ce1c4cf930..818cb051a0f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -520,4 +520,83 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
);
});
});
+
+ // The seed side of the hetero terminal-hook funnel. execAgent runs the hetero
+ // block inline (process A) and serializes the run's lifecycle hooks onto
+ // `topic.metadata.runningOperation.hooks` BEFORE the device/sandbox fork, so
+ // the later heteroFinish callback (process B) can re-fire them across the
+ // process boundary. If this seed drops the task-on-complete webhook, a finished
+ // hetero task's `task_topics.status` stays stuck at `running` because
+ // `onTopicComplete` never gets delivered. Guards that the passed hooks reach
+ // runningOperation.hooks in serialized (webhook-only) form on BOTH dispatch
+ // targets.
+ describe('terminal hook seeding onto runningOperation (regression guard)', () => {
+ const taskHook = {
+ handler: async () => {},
+ id: 'task-on-complete',
+ type: 'onComplete' as const,
+ webhook: {
+ body: { taskId: 'task_x', taskIdentifier: 'T-X', userId: 'test-user-id' },
+ delivery: 'qstash' as const,
+ url: '/api/workflows/task/on-topic-complete',
+ },
+ };
+
+ // Pick out the updateMetadata call that persists the running operation.
+ const findRunningOpSeed = () =>
+ topicMock.updateMetadata.mock.calls
+ .map((call) => call[1])
+ .find((patch: any) => patch?.runningOperation?.operationId);
+
+ it('serializes the onComplete webhook hook onto runningOperation (sandbox dispatch)', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ hooks: [taskHook],
+ prompt: 'do the task',
+ } as any);
+
+ // Sanity: this run took the sandbox path (no bound device).
+ expect(mockSpawnHeteroSandbox).toHaveBeenCalled();
+
+ const seed = findRunningOpSeed();
+ expect(seed).toBeDefined();
+ expect(seed.runningOperation.hooks).toEqual([
+ expect.objectContaining({
+ id: 'task-on-complete',
+ type: 'onComplete',
+ webhook: expect.objectContaining({
+ delivery: 'qstash',
+ url: '/api/workflows/task/on-topic-complete',
+ }),
+ }),
+ ]);
+ // The non-serializable handler must be stripped (only webhook crosses the
+ // process boundary).
+ expect(seed.runningOperation.hooks[0]).not.toHaveProperty('handler');
+ });
+
+ it('serializes the onComplete webhook hook onto runningOperation (device dispatch)', async () => {
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ hooks: [taskHook],
+ prompt: 'do the task on device',
+ } as any);
+
+ // Sanity: this run took the device path.
+ expect(mockDispatchAgentRun).toHaveBeenCalled();
+
+ const seed = findRunningOpSeed();
+ expect(seed).toBeDefined();
+ expect(seed.runningOperation.hooks?.[0]?.id).toBe('task-on-complete');
+ expect(seed.runningOperation.hooks?.[0]?.webhook?.url).toBe(
+ '/api/workflows/task/on-topic-complete',
+ );
+ });
+ });
});
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index ca341d21b87..4756f89b905 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -1,14 +1,30 @@
// @vitest-environment node
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
-import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
+import type { AgentHook, SerializedHook } from '@/server/services/agentRuntime/hooks/types';
import type { HeterogeneousPersistenceHandler } from '..';
import { HeterogeneousAgentService, StaleHeteroOperationError } from '..';
+// Force queue/production mode so the terminal funnel takes the serialized-webhook
+// delivery path (the hetero cross-process path), not the in-memory handler path.
+// Default to local (false) so the existing in-memory-handler tests are unaffected.
+vi.mock('@/server/services/queue/impls', () => ({
+ isQueueAgentRuntimeEnabled: vi.fn(() => false),
+}));
+
+const mockPublishJSON = vi.hoisted(() => vi.fn());
+vi.mock('@upstash/qstash', () => ({
+ Client: class {
+ publishJSON = mockPublishJSON;
+ },
+}));
+
+const { isQueueAgentRuntimeEnabled } = await import('@/server/services/queue/impls');
+
const createFakeStreamManager = () => {
const published: Array<{ event: any; operationId: string }> = [];
const manager: Partial<IStreamEventManager> = {
@@ -342,4 +358,239 @@ describe('HeterogeneousAgentService', () => {
hookDispatcher.unregister('op-hook-cancelled');
});
});
+
+ // ───────────────────────────────────────────────────────────────────────────
+ // The hetero terminal funnel in PRODUCTION (queue) mode. This is the path the
+ // device/sandbox runs actually take: execAgent (process A) serializes the run's
+ // lifecycle hooks onto `topic.metadata.runningOperation.hooks`; heteroFinish
+ // (process B β€” the device callback / CLI exit, a different Lambda) reads them
+ // back and must deliver each webhook. There is NO in-memory handler to fall
+ // back on across that process boundary, so the in-memory-handler tests above
+ // (which run in local mode) never exercise it. This guards the
+ // read(runningOperation.hooks) β†’ dispatch β†’ deliverWebhook round-trip β€” the
+ // link that, if broken, leaves a finished hetero task's `task_topics.status`
+ // stuck at `running` because `onTopicComplete` never fires.
+ describe('heteroFinish β€” queue-mode terminal webhook delivery (regression guard)', () => {
+ const originalToken = process.env.QSTASH_TOKEN;
+ const originalAppUrl = process.env.APP_URL;
+
+ const taskHook: SerializedHook = {
+ id: 'task-on-complete',
+ type: 'onComplete',
+ webhook: {
+ body: { taskId: 'task_q', taskIdentifier: 'T-Q', userId: 'user-test' },
+ delivery: 'qstash',
+ url: '/api/workflows/task/on-topic-complete',
+ },
+ };
+
+ const makeService = (hooks: SerializedHook[] | undefined) => {
+ const topicModel = {
+ // Mirror what execAgent persisted at dispatch: the serialized hooks live
+ // under runningOperation. heteroFinish must read them from here.
+ findById: vi.fn(async () => ({
+ id: 'topic-q',
+ metadata: { runningOperation: { hooks, operationId: 'op-q' } },
+ })),
+ updateMetadata: vi.fn(async () => {}),
+ } as any;
+ const { manager } = createFakeStreamManager();
+ const service = new HeterogeneousAgentService({} as any, 'user-test', {
+ persistenceHandler: createFakePersistenceHandler(),
+ snapshotStore: null,
+ streamEventManager: manager,
+ topicModel,
+ });
+ return { service, topicModel };
+ };
+
+ beforeEach(() => {
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
+ mockPublishJSON.mockReset();
+ mockPublishJSON.mockResolvedValue(undefined);
+ process.env.QSTASH_TOKEN = 'test-token';
+ process.env.APP_URL = 'https://app.test';
+ });
+
+ afterEach(() => {
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(false);
+ if (originalToken === undefined) delete process.env.QSTASH_TOKEN;
+ else process.env.QSTASH_TOKEN = originalToken;
+ if (originalAppUrl === undefined) delete process.env.APP_URL;
+ else process.env.APP_URL = originalAppUrl;
+ });
+
+ it('delivers the task-on-complete webhook read from runningOperation.hooks (reason=done)', async () => {
+ const { service } = makeService([taskHook]);
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-q',
+ result: 'success',
+ topicId: 'topic-q',
+ });
+
+ expect(mockPublishJSON).toHaveBeenCalledTimes(1);
+ const arg = mockPublishJSON.mock.calls[0][0];
+ expect(arg.url).toContain('/api/workflows/task/on-topic-complete');
+ expect(arg.body).toMatchObject({
+ hookId: 'task-on-complete',
+ hookType: 'onComplete',
+ reason: 'done',
+ taskId: 'task_q',
+ topicId: 'topic-q',
+ });
+ });
+
+ it('negative control: delivers nothing when runningOperation.hooks is empty', async () => {
+ const { service } = makeService([]);
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-q',
+ result: 'success',
+ topicId: 'topic-q',
+ });
+
+ expect(mockPublishJSON).not.toHaveBeenCalled();
+ });
+ });
+
+ // ───────────────────────────────────────────────────────────────────────────
+ // End-to-end DATA-FLOW reproduction of the runtime path: seed the run's hooks
+ // the way execAgent does (real hookDispatcher.register β†’ getSerializedHooks β†’
+ // persist onto runningOperation via a shared in-memory topic store with REAL
+ // shallow-merge semantics), then run the REAL heteroFinish against the SAME
+ // store. This exercises the cross-process round-trip the isolated unit tests
+ // hand-wave, and lets us reproduce the production "stuck task_topics" symptom
+ // by injecting the suspected lost-update race on topic.metadata.
+ describe('heteroFinish — seed→read→deliver round-trip + lost-update repro', () => {
+ const originalToken = process.env.QSTASH_TOKEN;
+ const originalAppUrl = process.env.APP_URL;
+ const TOPIC = 'topic-int';
+
+ // The exact hook taskRunner attaches: a handler (local) PLUS a qstash webhook.
+ const taskHook: AgentHook = {
+ handler: async () => {},
+ id: 'task-on-complete',
+ type: 'onComplete',
+ webhook: {
+ body: { taskId: 'task_x', taskIdentifier: 'T-X', userId: 'user-test' },
+ delivery: 'qstash',
+ url: '/api/workflows/task/on-topic-complete',
+ },
+ };
+
+ // Shared topic store whose updateMetadata mirrors TopicModel.updateMetadata:
+ // a non-atomic read-modify-write that shallow-merges the patch over a
+ // snapshot. `mergeBase` lets a test force the "read a stale snapshot" race.
+ const makeStore = () => {
+ let meta: Record<string, any> = {};
+ const topicModel = {
+ findById: vi.fn(async () => ({ id: TOPIC, metadata: meta })),
+ updateMetadata: vi.fn(async (_id: string, patch: Record<string, any>, mergeBase?: any) => {
+ meta = { ...(mergeBase ?? meta), ...patch };
+ }),
+ } as any;
+ return { get: () => meta, topicModel };
+ };
+
+ // Reproduce execAgent's seed step exactly.
+ const seed = (store: ReturnType<typeof makeStore>, operationId: string) => {
+ hookDispatcher.register(operationId, [taskHook]);
+ const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
+ return store.topicModel.updateMetadata(TOPIC, {
+ runningOperation: { assistantMessageId: 'asst-1', hooks: serializedHooks, operationId },
+ });
+ };
+
+ const makeService = (store: ReturnType<typeof makeStore>) =>
+ new HeterogeneousAgentService({} as any, 'user-test', {
+ persistenceHandler: createFakePersistenceHandler(),
+ snapshotStore: null,
+ streamEventManager: createFakeStreamManager().manager,
+ topicModel: store.topicModel,
+ });
+
+ beforeEach(() => {
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
+ mockPublishJSON.mockReset();
+ mockPublishJSON.mockResolvedValue(undefined);
+ process.env.QSTASH_TOKEN = 'test-token';
+ process.env.APP_URL = 'https://app.test';
+ });
+
+ afterEach(() => {
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(false);
+ hookDispatcher.unregister('op-int');
+ if (originalToken === undefined) delete process.env.QSTASH_TOKEN;
+ else process.env.QSTASH_TOKEN = originalToken;
+ if (originalAppUrl === undefined) delete process.env.APP_URL;
+ else process.env.APP_URL = originalAppUrl;
+ });
+
+ it('happy path: a fresh-read heteroIngest write preserves hooks β†’ heteroFinish delivers', async () => {
+ const store = makeStore();
+ await seed(store, 'op-int');
+
+ // A normal mid-run ingest write reads the CURRENT snapshot, so the
+ // shallow-merge keeps runningOperation intact.
+ await store.topicModel.updateMetadata(TOPIC, {
+ heteroCurrentMsgId: { msgId: 'm1', operationId: 'op-int' },
+ });
+ expect(store.get().runningOperation?.hooks).toHaveLength(1);
+
+ // heteroFinish runs in a DIFFERENT process/Lambda than execAgent, so the
+ // in-memory hookDispatcher has nothing for this op β€” it relies purely on
+ // the serialized hooks read from runningOperation. Drop the in-memory
+ // registration to model that boundary faithfully.
+ hookDispatcher.unregister('op-int');
+
+ await makeService(store).heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-int',
+ result: 'success',
+ topicId: TOPIC,
+ });
+
+ expect(mockPublishJSON).toHaveBeenCalledTimes(1);
+ expect(mockPublishJSON.mock.calls[0][0].url).toContain(
+ '/api/workflows/task/on-topic-complete',
+ );
+ });
+
+ it('REPRO: a stale-read ingest write clobbers runningOperation.hooks β†’ heteroFinish delivers nothing (the stuck-task symptom)', async () => {
+ const store = makeStore();
+ // Snapshot BEFORE the seed commits β€” what a racing reader would have seen.
+ const preSeedSnapshot = { ...store.get() };
+ await seed(store, 'op-int');
+ expect(store.get().runningOperation?.hooks).toHaveLength(1);
+
+ // A concurrent heteroIngest whose read-modify-write started from the
+ // pre-seed snapshot (replica lag / interleave): merging its patch over the
+ // STALE base drops runningOperation entirely β€” a classic lost update.
+ await store.topicModel.updateMetadata(
+ TOPIC,
+ { heteroCurrentMsgId: { msgId: 'm1', operationId: 'op-int' } },
+ preSeedSnapshot,
+ );
+ expect(store.get().runningOperation).toBeUndefined();
+
+ // Model the process boundary: heteroFinish's in-memory dispatcher is empty,
+ // so the clobbered runningOperation is its ONLY source of the hook.
+ hookDispatcher.unregister('op-int');
+
+ await makeService(store).heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-int',
+ result: 'success',
+ topicId: TOPIC,
+ });
+
+ // Exactly the production failure: the run finished, but the terminal hook
+ // had nothing to deliver, so onTopicComplete never fires and the task
+ // topic is stranded at `running`.
+ expect(mockPublishJSON).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/topics/topic.updateMetadata.race.test.ts b/packages/database/src/models/__tests__/topics/topic.updateMetadata.race.test.ts
new file mode 100644
index 00000000000..d1a1e3bb179
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.updateMetadata.race.test.ts
@@ -0,0 +1,84 @@
+import { eq } from 'drizzle-orm';
+import { afterAll, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+
+// Real-Postgres reproduction of the lost-update race on `topic.metadata` that
+// strands a finished heterogeneous task at `task_topics.status = 'running'`.
+//
+// In production execAgent serializes the run's lifecycle hooks onto
+// `metadata.runningOperation.hooks`; during the run heteroIngest repeatedly
+// writes `metadata.heteroCurrentMsgId`. `TopicModel.updateMetadata` is a
+// non-atomic read-modify-write (`{ ...existing, ...patch }`), so two writers
+// whose reads overlap can drop each other's keys. If the ingest write merges a
+// patch over a snapshot taken before the seed landed, `runningOperation`
+// (hooks and all) is lost β€” and heteroFinish, running in another process with
+// an empty in-memory dispatcher, then has nothing to deliver.
+//
+// This test exercises the REAL TopicModel against a REAL node-postgres pool
+// (separate connections per query β†’ genuine interleave). Before the fix the
+// concurrent ingest write clobbered `runningOperation` ~half the time and at
+// least one key was lost in 29/30 trials. The fix wraps the merge in a
+// `SELECT … FOR UPDATE` transaction, so writers serialize on the row and every
+// key survives β€” this test now guards that (clobbered === 0, bothSurvived ===
+// TRIALS).
+
+const userId = 'updatemeta-race-user';
+const serverDB: LobeChatDatabase = await getTestDB();
+const topicModel = new TopicModel(serverDB, userId);
+
+const cleanup = async () => {
+ await serverDB.delete(topics).where(eq(topics.userId, userId));
+ await serverDB.delete(users).where(eq(users.id, userId));
+};
+
+describe('TopicModel.updateMetadata β€” concurrent lost-update (real Postgres)', () => {
+ beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values([{ id: userId }]);
+ });
+
+ afterAll(cleanup);
+
+ it('serializes concurrent writers so neither runningOperation nor heteroCurrentMsgId is lost', async () => {
+ const TRIALS = 30;
+ let clobbered = 0;
+ let bothSurvived = 0;
+
+ for (let i = 0; i < TRIALS; i++) {
+ const topicId = `race-${i}`;
+ // Topic starts with no runningOperation β€” exactly the pre-seed snapshot a
+ // racing ingest reader would observe.
+ await serverDB.insert(topics).values({ id: topicId, metadata: {}, title: 't', userId });
+
+ // Writer A = execAgent seed; Writer B = heteroIngest step write. Fired
+ // concurrently so their read-modify-writes can interleave on the pool.
+ await Promise.all([
+ topicModel.updateMetadata(topicId, {
+ runningOperation: { hooks: [{ id: 'task-on-complete' }], operationId: 'op' } as any,
+ }),
+ topicModel.updateMetadata(topicId, {
+ heteroCurrentMsgId: { msgId: 'm', operationId: 'op' } as any,
+ }),
+ ]);
+
+ const after = await topicModel.findById(topicId);
+ const meta = (after?.metadata ?? {}) as Record<string, any>;
+ if (!meta.runningOperation) clobbered++;
+ if (meta.runningOperation && meta.heteroCurrentMsgId) bothSurvived++;
+ }
+
+ console.log(
+ `[updateMetadata race] runningOperation clobbered in ${clobbered}/${TRIALS} trials; both keys survived in ${bothSurvived}/${TRIALS}`,
+ );
+
+ // With the row-locked merge, concurrent writers serialize on the row: every
+ // trial must keep BOTH keys. A single clobber means the lost-update race is
+ // back (the production failure mode that stranded finished hetero tasks).
+ expect(clobbered).toBe(0);
+ expect(bothSurvived).toBe(TRIALS);
+ });
+});
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 6263275c28f..28aaedb2be1 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1028,31 +1028,46 @@ export class TopicModel {
* This method merges new metadata with existing metadata instead of replacing it
*/
updateMetadata = async (id: string, metadata: TopicMetadataPatch) => {
- // Get existing topic to merge metadata
- const existing = await this.db.query.topics.findFirst({
- columns: { metadata: true },
- where: and(eq(topics.id, id), this.ownership()),
- });
+ // Merge into the existing metadata under a row lock so concurrent writers
+ // can't lose each other's keys. The old read-then-write was a non-atomic
+ // read-modify-write: a hetero run seeds `metadata.runningOperation` while
+ // heteroIngest concurrently writes `metadata.heteroCurrentMsgId`, and a write
+ // built on a stale snapshot (interleaved read, or a read-replica that hadn't
+ // caught up) silently dropped `runningOperation` β€” stranding the finished
+ // task at `task_topics.status = 'running'` because heteroFinish then had no
+ // hooks to deliver. `SELECT … FOR UPDATE` forces a primary read + serializes
+ // writers on the row, killing both the interleave and replica-lag variants
+ // while preserving the exact (shallow + nested onboardingSession) merge.
+ return this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
- const mergedOnboardingSession =
- existing?.metadata?.onboardingSession && metadata.onboardingSession
- ? {
- ...existing.metadata.onboardingSession,
- ...metadata.onboardingSession,
- }
- : metadata.onboardingSession;
+ // No row (missing or not owned) β€” nothing to update, mirror the old no-op.
+ if (!existing) return [];
- const mergedMetadata = {
- ...existing?.metadata,
- ...metadata,
- ...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),
- } as ChatTopicMetadata;
+ const mergedOnboardingSession =
+ existing.metadata?.onboardingSession && metadata.onboardingSession
+ ? {
+ ...existing.metadata.onboardingSession,
+ ...metadata.onboardingSession,
+ }
+ : metadata.onboardingSession;
- return this.db
- .update(topics)
- .set({ metadata: mergedMetadata })
- .where(and(eq(topics.id, id), this.ownership()))
- .returning();
+ const mergedMetadata = {
+ ...existing.metadata,
+ ...metadata,
+ ...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),
+ } as ChatTopicMetadata;
+
+ return tx
+ .update(topics)
+ .set({ metadata: mergedMetadata })
+ .where(and(eq(topics.id, id), this.ownership()))
+ .returning();
+ });
};
getCronTopicsGroupedByCronJob = async (
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
index c32e4aac95f..2a48f120315 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
@@ -37,10 +37,12 @@ vi.mock('../../../store', () => ({
useConversationStore: (selector: (state: unknown) => unknown) => selector({}),
}));
-const useMarkdownMock = vi.fn(() => ({}));
+type UseMarkdownArgs = [id: string, disableStreaming?: boolean];
+
+const useMarkdownMock = vi.fn((..._args: UseMarkdownArgs) => ({}));
vi.mock('../useMarkdown', () => ({
- useMarkdown: (...args: unknown[]) => useMarkdownMock(...args),
+ useMarkdown: (...args: UseMarkdownArgs) => useMarkdownMock(...args),
}));
describe('MessageContent', () => {