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(memory): retry transient model outages, keep extraction inside the context window, type user-side failures (#22894)

Arvin Xufdbe281ae00b
diff --git a/apps/server/src/services/memory/userMemory/__tests__/extract.errors.test.ts b/apps/server/src/services/memory/userMemory/__tests__/extract.errors.test.ts
index cf44c00eb9a..7e45ac04d2f 100644
--- a/apps/server/src/services/memory/userMemory/__tests__/extract.errors.test.ts
+++ b/apps/server/src/services/memory/userMemory/__tests__/extract.errors.test.ts
@@ -1,8 +1,15 @@
import { describe, expect, it } from 'vitest';
+import { AsyncTaskErrorType } from '@/types/asyncTask';
import { LayersEnum } from '@/types/userMemory';
-import { buildAsyncTaskErrorFrom, describeError } from '../extract/errors';
+import {
+ buildAsyncTaskErrorFrom,
+ classifyExtractionError,
+ describeError,
+ MemoryExtractionAggregateError,
+} from '../extract/errors';
+import { splitExtractorContextBudget } from '../extract/extractTopic';
import { normalizeLayerError } from '../extract/persistExtraction';
// The shape model runtimes throw: a plain payload, not an Error.
@@ -45,3 +52,59 @@ describe('extraction errors no longer lose their cause', () => {
expect(task.body.detail).toBe('google QuotaLimitReached: You exceeded your current quota');
});
});
+
+describe('failures that are not ours are typed apart', () => {
+ it('records an exhausted budget as SubscriptionPlanLimit', () => {
+ const task = buildAsyncTaskErrorFrom({
+ error: {},
+ errorType: 'InsufficientBudgetForModel',
+ message: 'Budget exceeded',
+ provider: 'lobehub',
+ }) as { name: string };
+
+ expect(task.name).toBe(AsyncTaskErrorType.SubscriptionPlanLimit);
+ });
+
+ it('records a provider content block as ProviderContentModeration', () => {
+ const task = buildAsyncTaskErrorFrom(
+ new Error('400 request blocked by (PROHIBITED_CONTENT): content is prohibited'),
+ ) as { name: string };
+
+ expect(task.name).toBe(AsyncTaskErrorType.ProviderContentModeration);
+ });
+
+ it('classifies layer errors by their messages', () => {
+ const task = buildAsyncTaskErrorFrom(
+ new MemoryExtractionAggregateError(
+ 'Memory extraction encountered layer errors: [extract] activities: lobehub InsufficientBudgetForModel: Budget exceeded',
+ [],
+ ),
+ ) as { name: string };
+
+ expect(task.name).toBe(AsyncTaskErrorType.SubscriptionPlanLimit);
+ });
+
+ it('keeps other failures as ServerError', () => {
+ expect((buildAsyncTaskErrorFrom(new Error('boom')) as { name: string }).name).toBe(
+ AsyncTaskErrorType.ServerError,
+ );
+ expect(classifyExtractionError('lobehub ExceededContextWindow: 400')).toBeUndefined();
+ });
+});
+
+describe('splitExtractorContextBudget', () => {
+ it('keeps the parts together within the limit', () => {
+ const budget = splitExtractorContextBudget(100_000);
+
+ expect(budget.topic + budget.memories + budget.identities).toBeLessThanOrEqual(100_000);
+ expect(budget.topic).toBeGreaterThan(budget.memories);
+ });
+
+ it('leaves trimming off when no limit is configured', () => {
+ expect(splitExtractorContextBudget(undefined)).toEqual({
+ identities: undefined,
+ memories: undefined,
+ topic: undefined,
+ });
+ });
+});
diff --git a/apps/server/src/services/memory/userMemory/extract/errors.ts b/apps/server/src/services/memory/userMemory/extract/errors.ts
index 1fa4427c7ea..b2632087770 100644
--- a/apps/server/src/services/memory/userMemory/extract/errors.ts
+++ b/apps/server/src/services/memory/userMemory/extract/errors.ts
@@ -72,6 +72,21 @@ export const describeError = (error: unknown, limit = 500): string => {
}
};
+// Failures that are the user's situation, not ours: an exhausted budget, or content the
+// provider refuses to process. Recorded under their own type so dashboards can count them as
+// skipped rather than as extraction failures.
+const BUDGET_ERROR =
+ /InsufficientBudgetForModel|FreePlanLimit|SubscriptionPlanLimit|Budget exceeded/;
+const CONTENT_POLICY_ERROR =
+ /ProviderContentPolicyViolation|ProviderContentModeration|PROHIBITED_CONTENT|content is prohibited|内容安全/;
+
+/** The task error type for a failure that is not ours to fix, if it is one. */
+export const classifyExtractionError = (message: string): AsyncTaskErrorType | undefined => {
+ if (BUDGET_ERROR.test(message)) return AsyncTaskErrorType.SubscriptionPlanLimit;
+ if (CONTENT_POLICY_ERROR.test(message)) return AsyncTaskErrorType.ProviderContentModeration;
+ return undefined;
+};
+
type MemoryExtractionErrorStage = 'extract' | 'persist' | 'retrieval';
export interface MemoryExtractionTaskErrorItem extends AsyncTaskStructuredErrorItem {
@@ -160,9 +175,13 @@ export const buildAsyncTaskErrorFrom = (
if (error instanceof MemoryExtractionAggregateError) {
return {
body: buildAsyncTaskStructuredError(error.message, error.items),
- name: AsyncTaskErrorType.ServerError,
+ name: classifyExtractionError(error.message) ?? AsyncTaskErrorType.ServerError,
};
}
- return new AsyncTaskError(AsyncTaskErrorType.ServerError, describeError(error));
+ const message = describeError(error);
+ return new AsyncTaskError(
+ classifyExtractionError(message) ?? AsyncTaskErrorType.ServerError,
+ message,
+ );
};
diff --git a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
index 4ac693274cd..817d31ebebb 100644
--- a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
+++ b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
@@ -54,6 +54,19 @@ const isTopicExtracted = (metadata?: ChatTopicMetadata | null): boolean => {
);
};
+/**
+ * Shares the extractor context limit between the parts of one request. Each part used to be
+ * trimmed to the whole limit, so topic + recalled memories + identities could reach three times
+ * it and overflow the model window.
+ */
+export const splitExtractorContextBudget = (limit?: number) => {
+ if (!limit || limit <= 0) return { identities: undefined, memories: undefined, topic: undefined };
+ return {
+ identities: Math.floor(limit * 0.1),
+ memories: Math.floor(limit * 0.2),
+ topic: Math.floor(limit * 0.7),
+ };
+};
export async function reportUserInitiatedProgress(
ctx: MemoryExtractionExecutorContext,
job: TopicExtractionJob,
@@ -197,6 +210,8 @@ export async function extractTopic(ctx: MemoryExtractionExecutorContext, job: To
}
const extractorContextLimit = memoryServiceConfig.extractorContextLimit;
+ // The limit is the whole dynamic slice of one request; the parts share it.
+ const budget = splitExtractorContextBudget(extractorContextLimit);
const embeddingContextLimit =
memoryServiceConfig.embeddingContextLimit ?? extractorContextLimit;
const extractorConversations = await ctx.trimConversationsToTokenLimit(
@@ -292,14 +307,13 @@ export async function extractTopic(ctx: MemoryExtractionExecutorContext, job: To
extractionJob.userId,
extractionJob.sourceId,
);
- const trimmedRetrievedContexts = await Promise.all(
- [topicContext.context, retrievalMemoryContext.context].map((context) =>
- ctx.trimTextToTokenLimit(context, extractorContextLimit),
- ),
- );
+ const trimmedRetrievedContexts = await Promise.all([
+ ctx.trimTextToTokenLimit(topicContext.context, budget.topic),
+ ctx.trimTextToTokenLimit(retrievalMemoryContext.context, budget.memories),
+ ]);
const trimmedRetrievedIdentitiesContext = await ctx.trimTextToTokenLimit(
retrievedIdentityContext.context,
- extractorContextLimit,
+ budget.identities,
);
const taxonomyOptions = await new UserMemoryModel(db, job.userId).queryTaxonomyOptions({
include: ['categories', 'labels', 'tags'],
diff --git a/packages/memory-user-memory/src/extractors/base.ts b/packages/memory-user-memory/src/extractors/base.ts
index edacd2ecf95..e4fd2c1e900 100644
--- a/packages/memory-user-memory/src/extractors/base.ts
+++ b/packages/memory-user-memory/src/extractors/base.ts
@@ -21,6 +21,7 @@ import type {
TemplateProps,
} from '../types';
import { parseLenient } from '../utils/lenientParse';
+import { withTransientRetry } from '../utils/transientRetry';
import { buildGenerateObjectSchema } from '../utils/zod';
const serializeForSpan = (value: unknown, limit = 4000) => {
@@ -183,19 +184,21 @@ export abstract class BaseMemoryExtractor<
}
span.addEvent('gen_ai.request.send');
- const result = await this.runtime.generateObject(payload, {
- metadata: {
- // Optional backlink to the job-level memory trace blob; the
- // llm_generation_tracing hook persists it under metadata so a
- // per-call row can be traced back to the job-level dump.
- ...(options?.parentMemoryTraceKey
- ? { parent_memory_trace_key: options.parentMemoryTraceKey }
- : {}),
- ...(options?.taskId ? { taskId: options.taskId } : {}),
- ...(options?.topicId ? { topicId: options.topicId } : {}),
- trigger: RequestTrigger.Memory,
- },
- });
+ const result = await withTransientRetry(() =>
+ this.runtime.generateObject(payload, {
+ metadata: {
+ // Optional backlink to the job-level memory trace blob; the
+ // llm_generation_tracing hook persists it under metadata so a
+ // per-call row can be traced back to the job-level dump.
+ ...(options?.parentMemoryTraceKey
+ ? { parent_memory_trace_key: options.parentMemoryTraceKey }
+ : {}),
+ ...(options?.taskId ? { taskId: options.taskId } : {}),
+ ...(options?.topicId ? { topicId: options.topicId } : {}),
+ trigger: RequestTrigger.Memory,
+ },
+ }),
+ );
span.addEvent('gen_ai.response.receive');
span.setAttributes({
diff --git a/packages/memory-user-memory/src/utils/__tests__/transientRetry.test.ts b/packages/memory-user-memory/src/utils/__tests__/transientRetry.test.ts
new file mode 100644
index 00000000000..fd306ba4130
--- /dev/null
+++ b/packages/memory-user-memory/src/utils/__tests__/transientRetry.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { isTransientModelError, withTransientRetry } from '../transientRetry';
+
+describe('isTransientModelError', () => {
+ it('treats provider outages as transient', () => {
+ expect(
+ isTransientModelError(new Error('503 The model service is temporarily unavailable.')),
+ ).toBe(true);
+ expect(isTransientModelError({ errorType: 'ProviderServiceUnavailable', error: {} })).toBe(
+ true,
+ );
+ expect(isTransientModelError({ error: { status: 502 } })).toBe(true);
+ expect(
+ isTransientModelError({
+ error: { error: { message: 'This model is currently experiencing high demand.' } },
+ }),
+ ).toBe(true);
+ });
+
+ it('reads a transient outage nested under a wrapper message', () => {
+ // handleOpenAIError keeps the SDK's `Connection error.` and tucks the socket error underneath,
+ // so matching only the top-level message drops every reset and timeout on the floor.
+ expect(
+ isTransientModelError({
+ message: 'Connection error.',
+ error: new Error('read ECONNRESET'),
+ }),
+ ).toBe(true);
+ expect(
+ isTransientModelError({
+ error: { message: 'Connection error.', error: { error: { code: 'ETIMEDOUT' } } },
+ }),
+ ).toBe(true);
+ expect(isTransientModelError({ message: 'Connection error.', error: { status: 503 } })).toBe(
+ true,
+ );
+ expect(
+ isTransientModelError({
+ message: 'Connection error.',
+ error: new Error('getaddrinfo ENOTFOUND api.openai.com'),
+ }),
+ ).toBe(false);
+ });
+
+ it('does not retry quota, budget, context or content errors', () => {
+ expect(isTransientModelError(new Error('429 You exceeded your current quota'))).toBe(false);
+ expect(isTransientModelError({ errorType: 'InsufficientBudgetForModel', error: {} })).toBe(
+ false,
+ );
+ expect(isTransientModelError({ errorType: 'ExceededContextWindow', error: {} })).toBe(false);
+ expect(isTransientModelError(new Error('400 request blocked by (PROHIBITED_CONTENT)'))).toBe(
+ false,
+ );
+ });
+});
+
+describe('withTransientRetry', () => {
+ it('retries a transient failure and returns the later success', async () => {
+ const call = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('503 temporarily unavailable'))
+ .mockResolvedValue('ok');
+
+ await expect(withTransientRetry(call, { delaysMs: [0, 0] })).resolves.toBe('ok');
+ expect(call).toHaveBeenCalledTimes(2);
+ });
+
+ it('gives up after the configured attempts', async () => {
+ const call = vi.fn().mockRejectedValue(new Error('503 temporarily unavailable'));
+
+ await expect(withTransientRetry(call, { delaysMs: [0, 0] })).rejects.toThrow('503');
+ expect(call).toHaveBeenCalledTimes(3);
+ });
+
+ it('fails at once on a non-transient error', async () => {
+ const call = vi.fn().mockRejectedValue(new Error('429 You exceeded your current quota'));
+
+ await expect(withTransientRetry(call, { delaysMs: [0, 0] })).rejects.toThrow('429');
+ expect(call).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/memory-user-memory/src/utils/transientRetry.ts b/packages/memory-user-memory/src/utils/transientRetry.ts
new file mode 100644
index 00000000000..08dfda8b812
--- /dev/null
+++ b/packages/memory-user-memory/src/utils/transientRetry.ts
@@ -0,0 +1,70 @@
+const TRANSIENT_ERROR_TYPES = new Set(['ProviderServiceUnavailable']);
+const TRANSIENT_STATUS = new Set([502, 503, 504, 529]);
+// Matched on the message too: providers report outages as plain text more often than as types.
+const TRANSIENT_MESSAGE =
+ /\b(502|503|504|529)\b|temporarily unavailable|overloaded|high demand|ECONNRESET|ETIMEDOUT|socket hang up/i;
+
+const readField = (value: unknown, key: string): unknown =>
+ value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined;
+
+// Wrapped provider errors keep their own message and put the real cause underneath, up to a few
+// levels deep (SDK error -> wrapper -> socket error). The top-level message alone loses the cause.
+const MAX_NESTED_DEPTH = 3;
+const NESTED_KEYS = ['message', 'code', 'error', 'cause'] as const;
+
+const inspectError = (error: unknown): { messages: string[]; statuses: number[] } => {
+ const messages: string[] = [];
+ const statuses: number[] = [];
+ const seen = new Set<unknown>();
+
+ const visit = (value: unknown, depth: number) => {
+ if (value === null || value === undefined) return;
+ if (typeof value === 'string') {
+ messages.push(value);
+ return;
+ }
+ // Only objects recurse, so strings at the bottom of the chain are always read.
+ if (typeof value !== 'object' || depth > MAX_NESTED_DEPTH || seen.has(value)) return;
+ seen.add(value);
+
+ const record = value as Record<string, unknown>;
+ const status = record.status;
+ if (typeof status === 'number') statuses.push(status);
+ for (const key of NESTED_KEYS) visit(record[key], depth + 1);
+ };
+
+ visit(error, 0);
+ return { messages, statuses };
+};
+
+/**
+ * Whether a model call failed for a reason worth retrying: the provider was briefly down or
+ * overloaded. Quota, budget, auth and content errors are not transient and fail at once.
+ */
+export const isTransientModelError = (error: unknown): boolean => {
+ const errorType = readField(error, 'errorType');
+ if (typeof errorType === 'string' && TRANSIENT_ERROR_TYPES.has(errorType)) return true;
+ const { messages, statuses } = inspectError(error);
+ if (statuses.some((status) => TRANSIENT_STATUS.has(status))) return true;
+ return messages.some((message) => TRANSIENT_MESSAGE.test(message));
+};
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Runs a model call, retrying transient provider failures with a growing delay. Each call already
+ * sits inside a workflow step, so a few seconds of waiting beats failing the whole extraction.
+ */
+export const withTransientRetry = async <T>(
+ call: () => Promise<T>,
+ { delaysMs = [2000, 6000] }: { delaysMs?: number[] } = {},
+): Promise<T> => {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ return await call();
+ } catch (error) {
+ if (attempt >= delaysMs.length || !isTransientModelError(error)) throw error;
+ await sleep(delaysMs[attempt]);
+ }
+ }
+};