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: retain route attempt work through streamed fallback (#19794)

YuTengjing28787f5ab76a
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts b/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts
index 521ec5cdd34..11f650aed1f 100644
--- a/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts
@@ -10,6 +10,7 @@ export interface ChatStreamFallbackAttempt {
}
interface CreateChatStreamFallbackResponseOptions {
+ onSettled?: () => void;
shouldFallback: (result: RouteAttemptFinished) => Promise<boolean>;
startAttempt: (index: number) => Promise<ChatStreamFallbackAttempt>;
totalAttempts: number;
@@ -21,6 +22,7 @@ interface CreateChatStreamFallbackResponseOptions {
* starting the next route without mixing output from two providers.
*/
export const createChatStreamFallbackResponse = async ({
+ onSettled,
shouldFallback,
startAttempt,
totalAttempts,
@@ -66,75 +68,87 @@ export const createChatStreamFallbackResponse = async ({
new ReadableStream<Uint8Array>(
{
async cancel(reason) {
- await active.reader?.cancel(reason);
- await active.observation.commit();
+ try {
+ await active.reader?.cancel(reason);
+ await active.observation.commit();
+ } finally {
+ onSettled?.();
+ }
},
async pull(controller) {
- while (true) {
- if (!active.reader) {
- const result = await active.observation.finished;
- if (await shouldFallbackTerminalAttempt(result)) {
- await activateNextAttempt();
- continue;
+ try {
+ while (true) {
+ if (!active.reader) {
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
+ }
+
+ await commitTerminalAttempt(result);
+ if (result.outcome === 'completed') controller.close();
+ else controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
+ onSettled?.();
+ return;
}
- await commitTerminalAttempt(result);
- if (result.outcome === 'completed') controller.close();
- else controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
- return;
- }
+ try {
+ const { done, value } = await active.reader.read();
+ if (!done) {
+ if (committed) {
+ controller.enqueue(value);
+ return;
+ }
- try {
- const { done, value } = await active.reader.read();
- if (!done) {
- if (committed) {
- controller.enqueue(value);
- return;
+ bufferedChunks.push(value);
+ if (active.observation.hasVisibleOutput()) {
+ committed = true;
+ await active.observation.commit();
+ flushBufferedChunks(controller);
+ return;
+ }
+ continue;
}
- bufferedChunks.push(value);
- if (active.observation.hasVisibleOutput()) {
- committed = true;
- await active.observation.commit();
- flushBufferedChunks(controller);
- return;
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
}
- continue;
- }
- const result = await active.observation.finished;
- if (await shouldFallbackTerminalAttempt(result)) {
- await activateNextAttempt();
- continue;
- }
+ await commitTerminalAttempt(result);
+ if (result.outcome === 'completed') {
+ flushBufferedChunks(controller);
+ controller.close();
+ } else {
+ controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
+ }
+ onSettled?.();
+ return;
+ } catch (error) {
+ // A deferred consumer callback can reject before EOF. Cancelling
+ // first lets the observer reach a terminal state without waiting
+ // forever inside the current pull.
+ try {
+ await active.reader.cancel(error);
+ } catch {
+ // The reader may already be errored and the observer terminal.
+ }
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
+ }
- await commitTerminalAttempt(result);
- if (result.outcome === 'completed') {
- flushBufferedChunks(controller);
- controller.close();
- } else {
- controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
+ await commitTerminalAttempt(result);
+ controller.error(error);
+ onSettled?.();
+ return;
}
- return;
- } catch (error) {
- // A deferred consumer callback can reject before EOF. Cancelling
- // first lets the observer reach a terminal state without waiting
- // forever inside the current pull.
- try {
- await active.reader.cancel(error);
- } catch {
- // The reader may already be errored and the observer terminal.
- }
- const result = await active.observation.finished;
- if (await shouldFallbackTerminalAttempt(result)) {
- await activateNextAttempt();
- continue;
- }
-
- await commitTerminalAttempt(result);
- controller.error(error);
- return;
}
+ } catch (error) {
+ onSettled?.();
+ throw error;
}
},
},
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 6adbb47a310..12afde87ec3 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -872,6 +872,180 @@ describe('createRouterRuntime', () => {
);
});
+ it('keeps one request task alive through a fallback started during stream consumption', async () => {
+ let requestOpen = true;
+ let releaseSecondStart!: () => void;
+ let releaseSecondFinish!: () => void;
+ const secondStart = new Promise<void>((resolve) => (releaseSecondStart = resolve));
+ const secondFinish = new Promise<void>((resolve) => (releaseSecondFinish = resolve));
+ let requestSettled!: Promise<void>;
+ let calls = 0;
+ const returned = vi.fn((result: { optionIndex: number; routeRequestManaged?: boolean }) => {
+ expect(result.routeRequestManaged).toBe(true);
+ expect(requestOpen || result.optionIndex === 1).toBe(true);
+ return result.optionIndex === 1 ? secondStart : Promise.resolve();
+ });
+ const finished = vi.fn((result: { optionIndex: number; routeRequestManaged?: boolean }) => {
+ expect(result.routeRequestManaged).toBe(true);
+ return result.optionIndex === 1 ? secondFinish : Promise.resolve();
+ });
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return calls === 1
+ ? createChatResponse(options, { final: { text: '' } })
+ : createChatResponse(options, { final: { text: 'answer' }, text: 'answer' });
+ };
+ }
+ const scheduleRouteRequestSettled = vi.fn((settled: Promise<void>) => {
+ expect(requestOpen).toBe(true);
+ requestSettled = settled;
+ });
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ scheduleRouteRequestSettled,
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+ requestOpen = false;
+ expect(await response.text()).toBe('answer');
+ expect(scheduleRouteRequestSettled).toHaveBeenCalledOnce();
+ expect(returned).toHaveBeenCalledTimes(2);
+ expect(finished).toHaveBeenCalledTimes(2);
+
+ let settled = false;
+ void requestSettled.then(() => (settled = true));
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ releaseSecondStart();
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ releaseSecondFinish();
+ await requestSettled;
+ expect(settled).toBe(true);
+ });
+
+ it('reports a managed route success failure only once', async () => {
+ const error = new Error('affinity unavailable');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onRouteSuccess = vi.fn().mockRejectedValue(error);
+ let requestSettled!: Promise<void>;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) =>
+ createChatResponse(options, { final: { text: 'answer' }, text: 'answer' });
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ onRouteSuccess,
+ routers: [{ apiType: 'openai', models: ['gpt-4'], options: {}, runtime: MockRuntime }],
+ scheduleRouteRequestSettled: (settled) => {
+ requestSettled = settled;
+ },
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+ expect(await response.text()).toBe('answer');
+ await requestSettled;
+ expect(onRouteSuccess).toHaveBeenCalledOnce();
+ expect(onRouteSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({ routeRequestManaged: true }),
+ );
+ expect(consoleError).toHaveBeenCalledOnce();
+ expect(consoleError).toHaveBeenCalledWith(
+ '[RouterRuntime] onRouteSuccess callback failed:',
+ error,
+ );
+ });
+
+ it('settles request work when the streamed response is cancelled', async () => {
+ let requestSettled!: Promise<void>;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async () => new Response(new ReadableStream());
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [{ apiType: 'openai', models: ['gpt-4'], options: {}, runtime: MockRuntime }],
+ scheduleRouteRequestSettled: (settled) => {
+ requestSettled = settled;
+ },
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+ await response.body!.cancel();
+ await expect(requestSettled).resolves.toBeUndefined();
+ });
+
+ it('settles request work when every provider fails before returning a response', async () => {
+ let requestSettled!: Promise<void>;
+ const returned = vi.fn().mockResolvedValue(undefined);
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async () => {
+ throw new Error('provider unavailable');
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ scheduleRouteRequestSettled: (settled) => {
+ requestSettled = settled;
+ },
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ await expect(new Runtime().chat({ messages: [], model: 'gpt-4' })).rejects.toThrow(
+ 'provider unavailable',
+ );
+ await expect(requestSettled).resolves.toBeUndefined();
+ expect(returned).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not mark attempts as managed when request task registration fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const returned = vi.fn().mockResolvedValue(undefined);
+ const finished = vi.fn().mockResolvedValue(undefined);
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) =>
+ createChatResponse(options, { final: { text: 'answer' }, text: 'answer' });
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ routers: [{ apiType: 'openai', models: ['gpt-4'], options: {}, runtime: MockRuntime }],
+ scheduleRouteRequestSettled: async () => {
+ throw new Error('request scope unavailable');
+ },
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+ expect(await response.text()).toBe('answer');
+ expect(returned).toHaveBeenCalledWith(
+ expect.objectContaining({ routeRequestManaged: false }),
+ );
+ expect(finished).toHaveBeenCalledWith(
+ expect.objectContaining({ routeRequestManaged: false }),
+ );
+ expect(consoleError).toHaveBeenCalledWith(
+ '[RouterRuntime] Failed to schedule route request work:',
+ expect.objectContaining({ message: 'request scope unavailable' }),
+ );
+ });
+
it('returns a non-streaming JSON response without retrying another route', async () => {
const finished = vi.fn();
const returned = vi.fn().mockResolvedValue(undefined);
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index c282b14a1b7..d248f89818d 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -56,6 +56,7 @@ import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';
import type { ChatStreamFallbackAttempt } from './chatStreamFallback';
import { createChatStreamFallbackResponse } from './chatStreamFallback';
import type { RouteAttemptFinished, RouteAttemptResult, RouteAttemptStart } from './routeAttempt';
+import { createRouteRequestTasks } from './routeRequestTasks';
export type { RouteAttemptResult } from './routeAttempt';
@@ -163,7 +164,9 @@ export interface RouteSuccessParams {
firstChannelId?: string;
method: RouterRuntimeMethod;
model: string;
+ routeRequestManaged?: boolean;
routerId?: string;
+ trackDeferredWork?: (task: Promise<void>) => void;
userId?: string;
weighted: boolean;
}
@@ -242,6 +245,8 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
) => ChatStreamPayload;
};
routers: Routers;
+ /** Register once while the request context is available. */
+ scheduleRouteRequestSettled?: (settled: Promise<void>) => void | Promise<void>;
shouldFallbackChatAttempt?: (result: RouteAttemptFinished) => boolean | Promise<boolean>;
shouldStopFallback?: (params: {
error: unknown;
@@ -657,14 +662,22 @@ export const createRouterRuntime = ({
}
const firstChannelId = routerOptions[0]?.id;
const weighted = routerOptions.some((option) => option.weight !== undefined);
+ const routeTasks = params.scheduleRouteRequestSettled
+ ? await createRouteRequestTasks(params.scheduleRouteRequestSettled)
+ : undefined;
const reportReturnedAttempt = (
attempt: RouteAttemptStart,
result: Partial<RouteAttemptResult> & Pick<RouteAttemptResult, 'durationMs' | 'success'>,
) => {
- params.onRouteAttempt?.({ ...attempt, ...result } as RouteAttemptResult).catch((error) => {
+ if (!params.onRouteAttempt) return;
+ try {
+ const task = params.onRouteAttempt({ ...attempt, ...result } as RouteAttemptResult);
+ if (routeTasks) routeTasks.track(task);
+ else task.catch((error) => log('onRouteAttempt callback error: %O', error));
+ } catch (error) {
log('onRouteAttempt callback error: %O', error);
- });
+ }
};
const shouldContinueAfterRequestError = async (error: unknown, optionIndex: number) => {
@@ -712,6 +725,7 @@ export const createRouterRuntime = ({
providerId: id,
remark,
requestId,
+ routeRequestManaged: Boolean(routeTasks),
routerId: matchedRouter.id,
startedAt: Date.now(),
userId: routeAttemptUserId,
@@ -723,7 +737,11 @@ export const createRouterRuntime = ({
options,
attempt,
payload.stream !== false,
- params.onRouteAttemptFinished!,
+ (result) => {
+ const task = params.onRouteAttemptFinished!(result);
+ if (routeTasks) routeTasks.track(Promise.resolve(task));
+ else return task;
+ },
{ deferCallbacks: true },
);
const durationMs = Date.now() - attempt.startedAt;
@@ -754,16 +772,25 @@ export const createRouterRuntime = ({
if (!params.onRouteSuccess) return;
try {
- await params.onRouteSuccess({
- channelId,
- channelWeight: optionItem.weight,
- firstChannelId,
- method: routeContext.method,
- model: payload.model,
- routerId: matchedRouter.id,
- userId: routeAttemptUserId,
- weighted,
+ /** Report failures here so the request tracker only waits for the handled task. */
+ const task = Promise.resolve(
+ params.onRouteSuccess({
+ channelId,
+ channelWeight: optionItem.weight,
+ firstChannelId,
+ method: routeContext.method,
+ model: payload.model,
+ routerId: matchedRouter.id,
+ routeRequestManaged: Boolean(routeTasks),
+ trackDeferredWork: routeTasks?.track,
+ userId: routeAttemptUserId,
+ weighted,
+ }),
+ ).catch((error) => {
+ console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
});
+ routeTasks?.track(task);
+ await task;
} catch (error) {
// Affinity storage must not turn a successful upstream response into a fallback.
console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
@@ -798,18 +825,24 @@ export const createRouterRuntime = ({
}
};
- return createChatStreamFallbackResponse({
- shouldFallback: async (result) => {
- try {
- return Boolean(await params.shouldFallbackChatAttempt?.(result));
- } catch (error) {
- log('shouldFallbackChatAttempt callback error: %O', error);
- return false;
- }
- },
- startAttempt,
- totalAttempts: routerOptions.length,
- });
+ try {
+ return await createChatStreamFallbackResponse({
+ onSettled: routeTasks?.settle,
+ shouldFallback: async (result) => {
+ try {
+ return Boolean(await params.shouldFallbackChatAttempt?.(result));
+ } catch (error) {
+ log('shouldFallbackChatAttempt callback error: %O', error);
+ return false;
+ }
+ },
+ startAttempt,
+ totalAttempts: routerOptions.length,
+ });
+ } catch (error) {
+ routeTasks?.settle();
+ throw error;
+ }
}
private async runWithFallback<T>(
diff --git a/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts
index 0c38001443a..56e50123635 100644
--- a/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts
@@ -17,6 +17,8 @@ export interface RouteAttemptResult {
providerId: string;
remark?: string;
requestId?: string;
+ /** A request-scoped task owns this attempt's asynchronous reporting. */
+ routeRequestManaged?: boolean;
routerId?: string;
startedAt?: number;
success: boolean;
diff --git a/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts b/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts
new file mode 100644
index 00000000000..51bc2ff7f46
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts
@@ -0,0 +1,31 @@
+/** Keep request-scoped background work alive until the stream and its callbacks settle. */
+export const createRouteRequestTasks = async (
+ schedule: (settled: Promise<void>) => void | Promise<void>,
+) => {
+ let resolveTerminal!: () => void;
+ const terminal = new Promise<void>((resolve) => (resolveTerminal = resolve));
+ const pending = new Set<Promise<void>>();
+ const settled = (async () => {
+ await terminal;
+ while (pending.size > 0) await Promise.allSettled(pending);
+ })();
+
+ try {
+ await schedule(settled);
+ } catch (error) {
+ console.error('[RouterRuntime] Failed to schedule route request work:', error);
+ resolveTerminal();
+ return undefined;
+ }
+
+ return {
+ settle: resolveTerminal,
+ track(task: Promise<void>) {
+ const observed = Promise.resolve(task).catch((error) => {
+ console.error('[RouterRuntime] Route request work failed:', error);
+ });
+ pending.add(observed);
+ void observed.then(() => pending.delete(observed));
+ },
+ };
+};