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): never hold a steer for a run that already ended (#23451)

Mocha620271f40cc2
diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
index 0416803b651..3c051b21f1a 100644
--- a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
@@ -102,6 +102,7 @@ beforeEach(() => {
mocks.boundOperations.mockResolvedValue({ operationIds: ['op-1'], total: 1 });
mocks.drain.mockResolvedValue([]);
mocks.findById.mockResolvedValue(undefined);
+ mocks.isRunAlive.mockResolvedValue(true);
mocks.queryByIds.mockResolvedValue([]);
mocks.settle.mockResolvedValue(undefined);
mocks.renew.mockResolvedValue(true);
@@ -345,6 +346,38 @@ describe('takeHeteroSteer', () => {
expect(mocks.settle).toHaveBeenLastCalledWith(scope, expect.any(String));
expect(mocks.deliveries.size).toBe(0);
});
+ // A poll of a killed producer can outlive it (the host does not cancel the
+ // request), and take what the stop just returned. Nothing renews or returns
+ // that hold, so every later send would queue behind it until its lease lapsed.
+ describe('for a run that ended meanwhile', () => {
+ beforeEach(() => {
+ mocks.isRunAlive.mockResolvedValue(false);
+ });
+
+ it('gives the follow-up back instead of holding it', async () => {
+ mocks.drain.mockResolvedValue([followUp('a', 1)]);
+
+ await expect(take()).resolves.toBeUndefined();
+
+ expect(mocks.isRunAlive).toHaveBeenCalledWith(ctx, 'user-1', 'op-1');
+ const [, drainId] = mocks.settle.mock.calls[0];
+ expect(mocks.settle).toHaveBeenLastCalledWith(scope, drainId, ['a']);
+ expect(mocks.deliveries.size).toBe(0);
+ });
+
+ it('gives back a delivery that lapsed back instead of holding it again', async () => {
+ mocks.deliveries.set(
+ 'msg-a',
+ JSON.stringify({ content: 'prompt a', drainId: 'old', entryId: 'a', scope }),
+ );
+ mocks.drain.mockResolvedValue([followUp('a', 1)]);
+
+ await expect(take()).resolves.toBeUndefined();
+
+ expect(mocks.settle).toHaveBeenLastCalledWith(scope, expect.any(String), ['a']);
+ expect(mocks.deliveries.size).toBe(0);
+ });
+ });
});
describe('renewHeteroSteers', () => {
diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.ts
index aa321608f63..6314d3ab98c 100644
--- a/apps/server/src/services/aiAgent/steerQueue/hetero.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.ts
@@ -26,6 +26,7 @@ import {
returnFollowUps,
takeSameSenderFollowUps,
} from './index';
+import { isRunAlive } from './liveRuns';
const log = debug('lobe-server:steer-queue:hetero');
@@ -91,6 +92,40 @@ export const renewHeteroSteers = async (operationId: string) => {
}
};
+/**
+ * Hold a delivery for the run, unless the run ended meanwhile: then put it
+ * back in the queue and report that it is not held.
+ *
+ * A poll can outlive the producer that sent it (a host that does not cancel a
+ * request when its client disconnects keeps the long-poll running), and take
+ * the follow-ups the run's end just returned. Nothing would renew or return
+ * that hold, so they would read as being delivered, and hold every later send
+ * behind them, until their lease lapsed. A run's end writes its terminal
+ * status before it releases what the run holds, and this writes the hold
+ * before it reads the status: either the release finds this hold, or this
+ * read finds the end.
+ *
+ * @returns whether the run holds the delivery
+ */
+const holdHeteroDelivery = async (
+ ctx: StoreContext,
+ operationId: string,
+ messageId: string,
+ delivery: HeteroSteerDelivery,
+): Promise<boolean> => {
+ await redisService.steerQueue.putHeteroDelivery(operationId, messageId, delivery);
+ const alive = await isRunAlive(ctx, ctx.userId, operationId).catch((error) => {
+ // Unknown: keep the hold, whose lease still puts it back if the run is gone.
+ log('[%s] checking the run before holding %s failed: %O', operationId, messageId, error);
+ return true;
+ });
+ if (alive) return true;
+
+ log('[%s] run ended meanwhile, putting %s back', operationId, messageId);
+ await returnHeteroSteer(operationId, messageId);
+ return false;
+};
+
/** Whether a session that takes image input only if `acceptsImages` can take this follow-up now. */
const fitsSession = (entry: QueuedFollowUp, acceptsImages: boolean | undefined) =>
acceptsImages || collectMarkdownImageUrls(entry.request.prompt).length === 0;
@@ -144,10 +179,10 @@ export const takeHeteroSteer = async (
const ids = new Set(delivery.entryIds ?? [delivery.entryId]);
const others = drained.entries.filter((entry) => !ids.has(entry.id));
await returnFollowUps(scope, drained, others, 'behind a delivery the session holds');
- await redisService.steerQueue.putHeteroDelivery(operationId, lapsedId, {
+ await holdHeteroDelivery(ctx, operationId, lapsedId, {
...delivery,
drainId: drained.drainId,
- } satisfies HeteroSteerDelivery);
+ });
return;
}
@@ -221,10 +256,10 @@ export const takeHeteroSteer = async (
// Keep holding it under the new batch instead of sending it twice.
const earlier = held[messageId];
if (earlier) {
- await redisService.steerQueue.putHeteroDelivery(operationId, messageId, {
+ await holdHeteroDelivery(ctx, operationId, messageId, {
...earlier,
drainId: drained.drainId,
- } satisfies HeteroSteerDelivery);
+ });
return;
}
@@ -234,7 +269,7 @@ export const takeHeteroSteer = async (
return;
}
- await redisService.steerQueue.putHeteroDelivery(operationId, messageId, {
+ const holding = await holdHeteroDelivery(ctx, operationId, messageId, {
agentSender: joining[0].agentSender,
content: request.prompt,
drainId: drained.drainId,
@@ -245,7 +280,8 @@ export const takeHeteroSteer = async (
groupId: request.appContext?.groupId ?? undefined,
scope,
trigger: request.trigger,
- } satisfies HeteroSteerDelivery);
+ });
+ if (!holding) return;
} catch (error) {
await returnFollowUps(scope, drained, joining, error);
return;