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.

✨ feat(model-runtime): add DatabasePersistError code for failed DB queries (#15279)

Arvin Xu8aa075cd805d
diff --git a/packages/model-runtime/src/errors/match.test.ts b/packages/model-runtime/src/errors/match.test.ts
index c12f62f5a1e..0896e0197f4 100644
--- a/packages/model-runtime/src/errors/match.test.ts
+++ b/packages/model-runtime/src/errors/match.test.ts
@@ -54,6 +54,60 @@ describe('matchErrorPattern', () => {
it('returns undefined for genuinely unknown errors', () => {
expect(matchErrorPattern({ message: 'something we have never seen before' })).toBeUndefined();
});
+
+ it('classifies Drizzle "Failed query:" wraps as DatabasePersistError', () => {
+ expect(matchErrorPattern({ message: 'Failed query: rollback params:' })?.code).toBe(
+ AgentRuntimeErrorType.DatabasePersistError,
+ );
+ });
+
+ it('does not let a Failed-query SQL blob trip an unrelated provider pattern', () => {
+ // The SQL text embeds parameter values (model names, error_log rows) that
+ // contain substrings matching other patterns. DatabasePersistError sits
+ // first in the registry, so it must win regardless of the embedded blob.
+ const msg =
+ 'Failed query: insert into "error_logs" ("type") values ($1) -- InsufficientQuota / context length exceeded';
+ expect(matchErrorPattern({ message: msg })?.code).toBe(
+ AgentRuntimeErrorType.DatabasePersistError,
+ );
+ });
+
+ it('classifies Redis/Upstash state-store aborts as StateStorePersistError (not provider network)', () => {
+ expect(matchErrorPattern({ message: 'Command aborted due to connection close' })?.code).toBe(
+ AgentRuntimeErrorType.StateStorePersistError,
+ );
+ expect(
+ matchErrorPattern({ message: 'ERR max request size exceeded. Limit: 10485760 bytes' })?.code,
+ ).toBe(AgentRuntimeErrorType.StateStorePersistError);
+ });
+
+ it('classifies harness JS runtime crashes as AgentRuntimeError', () => {
+ for (const message of [
+ 'e.trim is not a function',
+ "Cannot read properties of undefined (reading '0')",
+ 'Maximum call stack size exceeded',
+ '[object Object]',
+ ]) {
+ expect(matchErrorPattern({ message })?.code, message).toBe(
+ AgentRuntimeErrorType.AgentRuntimeError,
+ );
+ }
+ });
+
+ it('routes context-engine processor crashes to ContextEnginePipelineError', () => {
+ expect(
+ matchErrorPattern({ message: 'Processor [PlaceholderVariablesProcessor] execution failed' })
+ ?.code,
+ ).toBe(AgentRuntimeErrorType.ContextEnginePipelineError);
+ // …even when the nested cause is a bare TypeError (pipeline wins, not the
+ // generic "Cannot read properties" fallback).
+ expect(
+ matchErrorPattern({
+ message:
+ "Processor [X] execution failed: Cannot read properties of undefined (reading 'y')",
+ })?.code,
+ ).toBe(AgentRuntimeErrorType.ContextEnginePipelineError);
+ });
});
describe('isUserSideError', () => {
diff --git a/packages/model-runtime/src/errors/patterns.ts b/packages/model-runtime/src/errors/patterns.ts
index e671b2140ac..06579e05b0d 100644
--- a/packages/model-runtime/src/errors/patterns.ts
+++ b/packages/model-runtime/src/errors/patterns.ts
@@ -47,6 +47,18 @@ const sub = (value: string, opts?: { caseInsensitive?: boolean }): ErrorPattern[
* `packages/model-runtime/src/utils/`.
*/
export const ERROR_PATTERNS: ErrorPattern[] = [
+ // ─────────────────────────────────────────────────────────────────────────
+ // DatabasePersistError β€” MUST stay first. Drizzle stringifies failed queries
+ // as `Failed query: <sql> params: <values>`, embedding arbitrary parameter
+ // text (model names, user messages, error_log rows) that otherwise trips
+ // unrelated provider patterns below. First-match-wins, so claim it up front.
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.DatabasePersistError,
+ match: sub('Failed query:'),
+ note: 'Drizzle wrapper around a failed Postgres query / transaction.',
+ },
+
// ─────────────────────────────────────────────────────────────────────────
// ExceededContextWindow
// ─────────────────────────────────────────────────────────────────────────
@@ -488,11 +500,25 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
{ code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('request to http://') },
{ code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('request to https://') },
{ code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('self-signed certificate') },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('Network connection lost') },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // StateStorePersistError β€” Redis / Upstash agent-state store (NOT the LLM
+ // provider). ioredis aborts, request-size cap, suspended DB.
+ // ─────────────────────────────────────────────────────────────────────────
{
- code: AgentRuntimeErrorType.ProviderNetworkError,
+ code: AgentRuntimeErrorType.StateStorePersistError,
match: sub('Command aborted due to connection close'),
+ note: 'ioredis aborts queued commands when the Upstash connection drops.',
+ },
+ {
+ code: AgentRuntimeErrorType.StateStorePersistError,
+ match: sub('max request size exceeded'),
+ },
+ {
+ code: AgentRuntimeErrorType.StateStorePersistError,
+ match: sub('database has been suspended'),
},
- { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('Network connection lost') },
// ─────────────────────────────────────────────────────────────────────────
// NoAvailableChannel β€” router / proxy has no upstream
@@ -935,4 +961,31 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
match: sub('codewhisperer#ValidationException'),
note: 'kiro / AWS CodeWhisperer proxy malformed payload',
},
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ContextEnginePipelineError β€” a context-engine pipeline processor crashed.
+ // Sits before the generic JS-crash fallbacks so "Processor [X] execution
+ // failed: Cannot read properties …" is attributed to the pipeline, not the
+ // raw TypeError below.
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.ContextEnginePipelineError,
+ match: sub('Processor ['),
+ note: 'context-engine PipelineError: `Processor [<name>] execution failed`.',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // AgentRuntimeError β€” harness-side JS runtime crashes (V8 TypeError /
+ // RangeError). Our bugs, not upstream provider errors, so they stay LAST: a
+ // more specific provider/harness pattern above wins first, and only genuine
+ // bare crashes fall through to here.
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.AgentRuntimeError, match: sub('is not a function') },
+ { code: AgentRuntimeErrorType.AgentRuntimeError, match: sub('Cannot read properties of') },
+ { code: AgentRuntimeErrorType.AgentRuntimeError, match: sub('Maximum call stack size exceeded') },
+ {
+ code: AgentRuntimeErrorType.AgentRuntimeError,
+ match: sub('[object Object]'),
+ note: 'harness stringified an error object instead of extracting its message',
+ },
];
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index 1eb0a3e3378..3ab79e1ca40 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -362,13 +362,52 @@ export const ERROR_CODE_SPECS: SpecMap = {
[AgentRuntimeErrorType.ConversationParentMissing]: {
code: AgentRuntimeErrorType.ConversationParentMissing,
numericId: 7003,
+ // Usually the user deleted the topic / parent message mid-operation, so
+ // attribution is `user` and it does not count as an operational failure.
+ // (category stays `stream` β€” numericId 7003 is append-only β€” even though
+ // attribution is user-side; the two dimensions are orthogonal.)
+ category: 'stream',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 500,
+ retryable: false,
+ countAsFailure: false,
+ description:
+ 'Conversation chain broken β€” the referenced parent message no longer exists, usually because the user deleted the topic mid-operation.',
+ },
+ [AgentRuntimeErrorType.DatabasePersistError]: {
+ code: AgentRuntimeErrorType.DatabasePersistError,
+ numericId: 7004,
category: 'stream',
severity: 'error',
attribution: 'harness',
httpStatus: 500,
retryable: false,
countAsFailure: true,
- description: 'Conversation chain broken because an assistant/tool message lost its parent.',
+ description: 'Persistence-layer query / transaction failed (Drizzle "Failed query: …").',
+ },
+ [AgentRuntimeErrorType.StateStorePersistError]: {
+ code: AgentRuntimeErrorType.StateStorePersistError,
+ numericId: 7005,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 500,
+ retryable: false,
+ countAsFailure: true,
+ description: 'State-store (Redis / Upstash) connection dropped or command aborted mid-flight.',
+ },
+ [AgentRuntimeErrorType.ContextEnginePipelineError]: {
+ code: AgentRuntimeErrorType.ContextEnginePipelineError,
+ numericId: 7006,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 500,
+ retryable: false,
+ countAsFailure: true,
+ description:
+ 'Context-engine pipeline processor crashed ("Processor [<name>] execution failed").',
},
// ─── 8xxx Provider (catch-all) ────────────────────────────────────────
@@ -538,6 +577,10 @@ export const ERROR_CODE_SPECS: SpecMap = {
*/
const CODE_ALIASES: Record<string, ILobeAgentRuntimeErrorType> = {
[AgentRuntimeErrorType.QuotaLimitReached]: AgentRuntimeErrorType.RateLimitExceeded,
+ // The context-engine throws `PipelineError` (its `error.name`), which lands
+ // in stored error records as `errorType: 'PipelineError'`. Resolve it to the
+ // disambiguated runtime code.
+ PipelineError: AgentRuntimeErrorType.ContextEnginePipelineError,
};
/** Look up the spec for an error code; falls back to `undefined` when unknown. */
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 1457f0a3d58..16ed628a340 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -24,9 +24,11 @@ export const AgentRuntimeErrorType = {
AgentRuntimeError: 'AgentRuntimeError', // Agent Runtime module runtime error
/**
* The `parent_id` referenced by an assistant / tool message no longer exists
- * in the database β€” typically because the parent message was deleted during
- * operation execution. The conversation chain is broken, so the runtime
- * stops fail-fast instead of letting the next step hit another FK violation.
+ * in the database β€” usually because the user deleted the topic / parent
+ * message during operation execution. The conversation chain is broken, so
+ * the runtime stops fail-fast instead of letting the next step hit another
+ * FK violation. Attributed to `user` (expected on topic deletion), not a
+ * harness failure.
*/
ConversationParentMissing: 'ConversationParentMissing',
/**
@@ -95,6 +97,26 @@ export const AgentRuntimeErrorType = {
InvalidBedrockCredentials: 'InvalidBedrockCredentials',
InvalidVertexCredentials: 'InvalidVertexCredentials',
StreamChunkError: 'StreamChunkError',
+ /**
+ * A persistence-layer query / transaction failed (Drizzle "Failed query:
+ * …"). Harness-side: the DB write/read or txn could not complete and
+ * surfaced as an unhandled error instead of being retried / degraded.
+ */
+ DatabasePersistError: 'DatabasePersistError',
+ /**
+ * The Redis / Upstash state store dropped a command mid-flight (ioredis
+ * "Command aborted due to connection close", request-size limit, suspended
+ * DB, …). Harness-side infra β€” the agent state layer, not the LLM provider.
+ */
+ StateStorePersistError: 'StateStorePersistError',
+ /**
+ * A context-engine pipeline processor threw while building the prompt
+ * context ("Processor [<name>] execution failed"). Harness-side bug in the
+ * context assembly stage β€” the `PipelineError` thrown by
+ * `packages/context-engine` (its `error.name` is `PipelineError`, aliased
+ * to this code in the spec table).
+ */
+ ContextEnginePipelineError: 'ContextEnginePipelineError',
InvalidGithubToken: 'InvalidGithubToken',
InvalidGithubCopilotToken: 'InvalidGithubCopilotToken',
diff --git a/src/locales/default/modelRuntime.ts b/src/locales/default/modelRuntime.ts
index f323a7a1912..5a303ae6d66 100644
--- a/src/locales/default/modelRuntime.ts
+++ b/src/locales/default/modelRuntime.ts
@@ -20,6 +20,10 @@ export default {
'The request returned empty. Please check if the API proxy address does not end with `/v1`.',
ContentModeration:
'Sorry, the content was rejected by the upstream safety filter. Please revise your prompt and try again.',
+ ContextEnginePipelineError:
+ 'Failed to assemble the conversation context for this request. Please try again; if it persists, contact support.',
+ DatabasePersistError:
+ 'A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.',
ExceededContextWindow:
'The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.',
InsufficientQuota:
@@ -61,6 +65,8 @@ export default {
"Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.",
RateLimitExceeded:
"Sorry, the token usage or request count has reached the rate limit for this key. Please try again later or increase the key's quota.",
+ StateStorePersistError:
+ 'A temporary issue with the conversation state store interrupted this operation. Please try again; if it persists, contact support.',
StreamChunkError:
'Error parsing the message chunk of the streaming request. Please check if the current API interface complies with the standard specifications, or contact your API provider for assistance.',
UserConfigError: