🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-runtime): unwrap underlying PG error in formatErrorEventData (#14038)
Arvin Xu042987fe347a
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex cf7d128cbfe..a5f3438ba8c 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -48,6 +48,7 @@ import {} from '@/server/services/toolExecution';import { dispatchClientTool } from './dispatchClientTool';+import { formatErrorEventData } from './formatErrorEventData';import { classifyLLMError, type LLMErrorKind } from './llmErrorClassification';import {createConversationParentMissingError,@@ -194,51 +195,6 @@ const buildToolDiscoveryConfig = (operationToolSet: OperationToolSet, enabledTooreturn { availableTools };};-const formatErrorEventData = (error: unknown, phase: string) => {- let errorMessage = 'Unknown error';- let errorType: string | undefined;-- if (error && typeof error === 'object') {- const payload = error as { error?: unknown; errorType?: unknown; message?: unknown };-- if (typeof payload.errorType === 'string') {- errorType = payload.errorType;- }-- if (typeof payload.message === 'string' && payload.message.length > 0) {- errorMessage = payload.message;- } else if (typeof payload.error === 'string' && payload.error.length > 0) {- errorMessage = payload.error;- } else if (- payload.error &&- typeof payload.error === 'object' &&- 'message' in payload.error &&- typeof payload.error.message === 'string'- ) {- errorMessage = payload.error.message;- } else if (error instanceof Error && error.message.length > 0) {- errorMessage = error.message;- } else if (errorType) {- errorMessage = errorType;- }- } else if (error instanceof Error && error.message.length > 0) {- errorMessage = error.message;- errorType = error.name;- } else if (typeof error === 'string' && error.length > 0) {- errorMessage = error;- }-- if (!errorType && error instanceof Error && error.name) {- errorType = error.name;- }-- return {- error: errorMessage,- errorType,- phase,- };-};-export interface RuntimeExecutorContext {agentConfig?: any;botPlatformContext?: any;diff --git a/src/server/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts b/src/server/modules/AgentRuntime/__tests__/formatErrorEventData.test.tsnew file mode 100644index 00000000000..e712655f4d5--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from 'vitest';++import { formatErrorEventData } from '../formatErrorEventData';++describe('formatErrorEventData', () => {+ describe('PG enrichment', () => {+ it('classifies a top-level PostgresError (has .name set by driver, still unwrapped)', () => {+ // postgres-js style: error IS the PG error at the top level, with a+ // driver-assigned .name like "PostgresError". Prior to the fix this was+ // skipped because the condition required errorType to be missing or+ // exactly "Error" — losing the pg_<code> bucket on the dashboard.+ class PostgresError extends Error {+ code = '22021';+ column = 'state';+ detail = 'invalid byte sequence in column "state"';+ override name = 'PostgresError';+ severity = 'ERROR';+ table = 'message_plugins';+ }+ const err = new PostgresError('invalid byte sequence for encoding "UTF8": 0xed 0xa0 0x9f');++ const out = formatErrorEventData(err, 'tool_message_persist');++ expect(out.errorType).toBe('pg_22021');+ expect(out.error).toBe(+ 'PG 22021 · ERROR · invalid byte sequence for encoding "UTF8": 0xed 0xa0 0x9f · detail=invalid byte sequence in column "state" · table=message_plugins · column=state',+ );+ expect(out.phase).toBe('tool_message_persist');+ });++ it('classifies a top-level pg DatabaseError (plain object shape)', () => {+ // node-postgres throws errors whose .name is "DatabaseError". The+ // diagnostic fields live directly on the instance.+ const err = Object.assign(new Error('duplicate key value violates unique constraint'), {+ code: '23505',+ constraint: 'messages_pkey',+ name: 'DatabaseError',+ severity: 'ERROR',+ table: 'messages',+ });++ const out = formatErrorEventData(err, 'persist');++ expect(out.errorType).toBe('pg_23505');+ expect(out.error).toContain('PG 23505');+ expect(out.error).toContain('constraint=messages_pkey');+ });++ it('unwraps PG info from .cause (drizzle + postgres-js wrapper)', () => {+ const err = new Error('Failed query: insert into "message_plugins" ...');+ (err as any).cause = {+ code: '54000',+ message: 'row is too big: size X, maximum size Y',+ severity: 'ERROR',+ };++ const out = formatErrorEventData(err, 'persist');++ expect(out.errorType).toBe('pg_54000');+ expect(out.error).toBe('PG 54000 · ERROR · row is too big: size X, maximum size Y');+ });+ });++ describe('business-typed errors (must not be overridden)', () => {+ it('preserves ConversationParentMissing errorType and message even when .cause has PG info', () => {+ // Mirrors createConversationParentMissingError from messagePersistErrors.ts:+ // the user-facing errorType lives on the error object directly, and the+ // original driver error is kept under .cause for diagnostics.+ const err = Object.assign(+ new Error('Conversation parent message msg_abc no longer exists.'),+ {+ cause: {+ code: '23503',+ constraint_name: 'messages_parent_id_messages_id_fk',+ message: 'FK violation',+ severity: 'ERROR',+ },+ errorType: 'ConversationParentMissing',+ parentId: 'msg_abc',+ },+ );++ const out = formatErrorEventData(err, 'persist');++ expect(out.errorType).toBe('ConversationParentMissing');+ expect(out.error).toBe('Conversation parent message msg_abc no longer exists.');+ });++ it('preserves a custom errorType even when no .cause PG info exists', () => {+ const err = Object.assign(new Error('rate limited'), {+ errorType: 'ProviderRateLimited',+ });+ const out = formatErrorEventData(err, 'call_llm');+ expect(out.errorType).toBe('ProviderRateLimited');+ expect(out.error).toBe('rate limited');+ });+ });++ describe('non-PG fallbacks (unchanged behavior)', () => {+ it('uses error.name when there is no PG info anywhere', () => {+ const err = new Error('fetch failed');+ (err as any).name = 'TypeError';+ const out = formatErrorEventData(err, 'call_llm');+ expect(out.errorType).toBe('TypeError');+ expect(out.error).toBe('fetch failed');+ });++ it('does not misclassify Node errors with a code but no PG severity', () => {+ // ENOTFOUND has a .code string, but no .severity — must not get pg_<code>.+ const err = Object.assign(new Error('getaddrinfo ENOTFOUND db.example'), {+ code: 'ENOTFOUND',+ });+ const out = formatErrorEventData(err, 'call_llm');+ expect(out.errorType).not.toMatch(/^pg_/);+ expect(out.error).toBe('getaddrinfo ENOTFOUND db.example');+ });++ it('returns Unknown error for null / non-object / non-string inputs', () => {+ expect(formatErrorEventData(null, 'p')).toEqual({+ error: 'Unknown error',+ errorType: undefined,+ phase: 'p',+ });+ expect(formatErrorEventData(undefined, 'p')).toEqual({+ error: 'Unknown error',+ errorType: undefined,+ phase: 'p',+ });+ expect(formatErrorEventData(42, 'p')).toEqual({+ error: 'Unknown error',+ errorType: undefined,+ phase: 'p',+ });+ });++ it('uses a plain string error directly', () => {+ const out = formatErrorEventData('boom', 'p');+ expect(out.error).toBe('boom');+ expect(out.errorType).toBeUndefined();+ });++ it('extracts from a plain payload object with only a message field', () => {+ const out = formatErrorEventData({ message: 'custom failure' }, 'p');+ expect(out.error).toBe('custom failure');+ expect(out.errorType).toBeUndefined();+ });+ });+});diff --git a/src/server/modules/AgentRuntime/__tests__/pgError.test.ts b/src/server/modules/AgentRuntime/__tests__/pgError.test.tsnew file mode 100644index 00000000000..db653663832--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/pgError.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest';++import { formatPgError, pgErrorType, unwrapPgError } from '../pgError';++describe('unwrapPgError', () => {+ it('extracts fields from a top-level pg driver error', () => {+ const err: any = {+ code: '22021',+ column: 'state',+ detail: 'invalid byte sequence',+ message: 'invalid byte sequence for encoding "UTF8": 0xed 0xa0 0x9f',+ severity: 'ERROR',+ table: 'message_plugins',+ };+ expect(unwrapPgError(err)).toEqual({+ code: '22021',+ column: 'state',+ constraint: undefined,+ detail: 'invalid byte sequence',+ message: 'invalid byte sequence for encoding "UTF8": 0xed 0xa0 0x9f',+ severity: 'ERROR',+ table: 'message_plugins',+ });+ });++ it('walks .cause for the drizzle + postgres-js shape', () => {+ const outer: any = new Error('Failed query: insert into "message_plugins" ...');+ outer.cause = { code: '23505', message: 'duplicate key', severity: 'ERROR' };+ expect(unwrapPgError(outer)).toMatchObject({+ code: '23505',+ message: 'duplicate key',+ severity: 'ERROR',+ });+ });++ it('walks nested .cause layers (double-wrapped transaction error)', () => {+ const inner: any = { code: '54000', message: 'row is too big', severity: 'ERROR' };+ const middle: any = new Error('transaction failed');+ middle.cause = inner;+ const outer: any = new Error('Failed query: ...');+ outer.cause = middle;+ expect(unwrapPgError(outer)?.code).toBe('54000');+ });++ it('accepts constraint_name / table_name aliases from pg driver', () => {+ const err: any = {+ code: '23503',+ constraint_name: 'messages_parent_id_messages_id_fk',+ message: 'fk violation',+ severity: 'ERROR',+ table_name: 'messages',+ };+ expect(unwrapPgError(err)).toMatchObject({+ constraint: 'messages_parent_id_messages_id_fk',+ table: 'messages',+ });+ });++ it('rejects objects with a code but no pg severity (not a pg error)', () => {+ // Node-style errors and fetch failures often have a `code` like "ENOTFOUND"+ // but no `severity` — must not be mistaken for a pg error.+ const err: any = new Error('getaddrinfo ENOTFOUND db.example');+ (err as any).code = 'ENOTFOUND';+ expect(unwrapPgError(err)).toBeNull();+ });++ it('rejects objects with an unrecognized severity', () => {+ const err: any = { code: '22021', message: 'x', severity: 'TOTALLY_FAKE' };+ expect(unwrapPgError(err)).toBeNull();+ });++ it('handles null / non-object inputs safely', () => {+ expect(unwrapPgError(null)).toBeNull();+ expect(unwrapPgError(undefined)).toBeNull();+ expect(unwrapPgError('string-error')).toBeNull();+ expect(unwrapPgError(42)).toBeNull();+ });++ it('stops walking at depth 5 to avoid cycles', () => {+ const a: any = new Error('a');+ const b: any = new Error('b');+ a.cause = b;+ b.cause = a;+ // Should not throw / hang — just returns null because no pg error in chain.+ expect(unwrapPgError(a)).toBeNull();+ });+});++describe('formatPgError', () => {+ it('renders a single-line summary with code + severity + message', () => {+ const out = formatPgError({+ code: '22021',+ column: 'state',+ message: 'invalid byte sequence',+ severity: 'ERROR',+ table: 'message_plugins',+ });+ expect(out).toBe(+ 'PG 22021 · ERROR · invalid byte sequence · table=message_plugins · column=state',+ );+ });++ it('omits empty fields', () => {+ const out = formatPgError({ code: '23505', message: 'dup', severity: 'ERROR' });+ expect(out).toBe('PG 23505 · ERROR · dup');+ });+});++describe('pgErrorType', () => {+ it('derives a stable bucket key from the pg code', () => {+ expect(pgErrorType({ code: '22021', message: 'x' })).toBe('pg_22021');+ });++ it('falls back to pg_unknown when code is missing', () => {+ expect(pgErrorType({ message: 'x' })).toBe('pg_unknown');+ });+});diff --git a/src/server/modules/AgentRuntime/formatErrorEventData.ts b/src/server/modules/AgentRuntime/formatErrorEventData.tsnew file mode 100644index 00000000000..a68a0cdacfa--- /dev/null+++ b/src/server/modules/AgentRuntime/formatErrorEventData.ts@@ -0,0 +1,87 @@+import { formatPgError, pgErrorType, unwrapPgError } from './pgError';++/**+ * Normalize an arbitrary thrown value into the shape the runtime stream-event+ * protocol expects. Extracts a human-readable `error` string and a best-effort+ * `errorType` bucket key.+ *+ * Precedence:+ * 1. Business-typed errors that carry an `errorType` string on the error+ * object itself (e.g. `ConversationParentMissing`) — kept as-is with+ * their original message. These already mean something specific and+ * must not be reclassified.+ * 2. PostgreSQL errors — detected anywhere in the `.cause` chain OR at the+ * top level (driver classes like `PostgresError` / `DatabaseError`+ * carry their own `name` but no business-typed `errorType`). Emitted as+ * `pg_<sqlstate>` with a formatted single-line diagnostic.+ * 3. Anything else — falls back to `error.message` + `error.name`, or+ * `"Unknown error"` when the value isn't even an Error.+ *+ * See LOBE-7158 / LOBE-7334 for the motivation: Drizzle wraps driver errors+ * as `"Failed query: insert into ..."` and buries the real diagnostic fields+ * under `.cause`, which left the agent-gateway dashboard unable to bucket+ * DB failures by SQLSTATE.+ */+export const formatErrorEventData = (error: unknown, phase: string) => {+ let errorMessage = 'Unknown error';+ let errorType: string | undefined;+ // True when `errorType` came from a business-typed field on the error+ // payload (step 1 above). Driver class names assigned via `error.name`+ // do NOT set this flag, so raw `PostgresError` / `DatabaseError` instances+ // still fall through to the PG unwrap step.+ let hasBusinessErrorType = false;++ if (error && typeof error === 'object') {+ const payload = error as { error?: unknown; errorType?: unknown; message?: unknown };++ if (typeof payload.errorType === 'string') {+ errorType = payload.errorType;+ hasBusinessErrorType = true;+ }++ if (typeof payload.message === 'string' && payload.message.length > 0) {+ errorMessage = payload.message;+ } else if (typeof payload.error === 'string' && payload.error.length > 0) {+ errorMessage = payload.error;+ } else if (+ payload.error &&+ typeof payload.error === 'object' &&+ 'message' in payload.error &&+ typeof payload.error.message === 'string'+ ) {+ errorMessage = payload.error.message;+ } else if (error instanceof Error && error.message.length > 0) {+ errorMessage = error.message;+ } else if (errorType) {+ errorMessage = errorType;+ }+ } else if (error instanceof Error && error.message.length > 0) {+ errorMessage = error.message;+ errorType = error.name;+ } else if (typeof error === 'string' && error.length > 0) {+ errorMessage = error;+ }++ if (!errorType && error instanceof Error && error.name) {+ errorType = error.name;+ }++ // Enrichment: run PG unwrap whenever no *business-typed* errorType was+ // declared. This covers both Drizzle-wrapped errors (PG info under .cause)+ // AND raw top-level driver errors like `PostgresError` / `DatabaseError`+ // which carry a specific `name` but are still real PG errors deserving+ // `pg_<sqlstate>` classification on the dashboard.+ if (!hasBusinessErrorType) {+ const pg = unwrapPgError(error);+ if (pg) {+ errorMessage = formatPgError(pg);+ errorType = pgErrorType(pg);+ }+ }++ return {+ error: errorMessage,+ errorType,+ phase,+ };+};diff --git a/src/server/modules/AgentRuntime/pgError.ts b/src/server/modules/AgentRuntime/pgError.tsnew file mode 100644index 00000000000..488748a12a3--- /dev/null+++ b/src/server/modules/AgentRuntime/pgError.ts@@ -0,0 +1,101 @@+/**+ * Helpers for extracting PostgreSQL error diagnostics from errors thrown by+ * the `drizzle-orm` + `postgres-js` (or `pg`) stack.+ *+ * Drizzle wraps the underlying driver error as `.cause`; some paths double-wrap+ * (e.g. transaction runners), so walking a few layers is necessary. Without+ * unwrapping, the runtime only sees the generic `"Failed query: insert into ..."`+ * wrapper message, which strips every diagnostic field the Agent Harness+ * dashboard needs to classify the failure (see LOBE-7158 / LOBE-7334).+ *+ * @see https://www.postgresql.org/docs/current/errcodes-appendix.html+ */++export interface PgErrorInfo {+ code?: string;+ column?: string;+ constraint?: string;+ detail?: string;+ message: string;+ severity?: string;+ table?: string;+}++/**+ * PG `severity` values that appear on driver errors. Used as a duck-type+ * signature to distinguish real PG errors from unrelated objects that happen+ * to have a `code` string (e.g. Node `ERR_*` errors, fetch failures).+ */+const PG_SEVERITIES = new Set([+ 'ERROR',+ 'FATAL',+ 'PANIC',+ 'WARNING',+ 'NOTICE',+ 'DEBUG',+ 'INFO',+ 'LOG',+]);++const MAX_CAUSE_DEPTH = 5;++const looksLikePgError = (value: any): boolean =>+ !!value &&+ typeof value === 'object' &&+ typeof value.code === 'string' &&+ typeof value.severity === 'string' &&+ PG_SEVERITIES.has(value.severity);++/**+ * Walk the `.cause` chain up to {@link MAX_CAUSE_DEPTH} layers looking for an+ * object shaped like a raw PG driver error. Returns its diagnostic fields+ * flattened into {@link PgErrorInfo}, or `null` if no PG layer is found.+ *+ * Field aliases covered:+ * - `constraint` / `constraint_name` (postgres-js vs pg)+ */+export const unwrapPgError = (error: unknown): PgErrorInfo | null => {+ let current: any = error;+ for (let i = 0; i < MAX_CAUSE_DEPTH && current && typeof current === 'object'; i++) {+ if (looksLikePgError(current)) {+ return {+ code: current.code,+ column: current.column,+ constraint: current.constraint ?? current.constraint_name,+ detail: current.detail,+ message: typeof current.message === 'string' ? current.message : 'PG error',+ severity: current.severity,+ table: current.table ?? current.table_name,+ };+ }+ current = current.cause;+ }+ return null;+};++/**+ * Format a {@link PgErrorInfo} as a single-line human-readable string suitable+ * for the `error` field of a runtime stream event. Fields are joined with+ * ` · ` so downstream log viewers stay greppable.+ */+export const formatPgError = (info: PgErrorInfo): string =>+ [+ `PG ${info.code ?? '?'}`,+ info.severity,+ info.message,+ info.detail && `detail=${info.detail}`,+ info.table && `table=${info.table}`,+ info.column && `column=${info.column}`,+ info.constraint && `constraint=${info.constraint}`,+ ]+ .filter(Boolean)+ .join(' · ');++/**+ * Stable `errorType` tag derived from the PG SQLSTATE code. Agent Harness+ * dashboards bucket errors by `errorType` — using a fine-grained `pg_<code>`+ * keeps distinct PG failures (e.g. 22021 invalid UTF-8 vs 23505 unique+ * violation vs 54000 row-too-big) in separate buckets instead of collapsing+ * them all under a generic "DatabaseError".+ */+export const pgErrorType = (info: PgErrorInfo): string => `pg_${info.code ?? 'unknown'}`;