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): isolate message chains across steered runs (#21637)

AmAzing-ec4fe4256af7
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
index 6f3e886bfdc..dce3f0ea051 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts
@@ -24,6 +24,7 @@ export async function applyMainIntent(
case 'createAssistant': {
const createMetadata: Record<string, any> = {
...heteroProvenance(state, intent.mainMessageId),
+ operationId: state.operationId,
};
if (intent.signal) createMetadata.signal = intent.signal;
// Persist the turn's CC message.id so a cold replica can recover
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.operationIsolation.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.operationIsolation.test.ts
new file mode 100644
index 00000000000..f933ac5e52a
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.operationIsolation.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+import { parse } from '@lobechat/conversation-flow';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetOperationStatesForTesting } from '.';
+import { buildEvent, createHarness } from './testUtils';
+
+describe('heterogeneous operation isolation after steering', () => {
+ beforeEach(__resetOperationStatesForTesting);
+ afterEach(() => {
+ __resetOperationStatesForTesting();
+ vi.restoreAllMocks();
+ });
+
+ it.each([0, 1])('rejects a cached superseded run at step %i without writing', async (step) => {
+ const h = createHarness({
+ assistantMessageId: 'old-assistant',
+ isOperationLiveOnTopic: async () => true,
+ operationId: 'old-operation',
+ topicId: 'topic',
+ });
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'before steer' })],
+ operationId: 'old-operation',
+ topicId: 'topic',
+ });
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic',
+ metadata: {
+ runningOperation: { assistantMessageId: 'new-assistant', operationId: 'new-operation' },
+ },
+ });
+ h.messageModel.update.mockClear();
+ h.messageModel.create.mockClear();
+
+ await expect(
+ h.handler.ingest({
+ events: [buildEvent('stream_chunk', step, { chunkType: 'text', content: 'late output' })],
+ operationId: 'old-operation',
+ topicId: 'topic',
+ }),
+ ).rejects.toThrow(/Stale hetero operation/);
+ expect(h.messages.get('old-assistant')?.content).toBe('before steer');
+ expect(h.messageModel.update).not.toHaveBeenCalled();
+ expect(h.messageModel.create).not.toHaveBeenCalled();
+ });
+
+ it.each([true, false])('rechecks cached marker-less operation liveness: %s', async (live) => {
+ const h = createHarness({
+ assistantMessageId: 'assistant',
+ isOperationLiveOnTopic: async () => live,
+ operationId: 'operation',
+ topicId: 'topic',
+ });
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'first' })],
+ operationId: 'operation',
+ topicId: 'topic',
+ });
+ h.topicModel.findById.mockResolvedValue({ agentId: null, id: 'topic', metadata: {} });
+
+ const ingest = h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: ' continued' }, 2)],
+ operationId: 'operation',
+ topicId: 'topic',
+ });
+ if (live) await ingest;
+ else await expect(ingest).rejects.toThrow(/Stale hetero operation/);
+ expect(h.messages.get('assistant')?.content).toBe(live ? 'first continued' : 'first');
+ });
+
+ it('keeps a resumed reply reachable when another run wrote a newer assistant', async () => {
+ const h = createHarness({
+ assistantMessageId: 'new-seed',
+ operationId: 'new-operation',
+ topicId: 'topic',
+ });
+ h.messages.clear();
+ const common = { agentId: null, topicId: 'topic' };
+ h.messages.set('initial-user', {
+ ...common,
+ content: 'start',
+ id: 'initial-user',
+ role: 'user',
+ });
+ h.messages.set('old-seed', {
+ ...common,
+ content: 'working',
+ id: 'old-seed',
+ parentId: 'initial-user',
+ role: 'assistant',
+ });
+ h.messages.set('steer', {
+ ...common,
+ content: 'also check the update',
+ id: 'steer',
+ metadata: { steer: true },
+ parentId: 'old-seed',
+ role: 'user',
+ });
+ h.messages.set('new-seed', {
+ ...common,
+ content: 'checking the update',
+ id: 'new-seed',
+ parentId: 'steer',
+ role: 'assistant',
+ });
+ // A late old-run write can be newer than this run's seed. It must never
+ // become the next step's parent, even on a cold replica.
+ h.messages.set('late-old', {
+ ...common,
+ content: 'old continuation',
+ id: 'late-old',
+ metadata: { operationId: 'old-operation' },
+ parentId: 'old-seed',
+ role: 'assistant',
+ });
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_start', 1, { messageId: 'native-1', newStep: true }),
+ buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'new step' }),
+ ],
+ operationId: 'new-operation',
+ topicId: 'topic',
+ });
+ const first = [...h.messages.values()].find((m) => m.content === 'new step')!;
+ expect(first.parentId).toBe('new-seed');
+ expect(first.metadata?.operationId).toBe('new-operation');
+
+ h.messages.set('later-old', {
+ ...common,
+ content: 'another late old continuation',
+ id: 'later-old',
+ metadata: { operationId: 'old-operation' },
+ parentId: 'late-old',
+ role: 'assistant',
+ });
+ __resetOperationStatesForTesting();
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_start', 2, { messageId: 'native-2', newStep: true }),
+ buildEvent('stream_chunk', 2, { chunkType: 'text', content: 'final answer after steer' }),
+ ],
+ operationId: 'new-operation',
+ topicId: 'topic',
+ });
+ const final = [...h.messages.values()].find((m) => m.content === 'final answer after steer')!;
+ expect(final.parentId).toBe(first.id);
+ const rendered = parse(
+ [...h.messages.values()].map((m, index) => ({
+ ...m,
+ createdAt: index,
+ updatedAt: index,
+ })),
+ );
+ expect(JSON.stringify(rendered.flatList)).toContain('final answer after steer');
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts
index 9dc17664bcf..09a290a633d 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.stepBoundaries.test.ts
@@ -45,10 +45,6 @@ describe('HeterogeneousPersistenceHandler', () => {
message.id !== 'thread-asst-1',
);
expect(nextThreadAssistant?.parentId).toBe('thread-asst-1');
- expect(h.messageModel.getLatestSpineMessageId).toHaveBeenCalledWith({
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
});
it('flushes prior content, opens a new assistant chained off the prior assistant (spine)', async () => {
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
index 119da3dfbcb..3a62fbfe37d 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts
@@ -58,15 +58,11 @@ export async function loadOrCreateState(
allowMissingRunningOperation = false,
): Promise<OperationState> {
let state = operationStates.get(operationId);
- if (state) {
- // Defensive: caller mismatch on topicId would corrupt persistence β€”
- // assert and throw rather than silently writing to the wrong topic.
- if (state.topicId !== topicId) {
- throw new Error(
- `Operation ${operationId} is already bound to topic ${state.topicId}, not ${topicId}`,
- );
- }
- return state;
+ // A cached state must never be reused for another topic.
+ if (state && state.topicId !== topicId) {
+ throw new Error(
+ `Operation ${operationId} is already bound to topic ${state.topicId}, not ${topicId}`,
+ );
}
const topic = await deps.topicModel.findById(topicId);
@@ -107,6 +103,11 @@ export async function loadOrCreateState(
}
}
+ // Cached accumulators do not grant write ownership. A steer can replace the
+ // topic's operation without advancing this producer's step index, so every
+ // batch must pass the same ownership/liveness check as a cold replica.
+ if (state) return state;
+
// Prefer the assistantMessageId forwarded in the ingest payload (sandbox path).
// The orchestrator already has it in-memory and passes it through env β†’ CLI β†’ tRPC,
// so this path avoids depending on `runningOperation.assistantMessageId`
@@ -398,17 +399,13 @@ export async function refreshMainStateFromDb(
if (snapshot.model) state.main.turnModel = snapshot.model;
if (snapshot.provider) state.main.turnProvider = snapshot.provider;
- // Recover the chain spine from the DB. The next normal
- // turn parents off the run's latest main-thread message that is neither a
- // tool nor a TOOLLESS signal callback (a tools-bearing signal turn is
- // main-chain β€” see `getLatestSpineMessageId`); reading it straight
- // from the DB (independent of
- // `currentAssistantId`, which can regress to the seed placeholder on a cold
- // / non-sticky replica β€” see the multi-replica caveat on the class) keeps
- // consecutive cold-replica steps chained linearly instead of forking onto a
- // stale node. Signal turns still anchor off `lastToolMsgIdEver`, which is
- // maintained in-memory across the run's tool batches.
+ // Recover only THIS operation's spine. A late write from the interrupted
+ // producer can be newer than the steered run's seed; using the topic-wide
+ // latest row would attach the new reply to the old branch. Reading stamped
+ // steps still recovers progress on cold replicas whose pointer is stale.
+ // Before the first stamped step, keep the run's seeded/current spine.
const spineId = await deps.messageModel.getLatestSpineMessageId({
+ operationId: state.operationId,
threadId: state.threadId ?? null,
topicId: state.topicId,
});
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts
index 39b98b4422e..3ba92c054e4 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts
@@ -119,10 +119,18 @@ export const createHarness = (params: {
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
getLatestSpineMessageId: vi.fn(
- async ({ threadId }: { threadId?: string | null; topicId: string }) => {
+ async ({
+ operationId,
+ threadId,
+ }: {
+ operationId?: string;
+ threadId?: string | null;
+ topicId: string;
+ }) => {
const match = [...messages.values()].findLast(
(m) =>
m.role !== 'tool' &&
+ (!operationId || m.metadata?.operationId === operationId) &&
(m.threadId ?? null) === (threadId ?? null) &&
!(m as any).metadata?.signal,
);
diff --git a/packages/database/src/models/__tests__/messages/message.spine.test.ts b/packages/database/src/models/__tests__/messages/message.spine.test.ts
new file mode 100644
index 00000000000..712aced1736
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.spine.test.ts
@@ -0,0 +1,99 @@
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messages, threads, topics, users } from '../../../schemas';
+import { MessageModel } from '../../message';
+
+const db = await getTestDB();
+const userId = 'spine-operation-user';
+const otherUserId = 'spine-operation-other';
+const model = new MessageModel(db, userId);
+const topicId = 'spine-operation-topic';
+const threadId = 'spine-operation-thread';
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(topics).values({ id: topicId, userId });
+ await db.insert(threads).values({ id: threadId, topicId, type: 'isolation', userId });
+});
+afterEach(async () => {
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('operation-scoped message spine', () => {
+ it('ignores a newer assistant from another run and keeps topic-wide reads unchanged', async () => {
+ await db.insert(messages).values([
+ {
+ id: 'own-step',
+ userId,
+ topicId,
+ role: 'assistant',
+ metadata: { operationId: 'new-run' },
+ createdAt: new Date(1000),
+ },
+ {
+ id: 'late-old-step',
+ userId,
+ topicId,
+ role: 'assistant',
+ metadata: { operationId: 'old-run' },
+ createdAt: new Date(2000),
+ },
+ { id: 'legacy-step', userId, topicId, role: 'assistant', createdAt: new Date(3000) },
+ ]);
+ expect(await model.getLatestSpineMessageId({ topicId, operationId: 'new-run' })).toBe(
+ 'own-step',
+ );
+ expect(await model.getLatestSpineMessageId({ topicId })).toBe('legacy-step');
+ expect(await model.getLatestSpineMessageId({ topicId, operationId: 'absent' })).toBeUndefined();
+ expect(
+ await new MessageModel(db, otherUserId).getLatestSpineMessageId({
+ topicId,
+ operationId: 'new-run',
+ }),
+ ).toBeUndefined();
+ });
+
+ it('keeps tool and signal exclusions and thread isolation within an operation', async () => {
+ await db.insert(messages).values([
+ {
+ id: 'own-step',
+ userId,
+ topicId,
+ role: 'assistant',
+ metadata: { operationId: 'run' },
+ createdAt: new Date(1000),
+ },
+ {
+ id: 'own-tool',
+ userId,
+ topicId,
+ role: 'tool',
+ metadata: { operationId: 'run' },
+ createdAt: new Date(2000),
+ },
+ {
+ id: 'own-signal',
+ userId,
+ topicId,
+ role: 'assistant',
+ metadata: { operationId: 'run', signal: { type: 'tool-stdout' } },
+ createdAt: new Date(3000),
+ },
+ {
+ id: 'thread-step',
+ userId,
+ topicId,
+ threadId,
+ role: 'assistant',
+ metadata: { operationId: 'run' },
+ createdAt: new Date(4000),
+ },
+ ]);
+ expect(await model.getLatestSpineMessageId({ topicId, operationId: 'run' })).toBe('own-step');
+ expect(await model.getLatestSpineMessageId({ topicId, threadId, operationId: 'run' })).toBe(
+ 'thread-step',
+ );
+ });
+});
diff --git a/packages/database/src/models/message/spine.ts b/packages/database/src/models/message/spine.ts
index b60e977c6cf..17a429d7e63 100644
--- a/packages/database/src/models/message/spine.ts
+++ b/packages/database/src/models/message/spine.ts
@@ -17,8 +17,9 @@ export class MessageSpineQueries extends MessageScope {
* seed placeholder on a cold / non-sticky serverless replica. Anchoring here
* instead keeps consecutive cold-replica steps chained linearly rather than
* forking onto a stale node (the remote "ζ–­ι“Ύ" bug). No `createdAt` floor is
- * needed: a topic runs at most one operation at a time, so the latest spine
- * message IS this run's continuation point.
+ * needed for a topic-wide conversation tail. An in-flight run must pass its
+ * operationId to getLatestSpineMessageId so late writes from another run
+ * cannot become its continuation point.
*
* Excludes `role:'tool'` (inline children) and TOOLLESS signal-tagged
* assistants (`metadata->'signal'` with no tools), which are tool-child
@@ -80,13 +81,15 @@ export class MessageSpineQueries extends MessageScope {
* close the concurrent-append race: the client computes `parentId` from a
* local snapshot whose spine tail may already have advanced (e.g. another
* assistant turn was written while the user was composing), so trusting it
- * would fork the new turn off a stale node. Ordering by `createdAt` is safe
- * because a topic runs at most one operation at a time.
+ * would fork the new turn off a stale node. Heterogeneous step recovery passes
+ * operationId to restrict the tail to that producer's stamped messages.
*/
getLatestSpineMessageId = async ({
+ operationId,
topicId,
threadId,
}: {
+ operationId?: string;
threadId?: string | null;
topicId: string;
}): Promise<string | undefined> => {
@@ -96,6 +99,9 @@ export class MessageSpineQueries extends MessageScope {
.where(
and(
eq(messages.topicId, topicId),
+ operationId
+ ? sql`${messages.metadata} @> ${JSON.stringify({ operationId })}::jsonb`
+ : undefined,
not(eq(messages.role, 'tool')),
threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),
// Exclude signal-tagged assistants β€” BUT only the toolless ones. The