25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(query): preserve structured backend errors
miraclebcafc4a474ca
diff --git a/.gitignore b/.gitignoreindex 514c389733..3c635fac6a 100644--- a/.gitignore+++ b/.gitignore@@ -23,6 +23,7 @@ docs/.next/docs/out/docs/.source/docs/superpowers/+/docs/aegis/src-tauri/*.dylib# OS filesdiff --git a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.javaindex 3323881d33..c91ec03ef0 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java@@ -113,6 +113,7 @@ public final class AgentProtocol {public static final String CAPABILITY_ETCD_LEASE = "etcd_lease";public static final String CAPABILITY_ETCD_AUTH = "etcd_auth";public static final String CAPABILITY_MULTI_SESSION = "multi_session";+ public static final String CAPABILITY_STRUCTURED_ERROR_V1 = "structured_error_v1";public static final List<String> CAPABILITIES = Collections.unmodifiableList(Arrays.asList(CAPABILITY_CONNECT,@@ -147,6 +148,8 @@ public final class AgentProtocol {public static final List<String> MULTI_SESSION_CAPABILITIES;public static final List<String> MULTI_SESSION_ALL_CAPABILITIES;+ public static final List<String> MULTI_SESSION_JDBC_CAPABILITIES;+ public static final List<String> MULTI_SESSION_JDBC_ALL_CAPABILITIES;public static final List<String> COMMON_METHODS = Collections.unmodifiableList(Arrays.asList(METHOD_HANDSHAKE,@@ -194,6 +197,14 @@ public final class AgentProtocol {allCapabilities.add(CAPABILITY_MULTI_SESSION);MULTI_SESSION_ALL_CAPABILITIES = Collections.unmodifiableList(allCapabilities);+ List<String> jdbcCapabilities = new java.util.ArrayList<>(MULTI_SESSION_CAPABILITIES);+ jdbcCapabilities.add(CAPABILITY_STRUCTURED_ERROR_V1);+ MULTI_SESSION_JDBC_CAPABILITIES = Collections.unmodifiableList(jdbcCapabilities);++ List<String> jdbcAllCapabilities = new java.util.ArrayList<>(MULTI_SESSION_ALL_CAPABILITIES);+ jdbcAllCapabilities.add(CAPABILITY_STRUCTURED_ERROR_V1);+ MULTI_SESSION_JDBC_ALL_CAPABILITIES = Collections.unmodifiableList(jdbcAllCapabilities);+List<String> methods = new java.util.ArrayList<>(COMMON_METHODS);int insertAt = methods.indexOf(METHOD_CONNECT) + 1;methods.addAll(insertAt, Arrays.asList(@@ -270,6 +281,18 @@ public final class AgentProtocol {);}+ /**+ * Handshake for pooled JDBC Agents that emit the v1 structured error contract.+ * Generic/custom v2 handlers must continue using multiSessionHandshakeResult().+ */+ public static HandshakeResult multiSessionJdbcHandshakeResult() {+ return new HandshakeResult(+ MULTI_SESSION_PROTOCOL_VERSION,+ MULTI_SESSION_PROTOCOL_VERSION,+ MULTI_SESSION_JDBC_CAPABILITIES+ );+ }+public static final class HandshakeResult {private final int protocolVersion;private final int agentProtocolVersion;diff --git a/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java b/agents/common/src/main/java/com/dbx/agent/AgentRpcError.javaindex bb356e1b2d..aed7c39979 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java@@ -3,15 +3,21 @@ package com.dbx.agent;import com.google.gson.JsonObject;import java.sql.SQLException;+import java.sql.SQLTimeoutException;import java.sql.SQLRecoverableException;import java.sql.SQLTransientConnectionException;import java.util.Locale;+import java.util.concurrent.CancellationException;final class AgentRpcError extends RuntimeException {private final String category;private final boolean retryable;private final String disposition;private final String stage;+ private final String operationOutcome;+ private final String sqlState;+ private final Integer vendorCode;+ private final String exceptionClass;private AgentRpcError(String message,@@ -19,6 +25,10 @@ final class AgentRpcError extends RuntimeException {boolean retryable,String disposition,String stage,+ String operationOutcome,+ String sqlState,+ Integer vendorCode,+ String exceptionClass,Throwable cause) {super(message, cause);@@ -26,6 +36,10 @@ final class AgentRpcError extends RuntimeException {this.retryable = retryable;this.disposition = disposition;this.stage = stage;+ this.operationOutcome = operationOutcome;+ this.sqlState = sqlState;+ this.vendorCode = vendorCode;+ this.exceptionClass = exceptionClass;}static AgentRpcError resource(String stage, Throwable cause) {@@ -35,6 +49,10 @@ final class AgentRpcError extends RuntimeException {false,"replace_runtime",stage,+ operationOutcome(stage),+ null,+ null,+ cause == null ? null : cause.getClass().getName(),cause);}@@ -46,6 +64,10 @@ final class AgentRpcError extends RuntimeException {true,"keep",stage,+ operationOutcome(stage),+ null,+ null,+ cause == null ? null : cause.getClass().getName(),cause);}@@ -60,6 +82,13 @@ final class AgentRpcError extends RuntimeException {data.addProperty("retryable", classified.retryable);data.addProperty("sessionDisposition", classified.disposition);data.addProperty("stage", classified.stage);+ data.addProperty("contractVersion", 1);+ data.addProperty("operationOutcome", classified.operationOutcome);+ addDiagnostic(data, "sqlState", classified.sqlState);+ if (classified.vendorCode != null) {+ data.addProperty("vendorCode", classified.vendorCode);+ }+ addDiagnostic(data, "exceptionClass", classified.exceptionClass);if (agentSessionId != null && !agentSessionId.trim().isEmpty()) {data.addProperty("agentSessionId", agentSessionId);}@@ -72,34 +101,69 @@ final class AgentRpcError extends RuntimeException {if (explicit != null) {return explicit;}+ String stage = stage(method);+ if (find(error, CancellationException.class) != null || find(error, InterruptedException.class) != null) {+ return new AgentRpcError(+ message(error),+ "canceled",+ false,+ "quarantine",+ stage,+ operationOutcome(stage),+ null,+ null,+ safeClassName(error),+ error+ );+ }SQLException sqlError = find(error, SQLException.class);if (sqlError != null) {String sqlState = sqlError.getSQLState();- String stage = stage(method);+ String category = sqlError instanceof SQLTimeoutException ? "timeout" : null;boolean connectionError = "connect".equals(stage)|| "validate".equals(stage)|| sqlError instanceof SQLRecoverableException|| sqlError instanceof SQLTransientConnectionException|| (sqlState != null && sqlState.toUpperCase(Locale.ROOT).startsWith("08"));boolean operationRetryable = connectionError && ("connect".equals(stage) || "validate".equals(stage));- String disposition = connectionError && !"connect".equals(stage) ? "quarantine" : "keep";+ String disposition = category != null || (connectionError && !"connect".equals(stage)) ? "quarantine" : "keep";return new AgentRpcError(message(error),- connectionError ? "connection" : "sql",+ category == null ? (connectionError ? "connection" : "sql") : category,operationRetryable,disposition,stage,+ operationOutcome(stage),+ safeSqlState(sqlState),+ sqlError.getErrorCode(),+ safeClassName(sqlError),error);}- return new AgentRpcError(message(error), "protocol", false, "keep", stage(method), error);+ return new AgentRpcError(+ message(error),+ "protocol",+ false,+ "keep",+ stage,+ operationOutcome(stage),+ null,+ null,+ safeClassName(error),+ error+ );}private static String stage(String method) {if (method == null) {return "request";}- if (AgentProtocol.METHOD_CONNECT.equals(method) || AgentProtocol.METHOD_OPEN_SESSION.equals(method)) {+ if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {+ return "request";+ }+ if (AgentProtocol.METHOD_CONNECT.equals(method)+ || AgentProtocol.METHOD_OPEN_SESSION.equals(method)+ || AgentProtocol.METHOD_TEST_CONNECTION.equals(method)) {return "connect";}if (AgentProtocol.METHOD_VALIDATE_CONNECTION.equals(method) || AgentProtocol.METHOD_VALIDATE_SESSION.equals(method)) {@@ -108,7 +172,11 @@ final class AgentRpcError extends RuntimeException {if (AgentProtocol.METHOD_CANCEL_SESSION.equals(method)) {return "cancel";}- if (AgentProtocol.METHOD_CLOSE_SESSION.equals(method) || AgentProtocol.METHOD_DISCONNECT.equals(method)) {+ if (AgentProtocol.METHOD_CLOSE_SESSION.equals(method)+ || AgentProtocol.METHOD_DISCONNECT.equals(method)+ || AgentProtocol.METHOD_CLOSE_QUERY_SESSION.equals(method)+ || AgentProtocol.METHOD_CLOSE_TABLE_READ_SESSION.equals(method)+ || AgentProtocol.METHOD_SHUTDOWN.equals(method)) {return "close";}if (AgentProtocol.METHOD_FETCH_QUERY_PAGE.equals(method)@@ -122,6 +190,41 @@ final class AgentRpcError extends RuntimeException {return error.getMessage() == null ? error.toString() : error.getMessage();}+ private static String operationOutcome(String stage) {+ return switch (stage) {+ case "request", "checkout", "connect", "validate" -> "not_started";+ default -> "unknown";+ };+ }++ private static String safeSqlState(String sqlState) {+ return safeDiagnostic(sqlState, 16);+ }++ private static String safeClassName(Throwable error) {+ return error == null ? null : safeDiagnostic(error.getClass().getName(), 160);+ }++ private static String safeDiagnostic(String value, int maxLength) {+ if (value == null) {+ return null;+ }+ StringBuilder safe = new StringBuilder(Math.min(value.length(), maxLength));+ for (int index = 0; index < value.length() && safe.length() < maxLength; index++) {+ char character = value.charAt(index);+ if (character >= 0x21 && character <= 0x7e) {+ safe.append(character);+ }+ }+ return safe.isEmpty() ? null : safe.toString();+ }++ private static void addDiagnostic(JsonObject data, String name, String value) {+ if (value != null && !value.isBlank()) {+ data.addProperty(name, value);+ }+ }+private static <T extends Throwable> T find(Throwable error, Class<T> type) {Throwable current = error;while (current != null) {diff --git a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.javaindex f9dd6fa4eb..4d4f9bf59a 100644--- a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java@@ -27,7 +27,7 @@ import java.util.function.Supplier;public final class MultiSessionJsonRpcServer implements AutoCloseable {private static final String LEGACY_SESSION_ID = "__legacy__";- private static final int MAX_SESSIONS = 256;+ static final int MAX_SESSIONS = 256;private static final int MAX_REQUEST_THREADS = 64;private static final int MAX_CLEANUP_THREADS = 16;private static final long MAINTENANCE_INTERVAL_MILLIS = 60_000L;@@ -137,7 +137,7 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {try {Object result;if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {- result = sessionHandlerFactory == null ? AgentProtocol.multiSessionHandshakeResult() : customHandshake();+ result = sessionHandlerFactory == null ? AgentProtocol.multiSessionJdbcHandshakeResult() : customHandshake();} else if (AgentProtocol.METHOD_OPEN_SESSION.equals(method)) {result = openSession(requiredSessionId(params), params);} else if (AgentProtocol.METHOD_CLOSE_SESSION.equals(method)) {@@ -171,7 +171,10 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {private Object openSession(String sessionId, JsonObject params) throws Exception {if (sessions.size() >= MAX_SESSIONS && !sessions.containsKey(sessionId)) {- throw new IllegalStateException("Agent session limit reached: " + MAX_SESSIONS);+ throw AgentRpcError.backpressure(+ "connect",+ new IllegalStateException("Agent session limit reached: " + MAX_SESSIONS)+ );}Session session;if (sessionHandlerFactory != null) {diff --git a/agents/common/src/main/resources/agent-protocol-v2.json b/agents/common/src/main/resources/agent-protocol-v2.jsonindex 8764572baa..bc282be4a9 100644--- a/agents/common/src/main/resources/agent-protocol-v2.json+++ b/agents/common/src/main/resources/agent-protocol-v2.json@@ -2,9 +2,9 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "multi_session"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "multi_session", "structured_error_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],- "defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],+ "defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": ["handshake","connect",diff --git a/agents/common/src/test/java/com/dbx/agent/AgentRpcErrorTest.java b/agents/common/src/test/java/com/dbx/agent/AgentRpcErrorTest.javanew file mode 100644index 0000000000..c4721bf6b3--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/AgentRpcErrorTest.java@@ -0,0 +1,97 @@+package com.dbx.agent;++import com.google.gson.JsonObject;+import org.junit.jupiter.api.Test;++import java.sql.SQLException;+import java.sql.SQLTimeoutException;+import java.util.concurrent.CancellationException;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;++class AgentRpcErrorTest {+ @Test+ void serializesVersionedSqlDiagnosticsAndUnknownExecuteOutcome() {+ SQLException cause = new SQLException("statement failed", "42000", 1064);++ JsonObject data = errorData(cause, AgentProtocol.METHOD_EXECUTE_QUERY, "session-1");++ assertEquals(1, data.get("contractVersion").getAsInt());+ assertEquals("sql", data.get("category").getAsString());+ assertEquals("execute", data.get("stage").getAsString());+ assertEquals("unknown", data.get("operationOutcome").getAsString());+ assertEquals("keep", data.get("sessionDisposition").getAsString());+ assertEquals("42000", data.get("sqlState").getAsString());+ assertEquals(1064, data.get("vendorCode").getAsInt());+ assertEquals(SQLException.class.getName(), data.get("exceptionClass").getAsString());+ assertEquals("session-1", data.get("agentSessionId").getAsString());+ }++ @Test+ void classifiesTimeoutAndCanceledErrorsWithoutClaimingSafeReplay() {+ JsonObject timeout = errorData(+ new SQLTimeoutException("timed out", "HYT00", 0),+ AgentProtocol.METHOD_EXECUTE_QUERY,+ "session-1"+ );+ JsonObject canceled = errorData(+ new CancellationException("canceled"),+ AgentProtocol.METHOD_CANCEL_SESSION,+ "session-1"+ );++ assertEquals("timeout", timeout.get("category").getAsString());+ assertEquals("unknown", timeout.get("operationOutcome").getAsString());+ assertFalse(timeout.get("retryable").getAsBoolean());+ assertEquals("quarantine", timeout.get("sessionDisposition").getAsString());+ assertEquals("canceled", canceled.get("category").getAsString());+ assertEquals("cancel", canceled.get("stage").getAsString());+ assertEquals("unknown", canceled.get("operationOutcome").getAsString());+ }++ @Test+ void marksConnectionSetupFailureAsNotStartedAndBoundsSqlState() {+ SQLException cause = new SQLException("connect failed", "12345678901234567890", -7);++ JsonObject data = errorData(cause, AgentProtocol.METHOD_CONNECT, null);++ assertEquals("connection", data.get("category").getAsString());+ assertEquals("connect", data.get("stage").getAsString());+ assertEquals("not_started", data.get("operationOutcome").getAsString());+ assertEquals(16, data.get("sqlState").getAsString().length());+ assertFalse(data.has("agentSessionId"));+ }++ @Test+ void removesNonGraphicCharactersFromStrictDiagnostics() {+ SQLException cause = new SQLException("connect failed", "08\n006\u00e9", -7);++ JsonObject data = errorData(cause, AgentProtocol.METHOD_CONNECT, null);++ assertEquals("08006", data.get("sqlState").getAsString());+ }++ @Test+ void mapsConnectionAndCloseMethodsToTheSameStagesAsTheRustDecoder() {+ JsonObject testConnection = errorData(+ new SQLException("connect failed", "08001", 0),+ AgentProtocol.METHOD_TEST_CONNECTION,+ null+ );+ JsonObject closeQuery = errorData(+ new SQLException("close failed", "42000", 0),+ AgentProtocol.METHOD_CLOSE_QUERY_SESSION,+ "session-1"+ );++ assertEquals("connect", testConnection.get("stage").getAsString());+ assertEquals("not_started", testConnection.get("operationOutcome").getAsString());+ assertEquals("close", closeQuery.get("stage").getAsString());+ assertEquals("unknown", closeQuery.get("operationOutcome").getAsString());+ }++ private static JsonObject errorData(Throwable error, String method, String agentSessionId) {+ return AgentRpcError.toJson(error, method, agentSessionId).getAsJsonObject("data");+ }+}diff --git a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.javaindex 60a10d6040..0e71c87ef1 100644--- a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java+++ b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java@@ -72,7 +72,7 @@ class CommonJavaCompatibilityTest {strings(contract.getAsJsonArray("handshakeResponseFields")));assertEquals(- AgentProtocol.MULTI_SESSION_ALL_CAPABILITIES,+ AgentProtocol.MULTI_SESSION_JDBC_ALL_CAPABILITIES,strings(contract.getAsJsonArray("allCapabilities")));assertEquals(@@ -80,7 +80,7 @@ class CommonJavaCompatibilityTest {strings(contract.getAsJsonArray("capabilities")));assertEquals(- AgentProtocol.MULTI_SESSION_CAPABILITIES,+ AgentProtocol.MULTI_SESSION_JDBC_CAPABILITIES,strings(contract.getAsJsonArray("defaultSqlCapabilities")));assertEquals(AgentProtocol.MULTI_SESSION_METHODS, strings(contract.getAsJsonArray("commonMethods")));@@ -164,6 +164,7 @@ class CommonJavaCompatibilityTest {)).getAsJsonObject().getAsJsonObject("result");assertEquals(2, handshake.get("protocolVersion").getAsInt());assertTrue(containsCapability(handshake.getAsJsonArray("capabilities"), "multi_session"));+ assertTrue(containsCapability(handshake.getAsJsonArray("capabilities"), "structured_error_v1"));server.handleRequest("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"open_session\",\"params\":{\"agentSessionId\":\"a\"}}");server.handleRequest("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"open_session\",\"params\":{\"agentSessionId\":\"b\"}}");@@ -177,6 +178,68 @@ class CommonJavaCompatibilityTest {assertEquals(0, created.get(1).disconnectCount);}+ @Test+ void customSessionHandlersDoNotImplicitlyAdvertiseStructuredErrors() {+ MultiSessionJsonRpcServer server = MultiSessionJsonRpcServer.forSessionHandlers(() -> new SessionRpcHandler() {+ @Override+ public Object connect(JsonObject params) {+ return Collections.singletonMap("ok", true);+ }++ @Override+ public Object handle(String method, JsonObject params) {+ return Collections.singletonMap("ok", true);+ }++ @Override+ public void close() {+ }+ });++ JsonObject handshake = JsonParser.parseString(server.handleRequest(+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"handshake\",\"params\":{}}"+ )).getAsJsonObject().getAsJsonObject("result");++ assertTrue(containsCapability(handshake.getAsJsonArray("capabilities"), "multi_session"));+ assertFalse(containsCapability(handshake.getAsJsonArray("capabilities"), "structured_error_v1"));+ }++ @Test+ void multiSessionLimitReturnsStructuredBackpressureBeforeConnectStarts() {+ try (MultiSessionJsonRpcServer server = MultiSessionJsonRpcServer.forSessionHandlers(() -> new SessionRpcHandler() {+ @Override+ public Object connect(JsonObject params) {+ return Collections.singletonMap("ok", true);+ }++ @Override+ public Object handle(String method, JsonObject params) {+ return Collections.singletonMap("ok", true);+ }++ @Override+ public void close() {+ }+ })) {+ for (int index = 0; index < MultiSessionJsonRpcServer.MAX_SESSIONS; index++) {+ JsonObject response = JsonParser.parseString(server.handleRequest(openSessionRequest(index, "session-" + index)))+ .getAsJsonObject();+ assertTrue(response.has("result"), response::toString);+ }++ JsonObject response = JsonParser.parseString(server.handleRequest(+ openSessionRequest(MultiSessionJsonRpcServer.MAX_SESSIONS, "overflow")+ )).getAsJsonObject();+ JsonObject data = response.getAsJsonObject("error").getAsJsonObject("data");++ assertEquals("resource", data.get("category").getAsString());+ assertTrue(data.get("retryable").getAsBoolean());+ assertEquals("keep", data.get("sessionDisposition").getAsString());+ assertEquals("connect", data.get("stage").getAsString());+ assertEquals("not_started", data.get("operationOutcome").getAsString());+ }+ }+@Testvoid multiSessionServerKeepsProtocolOutputWhenGlobalStdoutChanges() {synchronized (System.class) {@@ -1113,6 +1176,17 @@ class CommonJavaCompatibilityTest {return false;}+ private static String openSessionRequest(int requestId, String sessionId) {+ JsonObject params = new JsonObject();+ params.addProperty("agentSessionId", sessionId);+ JsonObject request = new JsonObject();+ request.addProperty("jsonrpc", "2.0");+ request.addProperty("id", requestId);+ request.addProperty("method", AgentProtocol.METHOD_OPEN_SESSION);+ request.add("params", params);+ return request.toString();+ }+private static void awaitCondition(java.util.function.BooleanSupplier condition) throws InterruptedException {long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);while (!condition.getAsBoolean() && System.nanoTime() < deadline) {diff --git a/agents/docs/agent-protocol-v2.md b/agents/docs/agent-protocol-v2.mdindex 9ca6e7dcbb..3bd3eb2c3d 100644--- a/agents/docs/agent-protocol-v2.md+++ b/agents/docs/agent-protocol-v2.md@@ -1,6 +1,6 @@# Agent Protocol v2: Multi-session runtimes-Protocol v2 allows one Agent process to serve multiple isolated database sessions. The handshake advertises `protocolVersion: 2` and the `multi_session` capability. DBX falls back to the v1 one-process-per-pool lifecycle when that capability is absent.+Protocol v2 allows one Agent process to serve multiple isolated database sessions. Pooled JDBC Agents that use the common structured error producer advertise `protocolVersion: 2`, `multi_session`, and `structured_error_v1`. Generic/custom v2 handlers may advertise only `multi_session`. DBX falls back to the v1 one-process-per-pool lifecycle when `multi_session` is absent.## Session lifecycle@@ -37,14 +37,21 @@ JSON-RPC failures may include structured recovery data:```json{+ "contractVersion": 1,"category": "timeout|canceled|connection|protocol|resource|sql","retryable": false,"sessionDisposition": "keep|quarantine|replace_runtime","agentSessionId": "optional-session-id",- "stage": "checkout|connect|validate|execute|fetch|cancel|close"+ "stage": "request|checkout|connect|validate|execute|fetch|cancel|close",+ "operationOutcome": "not_started|unknown",+ "sqlState": "optional-jdbc-sql-state",+ "vendorCode": 0,+ "exceptionClass": "optional-java-exception-class"}```+`contractVersion: 1` is guaranteed only when the handshake advertises `structured_error_v1`. Unknown extra fields are allowed, but unknown enum values, missing required fields, invalid types, or an `agentSessionId` that does not match the current request are contract violations. `operationOutcome` describes whether the user operation may have reached the database; `retryable` is an internal hint and never authorizes automatic SQL replay.+`keep` preserves the logical session, `quarantine` removes only that session from routing, and `replace_runtime` requires DBX to atomically remove every pool sharing the runtime before terminating it. Agent code reports the disposition but must not independently terminate a shared runtime because it does not own DBX routing state. Temporary workload checkout backpressure uses `category=resource`, `retryable=true`, and `sessionDisposition=keep`; only unrecoverable runtime or cleanup saturation requests `replace_runtime`.The complete JDBC pool checkout runs under a bounded runtime executor, including HikariCP idle-connection validation, physical connection creation, and driver setup. Workload admission, the runtime-wide physical connection budget, physical creation, and checkout consume one absolute deadline rather than restarting the timeout at each stage. Connection return, eviction, and physical close use separate bounded executors so they cannot deadlock checkout or creation. If a driver call outlives its boundary, or cleanup cannot confirm the physical connection state, the connection identity is poisoned and returns `category=resource` with `sessionDisposition=replace_runtime` on the current or next checkout. A late connection must be evicted and closed instead of published, and DBX must not replay the timed-out user operation automatically.diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 463675c152..fa14d1a7c7 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -1309,7 +1309,7 @@ async function newQuery() {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);@@ -1344,7 +1344,7 @@ async function newQuery() {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);@@ -1367,7 +1367,7 @@ async function openConnectionQuery(connectionId: string) {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);@@ -1381,7 +1381,7 @@ async function openConnectionQuery(connectionId: string) {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);@@ -1399,7 +1399,7 @@ async function openConnectionQuery(connectionId: string) {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);@@ -1471,7 +1471,7 @@ async function onClickTable(table: SqlObjectNavigationTarget) {try {await openTableTarget(target, { tableInfoTab: "ddl" });} catch (e: any) {- toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);}}@@ -1481,7 +1481,7 @@ async function onViewTableData(table: SqlObjectNavigationTarget) {try {await openTableTarget(target);} catch (e: any) {- toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);}}@@ -1509,7 +1509,7 @@ async function onOpenObjectSource(table: SqlObjectNavigationTarget, initialEditiqueryEditorObjectSourceTarget.value = { connectionId: target.connectionId, database: target.database, schema: target.schema, name: target.tableName, objectType, initialEditing };showQueryEditorObjectSourceDialog.value = true;} catch (e: any) {- toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);}}@@ -1547,7 +1547,7 @@ async function changeActiveConnection(connectionId: string) {} catch (e: any) {toast(t("connection.connectFailed", {- message: translateBackendError(t, e?.message || String(e)),+ message: translateBackendError(t, e),}),5000,);diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex c570d84412..ac75ce528e 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -1502,7 +1502,7 @@ function finishAgentDriverInstall() {function failAgentDriverInstall(error: unknown) {agentInstallOperationId.value = null;agentInstallRunning.value = false;- agentInstallError.value = translateBackendError(t, errorMessage(error));+ agentInstallError.value = translateBackendError(t, error);showAgentInstallDialog.value = true;}@@ -1559,7 +1559,7 @@ async function ensureRequiredAgentDriverInstalled(config: ConnectionConfig): Proawait refreshLocalAgentDrivers();finishAgentDriverInstall();} catch (error) {- testResult.value = { ok: false, message: errorMessage(error) };+ testResult.value = { ok: false, message: translateBackendError(t, error) };failAgentDriverInstall(error);throw error;}@@ -1601,7 +1601,7 @@ async function installSqlServerLegacyCompatibilityComponentIfNeeded(): Promise<bawait refreshLocalAgentDrivers();finishAgentDriverInstall();} catch (error) {- testResult.value = { ok: false, message: errorMessage(error) };+ testResult.value = { ok: false, message: translateBackendError(t, error) };failAgentDriverInstall(error);throw error;}diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex 9a3297bda4..b5ad2fd90d 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -79,6 +79,7 @@ import type { ConnectionConfig, QueryTab, SavedSqlFile, TableInfo } from "@/typeimport { fetchNamespaceOptionsForConnection, useDatabaseOptions } from "@/composables/useDatabaseOptions";import { decodeSelectableDatabaseValue, encodeSelectableDatabaseValue, formatDatabaseLabel, resolveDefaultDatabase } from "@/lib/database/defaultDatabase";import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import { isSchemaAware } from "@/lib/database/databaseCapabilities";import ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";import { parseExplainResult, parseOracleExplainText, type ParsedExplainPlan } from "@/lib/diagram/explainPlan";@@ -662,8 +663,7 @@ watch(function selectAction(action: AiAction) {activeAction.value = action;if (action === "fix" && props.tab?.result) {- const cols = props.tab.result.columns;- if (cols.includes("Error")) {+ if (isQueryExecutionErrorResult(props.tab.result)) {const errVal = props.tab.result.rows[0]?.[0];if (errVal != null) prompt.value = String(errVal);}diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vueindex 88472b824d..588c35a01d 100644--- a/apps/desktop/src/components/grid/DataGrid.vue+++ b/apps/desktop/src/components/grid/DataGrid.vue@@ -67,6 +67,7 @@ import DataGridQueryControls from "@/components/grid/DataGridQueryControls.vue";import TemporalCellEditor from "@/components/grid/TemporalCellEditor.vue";import EnumCellEditor from "@/components/grid/EnumCellEditor.vue";import type { QueryResult, ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo, TableInfoTab } from "@/types/database";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import { tableObjectSourceKind } from "@/lib/table/tableObjectSourceKind";import { tableColumnDefaultDisplayValue } from "@/lib/table/tableColumnDefaultPresentation";import { shouldNavigateFromTableInfoColumnClick } from "@/lib/table/tableInfoColumnNavigation";@@ -3577,7 +3578,7 @@ watch(},{ immediate: true },);-const isErrorResult = computed(() => props.result.columns.length === 1 && props.result.columns[0] === "Error" && props.result.rows.length > 0);+const isErrorResult = computed(() => isQueryExecutionErrorResult(props.result) && props.result.rows.length > 0);const errorMessage = computed(() => (isErrorResult.value ? String(props.result.rows[0]?.[0] ?? "") : ""));// --- Selection composable ---const selection = useDataGridSelection({diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex 87d735b687..59469fd400 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -3,6 +3,7 @@ import { computed, ref, defineAsyncComponent, watch, nextTick, onMounted, onUnmoimport { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";import { appendDebugLog, isDebugLoggingEnabled } from "@/lib/backend/debugLog";import { canReloadUnavailableDataTab } from "@/lib/table/tableDataRefresh";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import type { CSSProperties } from "vue";import { useI18n } from "vue-i18n";import { Check, Columns3Cog, EyeOff, Loader2, Search, TableProperties, ChevronDown, ChevronUp, Inbox, RefreshCcw, Wrench, Toolbox, Database, Download, Upload, X, Pin, Rows3, SquareDashed, Minus, Plus, ShieldAlert, AlignLeft, AlignRight, PanelsTopLeft } from "@lucide/vue";@@ -340,7 +341,7 @@ const hasNumericData = computed(() => {const activeQueryError = computed(() => {const result = props.activeTab.result;- if (!result?.columns.includes("Error")) return "";+ if (!result || !isQueryExecutionErrorResult(result)) return "";return String(result.rows[0]?.[0] ?? "");});const hasQueryOutput = computed(@@ -1480,7 +1481,7 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand@export-archive="exportResultArchive"/></template>- <template v-if="activeTab.result?.columns.includes('Error')" #error-actions="{ errorMessage }">+ <template v-if="activeTab.result && isQueryExecutionErrorResult(activeTab.result)" #error-actions="{ errorMessage }"><QueryErrorActions :error-message="String(errorMessage)" :connection-id="activeTab.connectionId" @change-query-timeout="activeTab.connectionId && emit('openConnectionSettings', activeTab.connectionId, 'advanced')" @fix-with-ai="(message) => emit('fixWithAi', message)" /></template></DataGrid>@@ -1777,7 +1778,7 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand@paginate="(offset: number, limit: number, whereInput?: string, orderBy?: string) => emit('paginate', offset, limit, whereInput, orderBy)"@sort="(column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string, mode?: DataGridSortMode) => emit('sort', column, columnIndex, direction, whereInput, mode)">- <template v-if="activeTab.result?.columns.includes('Error')" #error-actions="{ errorMessage }">+ <template v-if="activeTab.result && isQueryExecutionErrorResult(activeTab.result)" #error-actions="{ errorMessage }"><QueryErrorActions :error-message="String(errorMessage)" :connection-id="activeTab.connectionId" @change-query-timeout="activeTab.connectionId && emit('openConnectionSettings', activeTab.connectionId, 'advanced')" @fix-with-ai="(message) => emit('fixWithAi', message)" /></template></DataGrid>diff --git a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.tsindex 74c0c6cb7e..9a07d07362 100644--- a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts+++ b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts@@ -425,14 +425,14 @@ describe("useSqlExecution", () => {expect(addHistory).toHaveBeenCalledWith(expect.objectContaining({ success: true, error: undefined }));});- it("continues to record active non-MySQL errors as failures", async () => {+ it("continues to record explicitly marked non-MySQL errors as failures", async () => {const activeTab = ref<QueryTab | undefined>(queryTab("app"));const activeConnection = ref<ConnectionConfig | undefined>(connection("postgres"));const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");const queryStore = useQueryStore();const historyStore = useHistoryStore();vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {- if (activeTab.value) activeTab.value.result = { columns: ["Error"], rows: [["relation does not exist"]], affected_rows: 0, execution_time_ms: 1 };+ if (activeTab.value) activeTab.value.result = { columns: ["Error"], rows: [["relation does not exist"]], affected_rows: 0, execution_time_ms: 1, execution_error: true };});const addHistory = vi.spyOn(historyStore, "add").mockResolvedValue(undefined);@@ -448,6 +448,29 @@ describe("useSqlExecution", () => {expect(addHistory).toHaveBeenCalledWith(expect.objectContaining({ success: false, error: "relation does not exist" }));});+ it("does not treat an unmarked PostgreSQL Error alias as a failure", async () => {+ const activeTab = ref<QueryTab | undefined>(queryTab("app"));+ const activeConnection = ref<ConnectionConfig | undefined>(connection("postgres"));+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");+ const queryStore = useQueryStore();+ const historyStore = useHistoryStore();+ vi.spyOn(queryStore, "executeCurrentSql").mockImplementation(async () => {+ if (activeTab.value) activeTab.value.result = { columns: ["Error"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 };+ });+ const addHistory = vi.spyOn(historyStore, "add").mockResolvedValue(undefined);++ const execution = useSqlExecution({+ activeTab: computed(() => activeTab.value),+ activeConnection: computed(() => activeConnection.value),+ executableSql: computed(() => "SELECT 2 AS Error"),+ activeOutputView,+ });++ await execution.tryExecute();++ expect(addHistory).toHaveBeenCalledWith(expect.objectContaining({ success: true, error: undefined }));+ });+it("keeps the full dangerous script and new-result-tab intent through confirmation", async () => {const activeTab = ref<QueryTab | undefined>(queryTab("app"));const activeConnection = ref<ConnectionConfig | undefined>(connection("mysql"));diff --git a/apps/desktop/src/composables/useNavigationTargets.ts b/apps/desktop/src/composables/useNavigationTargets.tsindex 8a1f2d93b5..292c450320 100644--- a/apps/desktop/src/composables/useNavigationTargets.ts+++ b/apps/desktop/src/composables/useNavigationTargets.ts@@ -2,7 +2,7 @@ import * as api from "@/lib/backend/api";import { connectionObjectTreeNodeSchema, effectiveDatabaseTypeForConnection, metadataSchemaForConnection } from "@/lib/database/jdbcDialect";import { invalidateTableMetadataCache, loadTableMetadata } from "@/lib/metadata/tableMetadataCache";import { canApplyDataTabMetadata } from "@/lib/sidebar/dataTabOpenPolicy";-import { isNoSnapshotErrorResult } from "@/lib/query/queryResultError";+import { isNoSnapshotErrorResult, isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import { buildTableSelectSql } from "@/lib/table/tableSelectSql";import { editableRowIdentifierColumns, usesSyntheticRowIdKey } from "@/lib/table/tableEditing";import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";@@ -169,7 +169,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTabconst tabAfterFirstExecute = queryStore.tabs.find((tab) => tab.id === tabId);const firstResult = tabAfterFirstExecute?.result;const cancelRequestedDuringExecute = (tabAfterFirstExecute?.cancelRequestCount ?? 0) > cancelCountBeforeExecute;- const firstQueryFailed = cancelRequestedDuringExecute || tabAfterFirstExecute?.isCancelling === true || (firstResult?.columns.length === 1 && firstResult.columns[0] === "Error");+ const firstQueryFailed = cancelRequestedDuringExecute || tabAfterFirstExecute?.isCancelling === true || (firstResult !== undefined && isQueryExecutionErrorResult(firstResult));// executeTabSql surfaces query failures as an "Error" result instead of throwing.// A snapshot-less lake table fails the data preview above but its metadata still// reads fine — retry with LIMIT 0 so the user sees the table structure (columns +diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.tsindex 38777671af..998be9f9e9 100644--- a/apps/desktop/src/composables/useSqlExecution.ts+++ b/apps/desktop/src/composables/useSqlExecution.ts@@ -9,7 +9,7 @@ import { isSingleDatabase, usesTreeSchemaMode } from "@/lib/database/databaseCapimport { supportsConnectionLevelSqlExecution } from "@/lib/connection/connectionLevelDatabaseBootstrap";import { classifySqlActivityKind } from "@/lib/history/historyActivityKind";import { sqlMetadataRefreshTarget } from "@/lib/sql/sqlMetadataRefresh";-import { isQueryExecutionErrorResult, usesMysqlProtocolDatabaseType } from "@/lib/query/queryResultError";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";import { isSqlExecutionSnapshot, resolveExecutableSql, type SqlExecutionOverride, type SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";import { isElasticsearchRestRequestText, parseElasticsearchRestRequestTarget, splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";@@ -63,10 +63,9 @@ function primarySqlOperation(sql: string): string {return statement?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";}-function firstQueryExecutionError(tab: Pick<QueryTab, "result" | "results">, databaseType: DatabaseType | undefined) {+function firstQueryExecutionError(tab: Pick<QueryTab, "result" | "results">) {const activeResult = tab.result;if (activeResult && isQueryExecutionErrorResult(activeResult)) return activeResult;- if (!usesMysqlProtocolDatabaseType(databaseType) && activeResult?.columns.includes("Error")) return activeResult;const results = tab.results?.length ? tab.results : tab.result ? [tab.result] : [];return results.find((result) => isQueryExecutionErrorResult(result));@@ -233,7 +232,7 @@ export function useSqlExecution(deps: {deps.activeOutputView.value = "summary";}const elapsed = Date.now() - start;- const failure = firstQueryExecutionError(tab, executionDatabaseType);+ const failure = firstQueryExecutionError(tab);const success = !failure;historyStore.add({connection_id: tab.connectionId,diff --git a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts b/apps/desktop/src/i18n/__tests__/backendErrors.spec.tsindex 41f18687de..ac2f0af149 100644--- a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts+++ b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";import { describe, expect, it as test } from "vitest";import { createI18n } from "vue-i18n";import { translateBackendError, type BackendErrorTranslate } from "@/i18n/backend-errors";+import { BackendErrorException, normalizeBackendError } from "@/lib/backend/errorUtils";import en from "@/i18n/locales/en";import es from "@/i18n/locales/es";import it from "@/i18n/locales/it";@@ -24,6 +25,21 @@ const LOCALES = {type LocaleKey = keyof typeof LOCALES;+const STRUCTURED_BACKEND_ERROR_KEYS = [+ "backendErrors.jdbc.connectionFailed",+ "backendErrors.jdbc.connectionInterrupted",+ "backendErrors.jdbc.operationTimedOut",+ "backendErrors.jdbc.operationCanceled",+ "backendErrors.jdbc.busyRetryLater",+ "backendErrors.jdbc.runtimeReplaced",+ "backendErrors.jdbc.sqlFailed",+ "backendErrors.jdbc.protocolFailed",+ "backendErrors.jdbc.contractInvalid",+ "backendErrors.jdbc.legacyFailure",+ "backendErrors.legacy",+ "backendErrors.unknown",+] as const;+// Reproduces the exact string crates/dbx-core/src/agent_service.rs builds on// Windows: `\` line continuations strip the newline plus the following indent.const WINDOWS_JRE_REMOVE_ERROR = [@@ -125,6 +141,12 @@ describe("backend error translation", () => {// alongside the other non-English locales.const localeKeys = Object.keys(LOCALES) as LocaleKey[];+ test.each(localeKeys)("all structured catalog keys exist in %s", (locale) => {+ for (const key of STRUCTURED_BACKEND_ERROR_KEYS) {+ expect(lookup(LOCALES[locale] as unknown as Record<string, unknown>, key), `${locale}:${key}`).toEqual(expect.any(String));+ }+ });+describe.each(localeKeys)("in %s", (locale) => {const t = translatorFor(locale);@@ -157,6 +179,68 @@ describe("backend error translation", () => {expect(translateBackendError(t, new Error(message))).toBe(expected);expect(translateBackendError(t, { message })).toBe(expected);});++ test("preserves and translates structured BackendError envelopes", () => {+ const t = translatorFor("zh-CN");+ const error = {+ version: 1,+ code: "DBX-JDBC-2002",+ messageKey: "backendErrors.jdbc.operationTimedOut",+ messageParams: { stage: "execute" },+ source: "jdbcAgent",+ operationOutcome: "unknown",+ detail: "relation dbx_table_that_does_not_exist does not exist",+ } as const;++ expect(normalizeBackendError(error)).toEqual(error);+ const expected = `${t(error.messageKey, error.messageParams)}\n\n${error.detail}`;+ expect(translateBackendError(t, error)).toBe(expected);+ expect(translateBackendError(t, new BackendErrorException(error))).toBe(expected);+ });++ test("shows the database detail after an unclassified Agent summary", () => {+ const t = translatorFor("zh-CN");+ const error = {+ version: 1,+ code: "DBX-JDBC-9001",+ messageKey: "backendErrors.jdbc.legacyFailure",+ messageParams: {},+ source: "jdbcAgentLegacy",+ operationOutcome: "unknown",+ detail: "Table dbx_table_that_does_not_exist does not exist",+ } as const;++ expect(translateBackendError(t, error)).toBe(`${t(error.messageKey)}\n\n${error.detail}`);+ });++ test.each([+ ["array params", { messageParams: ["execute"] }],+ ["nested params", { messageParams: { stage: { name: "execute" } } }],+ ["non-finite params", { messageParams: { retryAfter: Number.POSITIVE_INFINITY } }],+ ["non-string detail", { detail: 42 }],+ ["object detail", { detail: { message: "database failure" } }],+ ["unknown source", { source: "http" }],+ ["unknown outcome", { operationOutcome: "completed" }],+ ])("rejects malformed structured envelopes with %s", (_name, override) => {+ expect(+ normalizeBackendError({+ version: 1,+ code: "DBX-JDBC-2002",+ messageKey: "backendErrors.jdbc.operationTimedOut",+ messageParams: { stage: "execute" },+ source: "jdbcAgent",+ operationOutcome: "unknown",+ ...override,+ }),+ ).toBeNull();+ });++ test("falls back to legacy text for plain HTTP and Tauri failures", () => {+ const t = translatorFor("zh-CN");+ const error = new BackendErrorException("legacy backend failure");+ expect(error.backendError.code).toBe("DBX-LEGACY-0001");+ expect(translateBackendError(t, error)).toBe(`${t("backendErrors.legacy")}\n\nlegacy backend failure`);+ });});// Matching on message text only works while both sides agree on the wording, sodiff --git a/apps/desktop/src/i18n/backend-errors.ts b/apps/desktop/src/i18n/backend-errors.tsindex 37f8119946..334252020c 100644--- a/apps/desktop/src/i18n/backend-errors.ts+++ b/apps/desktop/src/i18n/backend-errors.ts@@ -1,3 +1,5 @@+import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";+/*** Minimal shape of a translate function, satisfied by both `useI18n().t` inside* components and `i18n.global.t` in stores and composables. Using the full@@ -118,7 +120,17 @@ function backendErrorMessage(error: unknown): string {return String(error);}+function translateStructuredBackendError(t: BackendErrorTranslate, error: BackendError): string {+ const translated = t(error.messageKey, error.messageParams);+ const summary = translated !== error.messageKey ? translated : t("backendErrors.unknown");+ const detail = error.detail?.trim();+ return detail && detail !== summary ? `${summary}\n\n${detail}` : summary;+}+export function translateBackendError(t: BackendErrorTranslate, error: unknown): string {+ const structured = normalizeBackendError(error);+ if (structured) return translateStructuredBackendError(t, structured);+const message = backendErrorMessage(error);const tagged = message.match(/^\[([A-Za-z][A-Za-z0-9]+)\]\s*([\s\S]*)$/);if (tagged) {diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex ee4bdc4629..b87a1ccb59 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1517,6 +1517,22 @@ export default {mcpDescription: "Beyond the built-in AI assistant, you can also use Claude Code, Cursor, and other coding agents to query your databases via MCP.",mcpLearnMore: "Learn more",},+ backendErrors: {+ jdbc: {+ connectionFailed: "Database connection failed before the operation started (stage: {stage}).",+ connectionInterrupted: "Database connection was interrupted while the operation was running (stage: {stage}).",+ operationTimedOut: "Database operation timed out (stage: {stage}).",+ operationCanceled: "Database operation was canceled (stage: {stage}).",+ busyRetryLater: "Database agent is busy; try again later (stage: {stage}).",+ runtimeReplaced: "Database agent runtime was replaced (stage: {stage}).",+ sqlFailed: "Database returned an SQL error (stage: {stage}).",+ protocolFailed: "Database agent protocol failed.",+ contractInvalid: "Database agent returned an invalid error contract.",+ legacyFailure: "Database agent returned an unclassified error.",+ },+ legacy: "Backend returned an error.",+ unknown: "An unexpected backend error occurred.",+ },common: {fileNotFound: "File does not exist: {path}",language: "Language",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex e36707763d..29f6a5b6a5 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1459,6 +1459,22 @@ export default withEnglishFallback({mcpDescription: "Además del asistente de IA integrado, puedes usar Claude Code, Cursor y otros agentes de programación para consultar tus bases de datos mediante MCP.",mcpLearnMore: "Más información",},+ backendErrors: {+ jdbc: {+ connectionFailed: "La conexión a la base de datos falló antes de iniciar la operación (fase: {stage}).",+ connectionInterrupted: "La conexión a la base de datos se interrumpió durante la operación (fase: {stage}).",+ operationTimedOut: "La operación de la base de datos agotó el tiempo de espera (fase: {stage}).",+ operationCanceled: "La operación de la base de datos fue cancelada (fase: {stage}).",+ busyRetryLater: "El agente de la base de datos está ocupado; inténtalo más tarde (fase: {stage}).",+ runtimeReplaced: "Se reemplazó el entorno del agente de la base de datos (fase: {stage}).",+ sqlFailed: "La base de datos devolvió un error SQL (fase: {stage}).",+ protocolFailed: "Falló el protocolo del agente de la base de datos.",+ contractInvalid: "El agente de la base de datos devolvió un contrato de error no válido.",+ legacyFailure: "El agente de la base de datos devolvió un error no clasificado.",+ },+ legacy: "El backend devolvió un error.",+ unknown: "Ocurrió un error inesperado del backend.",+ },common: {fileNotFound: "El archivo no existe: {path}",language: "Idioma",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex fd59aeaa3c..16d22f2a37 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1457,6 +1457,22 @@ export default withEnglishFallback({mcpDescription: "Oltre all'assistente AI integrato, puoi utilizzare Claude Code, Cursor e altri agenti di sviluppo per interrogare i tuoi database tramite MCP.",mcpLearnMore: "Scopri di più",},+ backendErrors: {+ jdbc: {+ connectionFailed: "La connessione al database è fallita prima dell'operazione (fase: {stage}).",+ connectionInterrupted: "La connessione al database è stata interrotta durante l'operazione (fase: {stage}).",+ operationTimedOut: "L'operazione del database è scaduta (fase: {stage}).",+ operationCanceled: "L'operazione del database è stata annullata (fase: {stage}).",+ busyRetryLater: "L'agente del database è occupato; riprova più tardi (fase: {stage}).",+ runtimeReplaced: "Il runtime dell'agente del database è stato sostituito (fase: {stage}).",+ sqlFailed: "Il database ha restituito un errore SQL (fase: {stage}).",+ protocolFailed: "Il protocollo dell'agente del database è fallito.",+ contractInvalid: "L'agente del database ha restituito un contratto di errore non valido.",+ legacyFailure: "L'agente del database ha restituito un errore non classificato.",+ },+ legacy: "Il backend ha restituito un errore.",+ unknown: "Si è verificato un errore backend imprevisto.",+ },common: {fileNotFound: "Il file non esiste: {path}",language: "Lingua",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 59932d05d5..6b823f8696 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1484,6 +1484,22 @@ export default withEnglishFallback({mcpDescription: "内蔵AIアシスタントに加えて、Claude Code、Cursor、その他のコーディングエージェントをMCP経由でデータベースクエリに使用できます。",mcpLearnMore: "詳細を見る",},+ backendErrors: {+ jdbc: {+ connectionFailed: "操作開始前にデータベース接続に失敗しました(段階: {stage})。",+ connectionInterrupted: "操作中にデータベース接続が中断されました(段階: {stage})。",+ operationTimedOut: "データベース操作がタイムアウトしました(段階: {stage})。",+ operationCanceled: "データベース操作をキャンセルしました(段階: {stage})。",+ busyRetryLater: "データベース Agent が混雑しています。後でもう一度お試しください(段階: {stage})。",+ runtimeReplaced: "データベース Agent ランタイムを置き換えました(段階: {stage})。",+ sqlFailed: "データベースが SQL エラーを返しました(段階: {stage})。",+ protocolFailed: "データベース Agent プロトコルに失敗しました。",+ contractInvalid: "データベース Agent が無効なエラー契約を返しました。",+ legacyFailure: "データベース Agent が分類できないエラーを返しました。",+ },+ legacy: "バックエンドがエラーを返しました。",+ unknown: "予期しないバックエンドエラーが発生しました。",+ },common: {fileNotFound: "ファイルが存在しません: {path}",language: "言語",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 153069f63c..e89cc65ebd 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1485,6 +1485,22 @@ export default withEnglishFallback({mcpDescription: "내장된 AI 어시스턴트 외에도 Claude Code, Cursor 등의 코딩 에이전트를 MCP로 연결하여 데이터베이스를 쿼리할 수 있습니다.",mcpLearnMore: "더 알아보기",},+ backendErrors: {+ jdbc: {+ connectionFailed: "작업 시작 전에 데이터베이스 연결에 실패했습니다(단계: {stage}).",+ connectionInterrupted: "작업 중 데이터베이스 연결이 중단되었습니다(단계: {stage}).",+ operationTimedOut: "데이터베이스 작업 시간이 초과되었습니다(단계: {stage}).",+ operationCanceled: "데이터베이스 작업이 취소되었습니다(단계: {stage}).",+ busyRetryLater: "데이터베이스 Agent가 사용 중입니다. 나중에 다시 시도하세요(단계: {stage}).",+ runtimeReplaced: "데이터베이스 Agent 런타임이 교체되었습니다(단계: {stage}).",+ sqlFailed: "데이터베이스에서 SQL 오류를 반환했습니다(단계: {stage}).",+ protocolFailed: "데이터베이스 Agent 프로토콜에 실패했습니다.",+ contractInvalid: "데이터베이스 Agent가 잘못된 오류 계약을 반환했습니다.",+ legacyFailure: "데이터베이스 Agent가 분류되지 않은 오류를 반환했습니다.",+ },+ legacy: "백엔드에서 오류를 반환했습니다.",+ unknown: "예상하지 못한 백엔드 오류가 발생했습니다.",+ },common: {fileNotFound: "파일이 존재하지 않습니다: {path}",language: "언어",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex d982b32b07..e8ba177ea9 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1459,6 +1459,22 @@ export default withEnglishFallback({mcpDescription: "Além do assistente de IA integrado, você também pode usar Claude Code, Cursor e outros agentes de codificação para consultar seus bancos de dados via MCP.",mcpLearnMore: "Saiba mais",},+ backendErrors: {+ jdbc: {+ connectionFailed: "A conexão com o banco falhou antes do início da operação (etapa: {stage}).",+ connectionInterrupted: "A conexão com o banco foi interrompida durante a operação (etapa: {stage}).",+ operationTimedOut: "A operação do banco excedeu o tempo limite (etapa: {stage}).",+ operationCanceled: "A operação do banco foi cancelada (etapa: {stage}).",+ busyRetryLater: "O Agent do banco está ocupado; tente novamente mais tarde (etapa: {stage}).",+ runtimeReplaced: "O runtime do Agent do banco foi substituído (etapa: {stage}).",+ sqlFailed: "O banco retornou um erro SQL (etapa: {stage}).",+ protocolFailed: "O protocolo do Agent do banco falhou.",+ contractInvalid: "O Agent do banco retornou um contrato de erro inválido.",+ legacyFailure: "O Agent do banco retornou um erro não classificado.",+ },+ legacy: "O backend retornou um erro.",+ unknown: "Ocorreu um erro inesperado no backend.",+ },common: {fileNotFound: "O arquivo não existe: {path}",language: "Idioma",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 221ea2e1fb..de872dfbc4 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1518,6 +1518,22 @@ export default withEnglishFallback({mcpDescription: "除了内置 AI 助手,还可以通过 MCP 让 Claude Code、Cursor 等编程助手直接使用这里的数据库连接。",mcpLearnMore: "了解更多",},+ backendErrors: {+ jdbc: {+ connectionFailed: "数据库连接在操作开始前失败(阶段:{stage})。",+ connectionInterrupted: "数据库连接在操作执行期间中断(阶段:{stage})。",+ operationTimedOut: "数据库操作超时(阶段:{stage})。",+ operationCanceled: "数据库操作已取消(阶段:{stage})。",+ busyRetryLater: "数据库 Agent 忙碌,请稍后重试(阶段:{stage})。",+ runtimeReplaced: "数据库 Agent 运行时已替换(阶段:{stage})。",+ sqlFailed: "数据库返回了 SQL 错误(阶段:{stage})。",+ protocolFailed: "数据库 Agent 协议失败。",+ contractInvalid: "数据库 Agent 返回了无效的错误契约。",+ legacyFailure: "数据库 Agent 返回了未分类错误。",+ },+ legacy: "后端返回了错误。",+ unknown: "发生了未预期的后端错误。",+ },common: {fileNotFound: "文件不存在:{path}",language: "语言",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex d3c063f050..a890e1f48f 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1458,6 +1458,22 @@ export default withEnglishFallback({mcpDescription: "除了內建 AI 助理,也可以藉由 MCP 讓 Claude Code、Cursor 等程式設計助理查詢你的資料庫。",mcpLearnMore: "了解更多",},+ backendErrors: {+ jdbc: {+ connectionFailed: "資料庫連線在操作開始前失敗(階段:{stage})。",+ connectionInterrupted: "資料庫連線在操作執行期間中斷(階段:{stage})。",+ operationTimedOut: "資料庫操作逾時(階段:{stage})。",+ operationCanceled: "資料庫操作已取消(階段:{stage})。",+ busyRetryLater: "資料庫 Agent 忙碌,請稍後再試(階段:{stage})。",+ runtimeReplaced: "資料庫 Agent 執行環境已替換(階段:{stage})。",+ sqlFailed: "資料庫回傳了 SQL 錯誤(階段:{stage})。",+ protocolFailed: "資料庫 Agent 通訊協定失敗。",+ contractInvalid: "資料庫 Agent 回傳了無效的錯誤契約。",+ legacyFailure: "資料庫 Agent 回傳了未分類錯誤。",+ },+ legacy: "後端回傳了錯誤。",+ unknown: "發生未預期的後端錯誤。",+ },common: {fileNotFound: "檔案不存在:{path}",language: "語言",diff --git a/apps/desktop/src/lib/__tests__/query/queryResultError.spec.ts b/apps/desktop/src/lib/__tests__/query/queryResultError.spec.tsindex a7497ff06f..3e5b830a0b 100644--- a/apps/desktop/src/lib/__tests__/query/queryResultError.spec.ts+++ b/apps/desktop/src/lib/__tests__/query/queryResultError.spec.ts@@ -14,29 +14,30 @@ function dataResult(columns: string[]): QueryResult {describe("isNoSnapshotErrorResult", () => {it("matches the StarRocks Paimon no-snapshot error surfaced via executeTabSql", () => {- const result = errorResult("Server error: `ERROR HY000 (1064): There is currently no snapshot.`");+ const result = { ...errorResult("Server error: `ERROR HY000 (1064): There is currently no snapshot.`"), execution_error: true as const };expect(isNoSnapshotErrorResult(result)).toBe(true);});it("matches case-insensitively", () => {- const result = errorResult("there IS currently NO snapshot");+ const result = { ...errorResult("there IS currently NO snapshot"), execution_error: true as const };expect(isNoSnapshotErrorResult(result)).toBe(true);});it("does not match unrelated query errors", () => {- expect(isNoSnapshotErrorResult(errorResult("Unknown table 'tag_test.record_tag_t'"))).toBe(false);- expect(isNoSnapshotErrorResult(errorResult("ERROR 1142: SELECT command denied"))).toBe(false);+ expect(isNoSnapshotErrorResult({ ...errorResult("Unknown table 'tag_test.record_tag_t'"), execution_error: true })).toBe(false);+ expect(isNoSnapshotErrorResult({ ...errorResult("ERROR 1142: SELECT command denied"), execution_error: true })).toBe(false);});it("does not match successful data results", () => {expect(isNoSnapshotErrorResult(dataResult(["id", "name"]))).toBe(false);expect(isNoSnapshotErrorResult(dataResult(["Error"]))).toBe(false); // data column literally named Error, no rows+ expect(isNoSnapshotErrorResult({ ...errorResult("There is currently no snapshot."), rows: [["There is currently no snapshot."]] })).toBe(false);});it("returns false for missing or empty results", () => {expect(isNoSnapshotErrorResult(undefined)).toBe(false);expect(isNoSnapshotErrorResult(null)).toBe(false);- expect(isNoSnapshotErrorResult({ ...errorResult("There is currently no snapshot."), rows: [] })).toBe(false);+ expect(isNoSnapshotErrorResult({ ...errorResult("There is currently no snapshot."), execution_error: true, rows: [] })).toBe(false);});});diff --git a/apps/desktop/src/lib/__tests__/query/sqlserverExplainPlan.spec.ts b/apps/desktop/src/lib/__tests__/query/sqlserverExplainPlan.spec.tsindex 59bdfe2678..ba44d8bad6 100644--- a/apps/desktop/src/lib/__tests__/query/sqlserverExplainPlan.spec.ts+++ b/apps/desktop/src/lib/__tests__/query/sqlserverExplainPlan.spec.ts@@ -60,11 +60,17 @@ describe("SQL Server explain plan", () => {});it("surfaces a SQL Server batch error instead of treating it as a plan", () => {- expect(sqlServerExplainResult([result(["Error"], [["Invalid object name 'missing_table'"]])])).toEqual({+ expect(sqlServerExplainResult([{ ...result(["Error"], [["Invalid object name 'missing_table'"]]), execution_error: true }])).toEqual({error: "Invalid object name 'missing_table'",});});+ it("does not mistake a successful Error column for a SQL Server batch failure", () => {+ expect(sqlServerExplainResult([result(["Error"], [["valid query value"]])])).toEqual({+ error: "SQL Server did not return ShowPlan XML",+ });+ });+it("rejects malformed SHOWPLAN XML", () => {const malformed = result(["Microsoft SQL Server 2005 XML Showplan"], [["<ShowPlanXML><RelOp></ShowPlanXML>"]]);diff --git a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.tsindex bfb43e0abe..2e09e381b0 100644--- a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts+++ b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { createPinia, setActivePinia } from "pinia";import { useConnectionStore } from "@/stores/connectionStore";-import { connectionGroupDisplayName, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultSourceRange, statementExecutionMarkers, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";+import { connectionGroupDisplayName, executionSummaryItems, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultSourceRange, statementExecutionMarkers, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";import type { ConnectionConfig, QueryTab } from "@/types/database";@@ -224,6 +224,18 @@ describe("query result source ranges", () => {});});+describe("execution summary", () => {+ it("uses the explicit execution marker instead of the result column name", () => {+ const successfulAlias = { columns: ["Error"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 };+ const markedFailure = { columns: ["Error"], rows: [["failed"]], affected_rows: 0, execution_time_ms: 1, execution_error: true as const };++ expect(executionSummaryItems({ results: [successfulAlias, markedFailure] }).map(({ status, isError }) => ({ status, isError }))).toEqual([+ { status: "success", isError: false },+ { status: "error", isError: true },+ ]);+ });+});+describe("statement execution markers", () => {it("renders a live marker for a single statement", () => {const sql = "SELECT 1";diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.tsindex 9d32f15197..fa265c4e4d 100644--- a/apps/desktop/src/lib/ai/ai.ts+++ b/apps/desktop/src/lib/ai/ai.ts@@ -9,6 +9,7 @@ import { aiSkillForAction } from "@/lib/ai/aiSkills";import { isSchemaAware } from "@/lib/database/databaseCapabilities";import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import type { AgentEvent } from "@/lib/backend/tauri";@@ -674,12 +675,12 @@ function prioritizeSchemas(schemas: string[]): string[] {}function extractLastError(result?: QueryResult): string | undefined {- if (!result?.columns.includes("Error")) return undefined;+ if (!result || !isQueryExecutionErrorResult(result)) return undefined;return result.rows[0]?.[0] == null ? undefined : String(result.rows[0][0]);}function formatResultPreview(result?: QueryResult): string | undefined {- if (!result || result.columns.includes("Error") || !result.rows.length) return undefined;+ if (!result || isQueryExecutionErrorResult(result) || !result.rows.length) return undefined;const MAX_VALUE_CHARS = 200;const rows = result.rows.slice(0, 5).map((row) => {return result.columnsdiff --git a/apps/desktop/src/lib/backend/errorUtils.ts b/apps/desktop/src/lib/backend/errorUtils.tsindex bec50ff524..4a0e0a9cea 100644--- a/apps/desktop/src/lib/backend/errorUtils.ts+++ b/apps/desktop/src/lib/backend/errorUtils.ts@@ -2,6 +2,87 @@* Utility functions for consistent error handling across the application.*/+export type BackendErrorParam = string | number | boolean;++export interface BackendError {+ version: 1;+ code: string;+ messageKey: string;+ messageParams: Record<string, BackendErrorParam>;+ source: "jdbcAgent" | "jdbcAgentLegacy" | "legacyBackend";+ operationOutcome: "not_started" | "unknown";+ detail?: string;+ diagnostics?: Record<string, unknown>;+ helpUrl?: string;+}++function isBackendError(value: unknown): value is BackendError {+ if (!value || typeof value !== "object") return false;+ const candidate = value as Record<string, unknown>;+ if (+ candidate.version !== 1 ||+ typeof candidate.code !== "string" ||+ !/^DBX-[A-Z][A-Z0-9]*-\d{4}$/.test(candidate.code) ||+ typeof candidate.messageKey !== "string" ||+ !candidate.messageKey.startsWith("backendErrors.") ||+ !candidate.messageParams ||+ typeof candidate.messageParams !== "object" ||+ Array.isArray(candidate.messageParams) ||+ !["jdbcAgent", "jdbcAgentLegacy", "legacyBackend"].includes(String(candidate.source)) ||+ !["not_started", "unknown"].includes(String(candidate.operationOutcome))+ ) {+ return false;+ }+ if (candidate.detail !== undefined && typeof candidate.detail !== "string") return false;+ return Object.values(candidate.messageParams).every((param) => typeof param === "string" || typeof param === "boolean" || (typeof param === "number" && Number.isFinite(param)));+}++export function normalizeBackendError(error: unknown): BackendError | null {+ if (error instanceof BackendErrorException) return error.backendError;+ if (isBackendError(error)) return error;+ if (error && typeof error === "object" && "backendError" in error) {+ const backendError = (error as { backendError: unknown }).backendError;+ if (isBackendError(backendError)) return backendError;+ }+ if (error && typeof error === "object" && "error" in error) {+ const nested = (error as { error: unknown }).error;+ if (isBackendError(nested)) return nested;+ }+ return null;+}++export class BackendErrorException extends Error {+ readonly backendError: BackendError;++ constructor(error: unknown) {+ const backendError = normalizeRawBackendError(error);+ const fallbackMessage = typeof error === "string" ? error : error instanceof Error ? error.message : "Backend request failed";+ super(backendError?.detail || fallbackMessage);+ this.name = "BackendErrorException";+ this.backendError = backendError ?? {+ version: 1,+ code: "DBX-LEGACY-0001",+ messageKey: "backendErrors.legacy",+ messageParams: {},+ source: "legacyBackend",+ operationOutcome: "unknown",+ detail: fallbackMessage,+ };+ }+}++function normalizeRawBackendError(error: unknown): BackendError | null {+ if (typeof error === "string") {+ try {+ const parsed: unknown = JSON.parse(error);+ return normalizeBackendError(parsed);+ } catch {+ return null;+ }+ }+ return normalizeBackendError(error);+}+/*** Formats an unknown error value into a human-readable string.* Handles Error objects, strings, null/undefined, and other types.@@ -17,6 +98,9 @@* }*/export function formatError(e: unknown): string {+ const backendError = normalizeBackendError(e);+ if (backendError?.detail) return backendError.detail;+if (e instanceof Error) {return e.message;}diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 17d27108de..299994399b 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -45,6 +45,7 @@ import type {TunnelProfile,} from "@/types/database";import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";+import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";import type { CollectionInfo } from "@/types/database";import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";@@ -223,19 +224,19 @@ async function post<T>(url: string, body: unknown): Promise<T> {headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});- if (!res.ok) throw new Error(await res.text());+ if (!res.ok) throw await backendResponseError(res);return res.json();}async function get<T>(url: string): Promise<T> {const res = await fetch(apiUrl(url));- if (!res.ok) throw new Error(await res.text());+ if (!res.ok) throw await backendResponseError(res);return res.json();}async function del<T>(url: string): Promise<T> {const res = await fetch(apiUrl(url), { method: "DELETE" });- if (!res.ok) throw new Error(await res.text());+ if (!res.ok) throw await backendResponseError(res);return res.json();}@@ -245,10 +246,21 @@ async function put<T>(url: string, body: unknown): Promise<T> {headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});- if (!res.ok) throw new Error(await res.text());+ if (!res.ok) throw await backendResponseError(res);return res.json();}+async function backendResponseError(response: Response): Promise<BackendErrorException> {+ const text = await response.text();+ let payload: unknown = text;+ try {+ payload = JSON.parse(text);+ } catch {+ // Preserve legacy plain-text responses at the same compatibility boundary.+ }+ return new BackendErrorException(payload);+}+function qs(params: Record<string, string | number | boolean | undefined>): string {const sp = new URLSearchParams();for (const [k, v] of Object.entries(params)) {@@ -880,7 +892,7 @@ export interface ExecuteMultiProgress {success: boolean;executionTimeMs: number;affectedRows: number;- error?: string;+ error?: BackendError;}export async function executeMultiWithProgress(@@ -918,7 +930,7 @@ export async function executeMultiWithProgress(success,executionTimeMs: result.execution_time_ms,affectedRows: result.affected_rows,- error: success ? undefined : String(result.rows[0]?.[0] ?? ""),+ error: success ? undefined : result.error,});});return results;diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex ab53e0db4f..bbada00975 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -1,4 +1,5 @@import { invoke } from "@tauri-apps/api/core";+import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";import { listen, type UnlistenFn } from "@tauri-apps/api/event";import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";import { ExternalSqlFileTooLargeError } from "@/lib/sql/sqlFileOpen";@@ -1060,14 +1061,18 @@ export async function executeQuery(executionMode?: "simple";},): Promise<QueryResult> {- return invoke("execute_query", {- connectionId,- database,- sql,- schema,- executionId,- ...options,- });+ try {+ return await invoke("execute_query", {+ connectionId,+ database,+ sql,+ schema,+ executionId,+ ...options,+ });+ } catch (error) {+ throw new BackendErrorException(error);+ }}export async function executeMulti(@@ -1089,14 +1094,18 @@ export async function executeMulti(executionMode?: "simple";},): Promise<QueryResult[]> {- return invoke("execute_multi", {- connectionId,- database,- sql,- schema,- executionId,- ...options,- });+ try {+ return await invoke("execute_multi", {+ connectionId,+ database,+ sql,+ schema,+ executionId,+ ...options,+ });+ } catch (error) {+ throw new BackendErrorException(error);+ }}export interface ExecuteMultiProgress {@@ -1107,7 +1116,7 @@ export interface ExecuteMultiProgress {success: boolean;executionTimeMs: number;affectedRows: number;- error?: string;+ error?: BackendError;}export async function executeMultiWithProgress(@@ -1137,6 +1146,8 @@ export async function executeMultiWithProgress(});try {return await invoke("execute_multi", { connectionId, database, sql, schema, executionId, ...invokeOptions });+ } catch (error) {+ throw new BackendErrorException(error);} finally {unlisten();}diff --git a/apps/desktop/src/lib/diagram/explainPlan.ts b/apps/desktop/src/lib/diagram/explainPlan.tsindex 96941715ea..4c72ba4bc6 100644--- a/apps/desktop/src/lib/diagram/explainPlan.ts+++ b/apps/desktop/src/lib/diagram/explainPlan.ts@@ -1,6 +1,7 @@import type { DatabaseType, QueryResult } from "@/types/database";import * as api from "@/lib/backend/api";import { supportsDatabaseFeature } from "@/lib/database/databaseDriverManifest";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";export interface ExplainPlanNode {id: string;@@ -376,7 +377,7 @@ export function flattenExplainPlanNodes(nodes: ExplainPlanNode[]): ExplainPlanNo}export function sqlServerExplainResult(results: QueryResult[]): { result?: QueryResult; error?: string } {- const errorResult = results.find((result) => result.columns.length === 1 && result.columns[0] === "Error" && result.rows.length > 0);+ const errorResult = results.find((result) => isQueryExecutionErrorResult(result) && result.rows.length > 0);if (errorResult) return { error: String(errorResult.rows[0]?.[0] ?? "") };const result = results.find((candidate) => firstSqlServerShowplanXml(candidate) !== undefined);diff --git a/apps/desktop/src/lib/query/queryResultError.ts b/apps/desktop/src/lib/query/queryResultError.tsindex fda218c2ba..edf938059f 100644--- a/apps/desktop/src/lib/query/queryResultError.ts+++ b/apps/desktop/src/lib/query/queryResultError.ts@@ -25,6 +25,6 @@ export function isQueryExecutionErrorResult(result: QueryResult): boolean {}export function isNoSnapshotErrorResult(result: QueryResult | undefined | null): boolean {- if (!result || !result.columns.includes("Error") || result.rows.length === 0) return false;+ if (!result || !isQueryExecutionErrorResult(result) || result.rows.length === 0) return false;return NO_SNAPSHOT_ERROR_PATTERN.test(String(result.rows[0]?.[0] ?? ""));}diff --git a/apps/desktop/src/lib/tabs/dataTabActivation.ts b/apps/desktop/src/lib/tabs/dataTabActivation.tsindex 0284497c98..131728bfbf 100644--- a/apps/desktop/src/lib/tabs/dataTabActivation.ts+++ b/apps/desktop/src/lib/tabs/dataTabActivation.ts@@ -1,14 +1,11 @@-import type { QueryResult, QueryTab } from "@/types/database";+import type { QueryTab } from "@/types/database";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";export type DataTableDoubleClickAction = "activate" | "open" | "none";-function isErrorResult(result: QueryResult | undefined): boolean {- return result?.columns.length === 1 && result.columns[0] === "Error";-}-export function canActivateExistingDataTableTab(tab: QueryTab, options: { activateExecuting?: boolean } = {}): boolean {if (tab.isExecuting) return options.activateExecuting !== false;- if (isErrorResult(tab.result)) return false;+ if (tab.result && isQueryExecutionErrorResult(tab.result)) return false;return !!tab.result || !!tab.results?.length;}diff --git a/apps/desktop/src/lib/tabs/tabPresentation.ts b/apps/desktop/src/lib/tabs/tabPresentation.tsindex 80b36cd2b9..1192df877b 100644--- a/apps/desktop/src/lib/tabs/tabPresentation.ts+++ b/apps/desktop/src/lib/tabs/tabPresentation.ts@@ -4,6 +4,7 @@ import { findConnectionGroupPath } from "@/lib/sidebar/sidebarLayout";import { splitMongoCommandRanges } from "@/lib/mongo/mongoShellCommand";import { executableStatementRanges, splitSqlStatementRanges, type SqlTextRange } from "@/lib/sql/sqlStatementRanges";import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import type { BatchSqlExecution, ConnectionConfig, DatabaseType, QueryResult, QueryTab } from "@/types/database";type Translate = (key: string, params?: Record<string, unknown>) => string;@@ -378,7 +379,7 @@ export function executionSummaryItems(tab: Pick<QueryTab, "result" | "results" |});}return results.map((result, index) => {- const isError = result.execution_error === true || result.columns.includes("Error");+ const isError = isQueryExecutionErrorResult(result);return {result,index,diff --git a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.tsindex ac6b52796d..20ef0ca226 100644--- a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts@@ -76,6 +76,17 @@ function deferred<T>() {return { promise, resolve, reject };}+function structuredTimeoutError() {+ return {+ version: 1 as const,+ code: "DBX-JDBC-2002",+ messageKey: "backendErrors.jdbc.operationTimedOut",+ messageParams: { stage: "execute" },+ source: "jdbcAgent" as const,+ operationOutcome: "unknown" as const,+ };+}+describe("queryStore multi-statement errors", () => {beforeEach(() => {vi.clearAllMocks();@@ -115,7 +126,7 @@ describe("queryStore multi-statement errors", () => {success,executionTimeMs: result.execution_time_ms,affectedRows: result.affected_rows,- error: success ? undefined : String(result.rows[0]?.[0] ?? ""),+ error: success ? undefined : result.error,});});return results;@@ -123,9 +134,10 @@ describe("queryStore multi-statement errors", () => {});it("opens the first error result from a mixed result batch", async () => {+ const structuredError = structuredTimeoutError();mocks.executeMulti.mockResolvedValue([{ columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 },- { columns: ["Error"], execution_error: true, rows: [["no such table: missing"]], affected_rows: 0, execution_time_ms: 1 },+ { columns: ["Error"], execution_error: true, error: structuredError, rows: [["no such table: missing"]], affected_rows: 0, execution_time_ms: 1 },]);const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();@@ -136,6 +148,10 @@ describe("queryStore multi-statement errors", () => {const tab = store.tabs.find((item) => item.id === tabId)!;expect(tab.activeResultIndex).toBe(1);expect(tab.result?.columns).toEqual(["Error"]);+ expect(tab.result?.error).toEqual(structuredError);+ expect(tab.batchSqlExecution?.items[1]?.errorDetails).toEqual(structuredError);+ expect(tab.batchSqlExecution?.items[1]?.error).not.toBe(structuredError.code);+ expect(tab.batchSqlExecution?.items[1]?.error).not.toBe("[object Object]");});it("updates live per-statement progress before the batch promise resolves", async () => {@@ -195,6 +211,24 @@ describe("queryStore multi-statement errors", () => {});});+ it("preserves a structured top-level batch failure", async () => {+ const structuredError = structuredTimeoutError();+ mocks.executeMultiWithProgress.mockRejectedValueOnce(structuredError);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("mysql-1", "app", "Query", "query", undefined, "SELECT 1;\nSELECT 2");++ await store.executeTabSql(tabId, "SELECT 1;\nSELECT 2");++ const tab = store.tabs.find((item) => item.id === tabId)!;+ expect(tab.result?.error).toEqual(structuredError);+ expect(tab.result?.rows[0]?.[0]).toEqual(expect.any(String));+ expect(tab.result?.rows[0]?.[0]).not.toBe(structuredError.code);+ expect(tab.result?.rows[0]?.[0]).not.toBe("[object Object]");+ expect(tab.batchSqlExecution?.items[0]?.errorDetails).toEqual(structuredError);+ expect(tab.batchSqlExecution?.items[0]?.error).toBe(tab.result?.rows[0]?.[0]);+ });+it("keeps completed progress and records a later top-level batch failure", async () => {mocks.executeMultiWithProgress.mockImplementationOnce((_connectionId, _database, _sql, onProgress, _schema, options) => {onProgress({@@ -359,7 +393,7 @@ describe("queryStore multi-statement errors", () => {database: "FooDB",query_timeout_secs: 30,});- mocks.executeMulti.mockResolvedValueOnce([{ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 }]).mockResolvedValueOnce([{ columns: ["Error"], rows: [["Database does not exist"]], affected_rows: 0, execution_time_ms: 1 }]);+ mocks.executeMulti.mockResolvedValueOnce([{ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 }]).mockResolvedValueOnce([{ columns: ["Error"], rows: [["Database does not exist"]], affected_rows: 0, execution_time_ms: 1, execution_error: true }]);const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();const tabA = store.createTab("sqlserver-1", "FooDB", "Tab A", "query", "dbo");diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 666ad5e6b7..23142c8f5f 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -61,7 +61,7 @@ import { useSavedSqlStore } from "@/stores/savedSqlStore";import { useExportTracker } from "@/composables/useExportTracker";import { recordQueryCancellationLatency, resourceLifecycleDiagnostics } from "@/lib/diagnostics/resourceLifecycleDiagnostics";import { appendDebugLog } from "@/lib/backend/debugLog";-import { formatError } from "@/lib/backend/errorUtils";+import { formatError, normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget";@@ -278,7 +278,7 @@ function applyBatchSqlProgress(success: boolean;executionTimeMs: number;affectedRows: number;- error?: string;+ error?: BackendError;},continueOnError: boolean,) {@@ -289,7 +289,8 @@ function applyBatchSqlProgress(item.status = progress.success ? "success" : "error";item.executionTimeMs = progress.executionTimeMs;item.affectedRows = progress.affectedRows;- item.error = progress.error;+ item.errorDetails = progress.error;+ item.error = progress.error ? translateBackendError(i18n.global.t, progress.error) : undefined;batch.completed = Math.max(batch.completed, progress.completed);if ((progress.success || continueOnError) && progress.completed < batch.total) {const next = batch.items[progress.statementIndex + 1];@@ -310,7 +311,8 @@ function reconcileBatchSqlResults(tab: QueryTab, executionId: string, results: Qitem.status = failed ? "error" : "success";item.executionTimeMs = result.execution_time_ms;item.affectedRows = result.affected_rows;- item.error = failed ? String(result.rows[0]?.[0] ?? "") : undefined;+ item.errorDetails = failed ? result.error : undefined;+ item.error = failed ? (result.error ? translateBackendError(i18n.global.t, result.error) : String(result.rows[0]?.[0] ?? "")) : undefined;}batch.completed = batch.items.filter((item) => item.status === "success" || item.status === "error").length;}@@ -321,7 +323,8 @@ function failBatchSqlExecution(tab: QueryTab, executionId: string, error: unknowconst item = batch.items.find((candidate) => candidate.status === "running") ?? batch.items.find((candidate) => candidate.status === "pending");if (!item) return;item.status = cancelled ? "cancelled" : "error";- item.error = cancelled ? undefined : error instanceof Error ? error.message : String(error);+ item.errorDetails = cancelled ? undefined : (normalizeBackendError(error) ?? undefined);+ item.error = cancelled ? undefined : translateBackendError(i18n.global.t, error);batch.completed = batch.items.filter((candidate) => candidate.status === "success" || candidate.status === "error").length;}@@ -329,7 +332,7 @@ function finishBatchSqlExecution(tab: QueryTab, executionId: string, cancelled:const batch = batchSqlExecutionFor(tab, executionId);if (!batch) return;if (cancelled) {- const cancelledError = [...batch.items].reverse().find((item) => item.status === "error" && /cancel|取消/i.test(item.error ?? ""));+ const cancelledError = [...batch.items].reverse().find((item) => item.status === "error" && (item.errorDetails?.code === "DBX-JDBC-2003" || /cancel|取消/i.test(item.error ?? "")));if (cancelledError) {cancelledError.status = "cancelled";cancelledError.error = undefined;@@ -384,9 +387,7 @@ function sqlServerUseDatabaseFromStatement(statement: string | undefined): strin}function isSqlServerBatchErrorResult(result: QueryResult): boolean {- // SQL Server batch errors can arrive without execution_error metadata.- // A standalone USE statement cannot legitimately return an Error column.- return result.execution_error === true || (result.columns.length === 1 && result.columns[0] === "Error" && result.rows.length > 0);+ return result.execution_error === true;}function sapHanaCurrentSchemaFromResult(result: QueryResult): string | undefined {@@ -2717,13 +2718,14 @@ export const useQueryStore = defineStore("query", () => {}function toErrorResult(e: any): NonNullable<QueryTab["result"]> {- const raw = e instanceof Error ? e.message : String(e);// Single funnel for every query execution failure, so backend messages DBX// knows about are shown in the active locale rather than as raw English.- const message = translateBackendError(i18n.global.t, raw);+ const error = normalizeBackendError(e) ?? undefined;+ const message = translateBackendError(i18n.global.t, e);return markQueryResultRowsRaw({columns: ["Error"],execution_error: true,+ error,rows: [[message]],affected_rows: 0,execution_time_ms: 0,@@ -3422,7 +3424,7 @@ export const useQueryStore = defineStore("query", () => {connStore.invalidateCompletionCache(tab.connectionId, String(currentDb));}} catch (e: any) {- allResults.push(annotateQueryResultSource({ columns: ["Error"], rows: [[e?.message ?? String(e)]], affected_rows: 0, execution_time_ms: 0 }, command, undefined, undefined, sourceRange));+ allResults.push(annotateQueryResultSource(toErrorResult(e), command, undefined, undefined, sourceRange));}}queryExecutionLog("info", "redis:done", { traceId, commandCount: commands.length, elapsed: elapsed() });@@ -3431,7 +3433,7 @@ export const useQueryStore = defineStore("query", () => {if (current?.executionId === executionId) {if (openInNewResultTab && current.isCancelling && restorePendingResultRun(current, executionId)) return false;if (allResults.length > 1) {- const activeResultIndex = allResults.findIndex((r) => !r.columns.includes("Error"));+ const activeResultIndex = allResults.findIndex((result) => !isQueryExecutionErrorResult(result));const resultIndex = preservedResultIndex(allResults, current.activeResultIndex, options?.preserveActiveResultIndex) ?? (activeResultIndex >= 0 ? activeResultIndex : 0);current.results = allResults;current.activeResultIndex = resultIndex;@@ -3770,7 +3772,7 @@ export const useQueryStore = defineStore("query", () => {} else if (allResults.length > 1) {// Open grouped output on the first non-error result when possible so// mixed success/error batches land on the most useful table first.- const activeResultIndex = allResults.findIndex((result) => !result.columns.includes("Error"));+ const activeResultIndex = allResults.findIndex((result) => !isQueryExecutionErrorResult(result));const resultIndex = preservedResultIndex(allResults, current.activeResultIndex, options?.preserveActiveResultIndex) ?? (activeResultIndex >= 0 ? activeResultIndex : 0);current.results = allResults;current.activeResultIndex = resultIndex;@@ -3839,7 +3841,7 @@ export const useQueryStore = defineStore("query", () => {if (current?.executionId === executionId && openInNewResultTab && current.isCancelling && restorePendingResultRun(current, executionId)) return false;if (current?.executionId === executionId && allResults.length > 0) {clearResultNavigationState(current);- const errorResultIndex = allResults.findIndex((result) => result.columns.includes("Error") || elasticsearchHttpErrorStatus(result) !== undefined);+ const errorResultIndex = allResults.findIndex((result) => isQueryExecutionErrorResult(result) || elasticsearchHttpErrorStatus(result) !== undefined);const resultIndex = errorResultIndex >= 0 ? errorResultIndex : 0;current.results = allResults.length > 1 ? allResults : undefined;current.activeResultIndex = allResults.length > 1 ? resultIndex : undefined;diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 8cb4f7e601..399bd34d4f 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -1,3 +1,5 @@+import type { BackendError } from "@/lib/backend/errorUtils";+export type DatabaseType =| "mysql"| "postgres"@@ -574,6 +576,8 @@ export interface QueryResult {appended_from_row_count?: number;/** Set for synthesized query execution failures. */execution_error?: true;+ /** Structured backend error; authoritative when execution_error is true. */+ error?: BackendError;/** Zero-based index of the submitted statement that produced this result. */statement_index?: number;/** Internal row identifiers appended to editable query results. */@@ -630,6 +634,7 @@ export interface BatchStatementExecutionItem {executionTimeMs?: number;affectedRows?: number;error?: string;+ errorDetails?: BackendError;}export interface BatchSqlExecution {diff --git a/crates/dbx-core/assets/agent-protocol-v2.json b/crates/dbx-core/assets/agent-protocol-v2.jsonindex 8764572baa..bc282be4a9 100644--- a/crates/dbx-core/assets/agent-protocol-v2.json+++ b/crates/dbx-core/assets/agent-protocol-v2.json@@ -2,9 +2,9 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "multi_session"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "multi_session", "structured_error_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],- "defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],+ "defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": ["handshake","connect",diff --git a/crates/dbx-core/src/agent_recovery.rs b/crates/dbx-core/src/agent_recovery.rsnew file mode 100644index 0000000000..6562357d5c--- /dev/null+++ b/crates/dbx-core/src/agent_recovery.rs@@ -0,0 +1,87 @@+//! Recovery decisions derived from typed JDBC Agent failures.++use crate::db::agent_driver::{AgentCallError, AgentErrorCategory, AgentSessionDisposition};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RecoveryScope {+ UserOperation,+ ReadOnlyMetadata { retried: bool },+ Keepalive,+ ConnectionOpen,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RecoveryDecision {+ KeepSession,+ RetryReadOnlyMetadata,+ QuarantineSession,+ ReplaceRuntime,+}++impl RecoveryDecision {+ pub fn discards_session(self) -> bool {+ !matches!(self, Self::KeepSession)+ }++ pub fn replaces_runtime(self) -> bool {+ matches!(self, Self::ReplaceRuntime)+ }+}++pub struct RecoveryPolicy;++impl RecoveryPolicy {+ pub fn decide(error: &AgentCallError, scope: RecoveryScope) -> RecoveryDecision {+ match error {+ AgentCallError::ContractViolation { .. } => RecoveryDecision::QuarantineSession,+ AgentCallError::Transport { .. } => RecoveryDecision::ReplaceRuntime,+ AgentCallError::Timeout { .. } | AgentCallError::Canceled { .. } => RecoveryDecision::QuarantineSession,+ AgentCallError::Structured { context, .. } => {+ if matches!(context.category, AgentErrorCategory::Timeout | AgentErrorCategory::Canceled) {+ return RecoveryDecision::QuarantineSession;+ }+ Self::from_disposition(Some(context.session_disposition), Some(context.category), scope)+ }+ AgentCallError::Legacy { hints, .. } => {+ Self::from_disposition(hints.session_disposition, hints.category, scope)+ }+ }+ }++ fn from_disposition(+ disposition: Option<AgentSessionDisposition>,+ category: Option<AgentErrorCategory>,+ scope: RecoveryScope,+ ) -> RecoveryDecision {+ match disposition {+ Some(AgentSessionDisposition::ReplaceRuntime) => RecoveryDecision::ReplaceRuntime,+ Some(AgentSessionDisposition::Quarantine)+ if category == Some(AgentErrorCategory::Connection)+ && matches!(scope, RecoveryScope::ReadOnlyMetadata { retried: false }) =>+ {+ RecoveryDecision::RetryReadOnlyMetadata+ }+ Some(AgentSessionDisposition::Quarantine) => RecoveryDecision::QuarantineSession,+ Some(AgentSessionDisposition::Keep) | None => RecoveryDecision::KeepSession,+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn business_modules_do_not_consume_legacy_marker_fields() {+ let business_sources = [+ ("query.rs", include_str!("query.rs")),+ ("schema.rs", include_str!("schema.rs")),+ ("connection.rs", include_str!("connection.rs")),+ ];+ let retired_consumers = ["agent_rpc_error_category", "agent_rpc_error_session_id", "agent_session_disposition"];++ for (name, source) in business_sources {+ for consumer in retired_consumers {+ assert!(!source.contains(consumer), "{name} still consumes {consumer}");+ }+ }+ }+}diff --git a/crates/dbx-core/src/agent_runtime.rs b/crates/dbx-core/src/agent_runtime.rsindex 5e5d9154e0..e931d86f94 100644--- a/crates/dbx-core/src/agent_runtime.rs+++ b/crates/dbx-core/src/agent_runtime.rs@@ -2,10 +2,9 @@ use serde::de::DeserializeOwned;use std::time::Duration;use crate::agent_manager::{AgentManager, DEFAULT_JRE_KEY};+use crate::agent_recovery::{RecoveryPolicy, RecoveryScope};use crate::database_capabilities;-use crate::db::agent_driver::{- agent_session_disposition, AgentDriverClient, AgentMethod, AgentRuntimeClient, AgentSessionDisposition,-};+use crate::db::agent_driver::{AgentCallError, AgentDriverClient, AgentMethod, AgentRuntimeClient};use crate::models::connection::DatabaseType;pub struct SharedConnectionOpenError {@@ -113,7 +112,7 @@ pub async fn spawn_shared_connection_client(}};if let Err(err) = runtime- .call::<serde_json::Value>(AgentMethod::OpenSession.as_str(), session_params, Some(connect_timeout), None)+ .call_typed::<serde_json::Value>(AgentMethod::OpenSession.as_str(), session_params, Some(connect_timeout), None).await{let open_error = shared_connection_open_error(err, runtime.clone());@@ -124,12 +123,11 @@ pub async fn spawn_shared_connection_client(}fn shared_connection_open_error(- message: String,+ error: AgentCallError,runtime: std::sync::Arc<AgentRuntimeClient>,) -> SharedConnectionOpenError {- let runtime =- (agent_session_disposition(&message) == Some(AgentSessionDisposition::ReplaceRuntime)).then_some(runtime);- SharedConnectionOpenError { message, runtime }+ let runtime = RecoveryPolicy::decide(&error, RecoveryScope::ConnectionOpen).replaces_runtime().then_some(runtime);+ SharedConnectionOpenError { message: error.into_legacy_string(), runtime }}async fn forget_unused_runtime_after_failed_open(@@ -412,9 +410,17 @@ for line in sys.stdin:#[tokio::test]async fn replace_runtime_open_error_reports_runtime_without_killing_it_directly() {let (manager, _cell, runtime, script_path) = test_shared_runtime("replace-runtime-open-error").await;- let error = "Agent RPC error (-1): capacity exhausted\nDBX_AGENT_ERROR_DATA:{\"category\":\"resource\",\"sessionDisposition\":\"replace_runtime\"}";+ let error = AgentCallError::Legacy {+ rpc_code: Some(-1),+ message: "capacity exhausted".to_string(),+ hints: crate::db::agent_driver::LegacyAgentHints {+ category: Some(crate::db::agent_driver::AgentErrorCategory::Resource),+ session_disposition: Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime),+ ..Default::default()+ },+ };- let open_error = shared_connection_open_error(error.to_string(), runtime.clone());+ let open_error = shared_connection_open_error(error, runtime.clone());assert!(open_error.runtime.as_ref().is_some_and(|failed| std::sync::Arc::ptr_eq(failed, &runtime)));assert!(!runtime.is_failed());diff --git a/crates/dbx-core/src/backend_error.rs b/crates/dbx-core/src/backend_error.rsnew file mode 100644index 0000000000..20a160d4a4--- /dev/null+++ b/crates/dbx-core/src/backend_error.rs@@ -0,0 +1,803 @@+//! Stable, safe backend error envelopes and the v1 JDBC Agent catalog.++use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++use crate::db::agent_driver::{+ category_name, stage_name, valid_agent_error_combination, AgentCallError, AgentErrorCategory, AgentErrorContext,+ AgentErrorStage, AgentOperationOutcome, AgentSessionDisposition,+};++const MAX_DETAIL_BYTES: usize = 512;++/// The origin of a backend error as exposed on the wire.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum BackendErrorSource {+ JdbcAgent,+ JdbcAgentLegacy,+ LegacyBackend,+}++/// Whether the operation definitely had not started or its result is unknown.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum BackendOperationOutcome {+ NotStarted,+ Unknown,+}++/// Scalar values permitted in catalog-owned message parameters.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum BackendMessageParam {+ String(String),+ Integer(i64),+ Boolean(bool),+}++/// Allowlisted diagnostics safe for a public error envelope.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BackendErrorDiagnostics {+ #[serde(skip_serializing_if = "Option::is_none")]+ category: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ stage: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ sql_state: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ vendor_code: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ exception_class: Option<String>,+}++/// Public v1 backend error envelope.+///+/// The fields are private on purpose: callers create envelopes through the+/// catalog adapters, so code/messageKey/params cannot drift independently.+#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BackendError {+ version: u8,+ code: String,+ message_key: String,+ message_params: BTreeMap<String, BackendMessageParam>,+ source: BackendErrorSource,+ operation_outcome: BackendOperationOutcome,+ #[serde(skip_serializing_if = "Option::is_none")]+ detail: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ diagnostics: Option<BackendErrorDiagnostics>,+ #[serde(skip_serializing_if = "Option::is_none")]+ help_url: Option<String>,+}++impl BackendError {+ /// Convert a typed Agent error into the stable v1 JDBC catalog envelope.+ pub fn from_agent_call_error(error: &AgentCallError) -> Self {+ match error {+ AgentCallError::Structured { message, context, .. } => {+ let (entry, outcome) = structured_entry(context);+ Self::new(+ entry,+ BackendErrorSource::JdbcAgent,+ outcome,+ stage_param(entry, context.stage),+ safe_detail(message),+ Some(diagnostics_from_context(context)),+ )+ }+ AgentCallError::Legacy { message, .. } => Self::new(+ catalog_entry(CatalogCode::JdbcLegacyFailure),+ BackendErrorSource::JdbcAgentLegacy,+ BackendOperationOutcome::Unknown,+ BTreeMap::new(),+ safe_detail(message),+ None,+ ),+ AgentCallError::ContractViolation { message, .. } => Self::new(+ catalog_entry(CatalogCode::ContractInvalid),+ BackendErrorSource::JdbcAgent,+ BackendOperationOutcome::Unknown,+ BTreeMap::new(),+ safe_detail(message),+ None,+ ),+ AgentCallError::Transport { message } => Self::new(+ catalog_entry(CatalogCode::ProtocolFailed),+ BackendErrorSource::JdbcAgent,+ BackendOperationOutcome::Unknown,+ BTreeMap::new(),+ safe_detail(message),+ None,+ ),+ AgentCallError::Timeout { stage, operation_outcome } => {+ let entry = catalog_entry(match operation_outcome {+ AgentOperationOutcome::NotStarted => CatalogCode::TimeoutNotStarted,+ AgentOperationOutcome::Unknown => CatalogCode::TimeoutUnknown,+ });+ Self::new(+ entry,+ BackendErrorSource::JdbcAgent,+ map_outcome(*operation_outcome),+ stage_param(entry, *stage),+ None,+ Some(diagnostics_for_local("timeout", *stage)),+ )+ }+ AgentCallError::Canceled { stage, operation_outcome } => Self::new(+ catalog_entry(CatalogCode::Canceled),+ BackendErrorSource::JdbcAgent,+ map_outcome(*operation_outcome),+ stage_param(catalog_entry(CatalogCode::Canceled), *stage),+ None,+ Some(diagnostics_for_local("canceled", *stage)),+ ),+ }+ }++ /// Adapt a non-Agent legacy backend string without attempting text classification.+ pub fn from_legacy_backend(message: &str) -> Self {+ Self::new(+ catalog_entry(CatalogCode::LegacyBackend),+ BackendErrorSource::LegacyBackend,+ BackendOperationOutcome::Unknown,+ BTreeMap::new(),+ safe_detail(message),+ None,+ )+ }++ /// Create a timeout envelope while retaining the bounded diagnostic detail.+ pub fn from_timeout_detail(message: &str) -> Self {+ let entry = catalog_entry(CatalogCode::TimeoutUnknown);+ Self::new(+ entry,+ BackendErrorSource::JdbcAgent,+ BackendOperationOutcome::Unknown,+ stage_param(entry, AgentErrorStage::Execute),+ safe_detail(message),+ Some(diagnostics_for_local("timeout", AgentErrorStage::Execute)),+ )+ }++ /// Create a SQL failure envelope while retaining the bounded diagnostic detail.+ pub fn from_sql_detail(message: &str) -> Self {+ let entry = catalog_entry(CatalogCode::SqlFailed);+ Self::new(+ entry,+ BackendErrorSource::JdbcAgent,+ BackendOperationOutcome::Unknown,+ stage_param(entry, AgentErrorStage::Execute),+ safe_detail(message),+ Some(diagnostics_for_local("sql", AgentErrorStage::Execute)),+ )+ }++ /// Create a cancellation envelope for work canceled by the Rust executor.+ pub fn from_canceled(stage: AgentErrorStage, operation_outcome: AgentOperationOutcome) -> Self {+ let entry = catalog_entry(CatalogCode::Canceled);+ Self::new(+ entry,+ BackendErrorSource::LegacyBackend,+ map_outcome(operation_outcome),+ stage_param(entry, stage),+ None,+ Some(diagnostics_for_local("canceled", stage)),+ )+ }++ /// Convert a legacy boundary string while preserving Agent data when the+ /// compatibility adapter can prove that the string came from an Agent.+ pub fn from_legacy_string(message: &str) -> Self {+ crate::db::agent_driver::try_agent_error_from_legacy(message)+ .map_or_else(|| Self::from_legacy_backend(message), |error| Self::from_agent_call_error(&error))+ }++ pub fn version(&self) -> u8 {+ self.version+ }++ pub fn code(&self) -> &str {+ &self.code+ }++ pub fn message_key(&self) -> &str {+ &self.message_key+ }++ pub fn message_params(&self) -> &BTreeMap<String, BackendMessageParam> {+ &self.message_params+ }++ pub fn source(&self) -> BackendErrorSource {+ self.source+ }++ pub fn operation_outcome(&self) -> BackendOperationOutcome {+ self.operation_outcome+ }++ pub fn detail(&self) -> Option<&str> {+ self.detail.as_deref()+ }++ pub fn without_detail(mut self) -> Self {+ self.detail = None;+ self+ }++ pub fn diagnostics(&self) -> Option<&BackendErrorDiagnostics> {+ self.diagnostics.as_ref()+ }++ fn new(+ entry: &'static CatalogEntry,+ source: BackendErrorSource,+ operation_outcome: BackendOperationOutcome,+ message_params: BTreeMap<String, BackendMessageParam>,+ detail: Option<String>,+ diagnostics: Option<BackendErrorDiagnostics>,+ ) -> Self {+ debug_assert_eq!(message_params.len(), entry.params.len());+ debug_assert!(message_params.iter().all(|(key, value)| entry.allows_value(key, value)));+ Self {+ version: 1,+ code: entry.code.to_string(),+ message_key: entry.message_key.to_string(),+ message_params,+ source,+ operation_outcome,+ detail,+ diagnostics,+ help_url: entry.help_url.map(str::to_string),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CatalogCode {+ ConnectionFailed,+ ConnectionInterrupted,+ TimeoutNotStarted,+ TimeoutUnknown,+ Canceled,+ BusyRetryLater,+ RuntimeReplaced,+ SqlFailed,+ ProtocolFailed,+ ContractInvalid,+ JdbcLegacyFailure,+ LegacyBackend,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ParamKind {+ String,+ Integer,+ Boolean,+}++#[derive(Debug, Clone, Copy)]+struct ParamSpec {+ name: &'static str,+ kind: ParamKind,+}++#[derive(Debug, Clone, Copy)]+struct CatalogEntry {+ code: &'static str,+ message_key: &'static str,+ params: &'static [ParamSpec],+ help_url: Option<&'static str>,+}++const STAGE_PARAM: &[ParamSpec] = &[ParamSpec { name: "stage", kind: ParamKind::String }];+const NO_PARAMS: &[ParamSpec] = &[];++fn catalog_entry(code: CatalogCode) -> &'static CatalogEntry {+ const ENTRIES: &[(CatalogCode, CatalogEntry)] = &[+ (+ CatalogCode::ConnectionFailed,+ CatalogEntry {+ code: "DBX-JDBC-1001",+ message_key: "backendErrors.jdbc.connectionFailed",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::ConnectionInterrupted,+ CatalogEntry {+ code: "DBX-JDBC-1002",+ message_key: "backendErrors.jdbc.connectionInterrupted",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::TimeoutNotStarted,+ CatalogEntry {+ code: "DBX-JDBC-2001",+ message_key: "backendErrors.jdbc.operationTimedOut",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::TimeoutUnknown,+ CatalogEntry {+ code: "DBX-JDBC-2002",+ message_key: "backendErrors.jdbc.operationTimedOut",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::Canceled,+ CatalogEntry {+ code: "DBX-JDBC-2003",+ message_key: "backendErrors.jdbc.operationCanceled",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::BusyRetryLater,+ CatalogEntry {+ code: "DBX-JDBC-3001",+ message_key: "backendErrors.jdbc.busyRetryLater",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::RuntimeReplaced,+ CatalogEntry {+ code: "DBX-JDBC-3002",+ message_key: "backendErrors.jdbc.runtimeReplaced",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::SqlFailed,+ CatalogEntry {+ code: "DBX-JDBC-4001",+ message_key: "backendErrors.jdbc.sqlFailed",+ params: STAGE_PARAM,+ help_url: None,+ },+ ),+ (+ CatalogCode::ProtocolFailed,+ CatalogEntry {+ code: "DBX-JDBC-5001",+ message_key: "backendErrors.jdbc.protocolFailed",+ params: NO_PARAMS,+ help_url: None,+ },+ ),+ (+ CatalogCode::ContractInvalid,+ CatalogEntry {+ code: "DBX-JDBC-5002",+ message_key: "backendErrors.jdbc.contractInvalid",+ params: NO_PARAMS,+ help_url: None,+ },+ ),+ (+ CatalogCode::JdbcLegacyFailure,+ CatalogEntry {+ code: "DBX-JDBC-9001",+ message_key: "backendErrors.jdbc.legacyFailure",+ params: NO_PARAMS,+ help_url: None,+ },+ ),+ (+ CatalogCode::LegacyBackend,+ CatalogEntry {+ code: "DBX-LEGACY-0001",+ message_key: "backendErrors.legacy",+ params: NO_PARAMS,+ help_url: None,+ },+ ),+ ];+ ENTRIES.iter().find(|(kind, _)| *kind == code).map(|(_, entry)| entry).expect("catalog entry missing")+}++fn structured_entry(context: &AgentErrorContext) -> (&'static CatalogEntry, BackendOperationOutcome) {+ if !valid_agent_error_combination(context) {+ return (catalog_entry(CatalogCode::ContractInvalid), BackendOperationOutcome::Unknown);+ }++ let code = match context.category {+ AgentErrorCategory::Connection => match (context.stage, context.operation_outcome) {+ (+ AgentErrorStage::Request+ | AgentErrorStage::Checkout+ | AgentErrorStage::Connect+ | AgentErrorStage::Validate,+ AgentOperationOutcome::NotStarted,+ ) => CatalogCode::ConnectionFailed,+ (+ AgentErrorStage::Execute | AgentErrorStage::Fetch | AgentErrorStage::Cancel | AgentErrorStage::Close,+ AgentOperationOutcome::Unknown,+ ) => CatalogCode::ConnectionInterrupted,+ _ => CatalogCode::ContractInvalid,+ },+ AgentErrorCategory::Timeout => match context.operation_outcome {+ AgentOperationOutcome::NotStarted => CatalogCode::TimeoutNotStarted,+ AgentOperationOutcome::Unknown => CatalogCode::TimeoutUnknown,+ },+ AgentErrorCategory::Canceled => CatalogCode::Canceled,+ AgentErrorCategory::Resource => {+ if context.session_disposition == AgentSessionDisposition::ReplaceRuntime {+ CatalogCode::RuntimeReplaced+ } else if context.operation_outcome == AgentOperationOutcome::NotStarted {+ CatalogCode::BusyRetryLater+ } else {+ CatalogCode::ContractInvalid+ }+ }+ AgentErrorCategory::Sql => {+ if matches!(+ context.stage,+ AgentErrorStage::Execute | AgentErrorStage::Fetch | AgentErrorStage::Cancel | AgentErrorStage::Close+ ) && context.operation_outcome == AgentOperationOutcome::Unknown+ {+ CatalogCode::SqlFailed+ } else {+ CatalogCode::ContractInvalid+ }+ }+ AgentErrorCategory::Protocol => CatalogCode::ProtocolFailed,+ };+ let entry = catalog_entry(code);+ let outcome = if matches!(code, CatalogCode::ContractInvalid) {+ BackendOperationOutcome::Unknown+ } else {+ map_outcome(context.operation_outcome)+ };+ (entry, outcome)+}++fn map_outcome(outcome: AgentOperationOutcome) -> BackendOperationOutcome {+ match outcome {+ AgentOperationOutcome::NotStarted => BackendOperationOutcome::NotStarted,+ AgentOperationOutcome::Unknown => BackendOperationOutcome::Unknown,+ }+}++fn stage_param(entry: &'static CatalogEntry, stage: AgentErrorStage) -> BTreeMap<String, BackendMessageParam> {+ let mut params = BTreeMap::new();+ let value = BackendMessageParam::String(stage_name(stage).to_string());+ if entry.allows_value("stage", &value) {+ params.insert("stage".to_string(), value);+ }+ params+}++impl CatalogEntry {+ fn allows_value(self, name: &str, value: &BackendMessageParam) -> bool {+ self.params.iter().any(|param| param.name == name && param.kind == value.kind())+ }+}++impl BackendMessageParam {+ fn kind(&self) -> ParamKind {+ match self {+ Self::String(_) => ParamKind::String,+ Self::Integer(_) => ParamKind::Integer,+ Self::Boolean(_) => ParamKind::Boolean,+ }+ }+}++fn diagnostics_from_context(context: &AgentErrorContext) -> BackendErrorDiagnostics {+ BackendErrorDiagnostics {+ category: Some(category_name(context.category).to_string()),+ stage: Some(stage_name(context.stage).to_string()),+ sql_state: context.sql_state.as_deref().map(|value| bounded_ascii(value, 32)),+ vendor_code: context.vendor_code,+ exception_class: context.exception_class.as_deref().map(|value| bounded_ascii(value, 128)),+ }+}++fn diagnostics_for_local(category: &str, stage: AgentErrorStage) -> BackendErrorDiagnostics {+ BackendErrorDiagnostics {+ category: Some(category.to_string()),+ stage: Some(stage_name(stage).to_string()),+ ..Default::default()+ }+}++fn bounded_ascii(value: &str, max: usize) -> String {+ value.chars().filter(|ch| ch.is_ascii_graphic() || *ch == ' ').take(max).collect()+}++fn bounded_text(value: &str, max_bytes: usize) -> String {+ let end = value+ .char_indices()+ .map(|(index, ch)| (index, index + ch.len_utf8()))+ .take_while(|(_, next)| *next <= max_bytes)+ .map(|(_, next)| next)+ .last()+ .unwrap_or(0);+ value[..end].to_string()+}++fn safe_detail(message: &str) -> Option<String> {+ let trimmed = message.trim();+ if trimmed.is_empty() {+ return None;+ }+ let normalized = trimmed.split_ascii_whitespace().collect::<Vec<_>>().join(" ");+ let lowered = normalized.to_ascii_lowercase();+ let sensitive_markers = [+ "://",+ "jdbc:",+ "password",+ "passwd",+ "pwd",+ "token",+ "secret",+ "authorization",+ "bearer",+ "api_key",+ "apikey",+ "credential",+ "auth=",+ "key=",+ "user=",+ "username=",+ "uid=",+ "access_key",+ "private_key",+ "agent session",+ "agentsessionid",+ "session id",+ "session_id",+ "session=",+ ];+ if sensitive_markers.iter().any(|marker| lowered.contains(marker)) {+ return None;+ }+ let sql_verbs = [+ "select", "insert", "update", "delete", "drop", "create", "alter", "truncate", "merge", "call", "with",+ "grant", "revoke", "comment", "explain", "begin", "commit", "rollback",+ ];+ if lowered.split(|ch: char| !ch.is_ascii_alphabetic()).any(|word| sql_verbs.contains(&word)) {+ return None;+ }+ let detail = bounded_text(&normalized, MAX_DETAIL_BYTES);+ (!detail.is_empty()).then_some(detail)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::db::agent_driver::{AgentErrorStage, AgentSessionDisposition};+ use std::collections::BTreeSet;++ fn context(+ category: AgentErrorCategory,+ stage: AgentErrorStage,+ outcome: AgentOperationOutcome,+ ) -> AgentErrorContext {+ AgentErrorContext {+ contract_version: 1,+ category,+ retryable: true,+ session_disposition: if matches!(category, AgentErrorCategory::Timeout | AgentErrorCategory::Canceled) {+ AgentSessionDisposition::Quarantine+ } else {+ AgentSessionDisposition::Keep+ },+ stage,+ operation_outcome: outcome,+ agent_session_id: Some("private-session".to_string()),+ sql_state: Some("08006".to_string()),+ vendor_code: Some(-7),+ exception_class: Some("java.sql.SQLException".to_string()),+ }+ }++ #[test]+ fn catalog_owns_exact_code_and_message_key_pairs() {+ let cases = [+ (CatalogCode::ConnectionFailed, "DBX-JDBC-1001", "backendErrors.jdbc.connectionFailed"),+ (CatalogCode::ConnectionInterrupted, "DBX-JDBC-1002", "backendErrors.jdbc.connectionInterrupted"),+ (CatalogCode::TimeoutNotStarted, "DBX-JDBC-2001", "backendErrors.jdbc.operationTimedOut"),+ (CatalogCode::TimeoutUnknown, "DBX-JDBC-2002", "backendErrors.jdbc.operationTimedOut"),+ (CatalogCode::Canceled, "DBX-JDBC-2003", "backendErrors.jdbc.operationCanceled"),+ (CatalogCode::BusyRetryLater, "DBX-JDBC-3001", "backendErrors.jdbc.busyRetryLater"),+ (CatalogCode::RuntimeReplaced, "DBX-JDBC-3002", "backendErrors.jdbc.runtimeReplaced"),+ (CatalogCode::SqlFailed, "DBX-JDBC-4001", "backendErrors.jdbc.sqlFailed"),+ (CatalogCode::ProtocolFailed, "DBX-JDBC-5001", "backendErrors.jdbc.protocolFailed"),+ (CatalogCode::ContractInvalid, "DBX-JDBC-5002", "backendErrors.jdbc.contractInvalid"),+ (CatalogCode::JdbcLegacyFailure, "DBX-JDBC-9001", "backendErrors.jdbc.legacyFailure"),+ (CatalogCode::LegacyBackend, "DBX-LEGACY-0001", "backendErrors.legacy"),+ ];+ let mut codes = BTreeSet::new();+ for (kind, expected_code, expected_key) in cases {+ let entry = catalog_entry(kind);+ assert_eq!(entry.code, expected_code);+ assert_eq!(entry.message_key, expected_key);+ assert!(codes.insert(entry.code), "duplicate catalog code: {}", entry.code);+ }+ }++ #[test]+ fn catalog_maps_valid_variants_and_emits_allowlisted_params() {+ let cases = [+ (+ AgentErrorCategory::Connection,+ AgentErrorStage::Request,+ AgentOperationOutcome::NotStarted,+ "DBX-JDBC-1001",+ ),+ (AgentErrorCategory::Connection, AgentErrorStage::Execute, AgentOperationOutcome::Unknown, "DBX-JDBC-1002"),+ (AgentErrorCategory::Timeout, AgentErrorStage::Connect, AgentOperationOutcome::NotStarted, "DBX-JDBC-2001"),+ (AgentErrorCategory::Timeout, AgentErrorStage::Execute, AgentOperationOutcome::Unknown, "DBX-JDBC-2002"),+ (AgentErrorCategory::Canceled, AgentErrorStage::Cancel, AgentOperationOutcome::Unknown, "DBX-JDBC-2003"),+ (+ AgentErrorCategory::Resource,+ AgentErrorStage::Request,+ AgentOperationOutcome::NotStarted,+ "DBX-JDBC-3001",+ ),+ (AgentErrorCategory::Resource, AgentErrorStage::Execute, AgentOperationOutcome::Unknown, "DBX-JDBC-5002"),+ (AgentErrorCategory::Sql, AgentErrorStage::Execute, AgentOperationOutcome::Unknown, "DBX-JDBC-4001"),+ (AgentErrorCategory::Protocol, AgentErrorStage::Request, AgentOperationOutcome::Unknown, "DBX-JDBC-5002"),+ ];+ for (category, stage, outcome, expected_code) in cases {+ let error = AgentCallError::Structured {+ rpc_code: -1,+ message: "safe failure".to_string(),+ context: context(category, stage, outcome),+ };+ let envelope = BackendError::from_agent_call_error(&error);+ assert_eq!(envelope.code(), expected_code);+ assert_eq!(envelope.version(), 1);+ if expected_code != "DBX-JDBC-5002" {+ assert_eq!(+ envelope.message_params().get("stage"),+ Some(&BackendMessageParam::String(stage_name(stage).to_string()))+ );+ }+ }+ }++ #[test]+ fn unsafe_detail_is_omitted_and_internal_fields_are_not_serialized() {+ for message in [+ "DROP TABLE users",+ "SELECT\tpassword FROM users",+ "postgresql://host/db?user=alice&pwd=secret",+ "Bearer token-value",+ "CALL refresh_cache()",+ "syntax error in statement [UPDATE customers SET ssn='123']",+ "Agent session not found: 7f51e7f4-7cee-42db-bfeb-76d1199d1afe",+ ] {+ assert!(safe_detail(message).is_none(), "detail leaked: {message}");+ }+ let error = BackendError::from_agent_call_error(&AgentCallError::Structured {+ rpc_code: -1,+ message: "jdbc:postgresql://host/db?password=secret".to_string(),+ context: context(+ AgentErrorCategory::Connection,+ AgentErrorStage::Request,+ AgentOperationOutcome::NotStarted,+ ),+ });+ let value = serde_json::to_value(error).unwrap();+ assert_eq!(value["source"], "jdbcAgent");+ assert!(value.get("retryable").is_none());+ assert!(value.get("sessionDisposition").is_none());+ assert!(value.get("agentSessionId").is_none());+ assert!(value.get("detail").is_none());+ }++ #[test]+ fn invalid_structured_combinations_use_contract_catalog_code() {+ let invalid = [+ (+ AgentErrorCategory::Timeout,+ AgentErrorStage::Request,+ AgentOperationOutcome::Unknown,+ AgentSessionDisposition::Keep,+ ),+ (+ AgentErrorCategory::Protocol,+ AgentErrorStage::Request,+ AgentOperationOutcome::NotStarted,+ AgentSessionDisposition::ReplaceRuntime,+ ),+ (+ AgentErrorCategory::Resource,+ AgentErrorStage::Execute,+ AgentOperationOutcome::Unknown,+ AgentSessionDisposition::Keep,+ ),+ (+ AgentErrorCategory::Sql,+ AgentErrorStage::Connect,+ AgentOperationOutcome::NotStarted,+ AgentSessionDisposition::Keep,+ ),+ ];+ for (category, stage, outcome, disposition) in invalid {+ let mut ctx = context(category, stage, outcome);+ ctx.session_disposition = disposition;+ let envelope = BackendError::from_agent_call_error(&AgentCallError::Structured {+ rpc_code: -1,+ message: "invalid combination".to_string(),+ context: ctx,+ });+ assert_eq!(envelope.code(), "DBX-JDBC-5002");+ assert_eq!(envelope.operation_outcome(), BackendOperationOutcome::Unknown);+ }+ }++ #[test]+ fn legacy_adapters_use_stable_sources() {+ let legacy = BackendError::from_agent_call_error(&AgentCallError::Legacy {+ rpc_code: None,+ message: "old agent".to_string(),+ hints: Default::default(),+ });+ assert_eq!(legacy.code(), "DBX-JDBC-9001");+ assert_eq!(legacy.source, BackendErrorSource::JdbcAgentLegacy);+ assert_eq!(BackendError::from_legacy_backend("driver failed").code(), "DBX-LEGACY-0001");+ }++ #[test]+ fn legacy_agent_envelope_keeps_multiline_database_detail() {+ let legacy = AgentCallError::Legacy {+ rpc_code: Some(-1),+ message: "ERROR: relation \"dbx_table_that_does_not_exist\" does not exist\n Position: 15".to_string(),+ hints: Default::default(),+ }+ .into_legacy_string();+ let error = BackendError::from_legacy_string(&legacy);++ assert_eq!(error.code(), "DBX-JDBC-9001");+ assert_eq!(+ error.detail(),+ Some("ERROR: relation \"dbx_table_that_does_not_exist\" does not exist Position: 15")+ );+ }++ #[test]+ fn legacy_agent_envelope_keeps_dm_chinese_database_detail() {+ let legacy = AgentCallError::Legacy {+ rpc_code: Some(-1),+ message: "无效的表或视图名\n错误码: -2106".to_string(),+ hints: Default::default(),+ }+ .into_legacy_string();+ let error = BackendError::from_legacy_string(&legacy);++ assert_eq!(error.code(), "DBX-JDBC-9001");+ assert_eq!(error.detail(), Some("无效的表或视图名 错误码: -2106"));+ }++ #[test]+ fn strict_marker_round_trip_keeps_catalog_code() {+ let error = AgentCallError::Structured {+ rpc_code: -1,+ message: "connection lost".to_string(),+ context: context(AgentErrorCategory::Connection, AgentErrorStage::Execute, AgentOperationOutcome::Unknown),+ };+ let legacy =+ crate::db::agent_driver::append_legacy_error_context(&error.into_legacy_string(), "SQL text omitted");++ assert_eq!(BackendError::from_legacy_string(&legacy).code(), "DBX-JDBC-1002");+ }+}diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 2976406069..1ef5b44519 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -15,9 +15,10 @@ use crate::agent_connection::{trino_like_jdbc_connection_string, AgentSessionRole,};use crate::agent_manager::{JavaRuntimeMode, DEFAULT_JRE_KEY};+use crate::agent_recovery::{RecoveryDecision, RecoveryPolicy, RecoveryScope};use crate::database_capabilities;use crate::db;-use crate::db::agent_driver::AgentMethod;+use crate::db::agent_driver::{AgentCallError, AgentMethod};use crate::db::http_tunnel::HttpTunnelManager;use crate::db::proxy_tunnel::ProxyTunnelManager;use crate::db::ssh_tunnel::TunnelManager;@@ -550,8 +551,7 @@ fn fail_stop_removed_agent_pool(pool_key: &str, pool: &PoolKind) {}fn should_replace_agent_runtime(error: &str) -> bool {- crate::db::agent_driver::agent_session_disposition(error)- == Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime)+ crate::db::agent_driver::agent_recovery_decision(error, RecoveryScope::ConnectionOpen).replaces_runtime()}pub fn metadata_connection_config(config: &ConnectionConfig) -> ConnectionConfig {@@ -681,10 +681,10 @@ pub fn sqlserver_uses_legacy_driver(config: &ConnectionConfig) -> bool {}pub fn sqlserver_legacy_driver_error(agent_error: &str) -> String {- // AgentManager currently returns launch failures as strings. This exact marker is generated- // internally and only adds guidance for an explicitly selected compatibility driver.+ // This mapper handles both AgentManager launch strings and Agent call errors, so context+ // must remain before any structured-error compatibility marker.if agent_error.contains("driver is not installed") {- format!("{agent_error}\n\n{SQLSERVER_LEGACY_DRIVER_INSTALL_HINT}")+ crate::db::agent_driver::append_legacy_error_context(agent_error, SQLSERVER_LEGACY_DRIVER_INSTALL_HINT)} else {agent_error.to_string()}@@ -1462,12 +1462,14 @@ impl AppState {Ok(Ok(())) => {}Ok(Err(err)) => {log::warn!("Connection keepalive failed for '{key}': {err}; invalidating pool");+ let replace_runtime =+ err.recovery_decision().is_some_and(RecoveryDecision::replaces_runtime);if !detach_keepalive_target_if_current(&routing,&connections,&key,target,- should_replace_agent_runtime(&err),+ replace_runtime,).await{@@ -2904,15 +2906,15 @@ impl AppState {return false;};let timeout = crate::db::connection_timeout();- match agent.validate_connection(Some(timeout)).await {+ match agent.validate_connection_typed(Some(timeout)).await {Ok(_) => false,- Err(err) if is_agent_validate_connection_unsupported(&err) => {+ Err(err) if is_agent_validate_connection_unsupported(&err.to_string()) => {log::debug!("Agent connection pool '{pool_key}' does not support validate_connection; keeping pool");false}- Err(err) if should_replace_agent_runtime(&err) => {+ Err(err) if RecoveryPolicy::decide(&err, RecoveryScope::Keepalive).replaces_runtime() => {log::warn!("Agent connection pool '{pool_key}' requested runtime replacement during health probe: {err}");@@ -3143,12 +3145,12 @@ impl AppState {self.detach_pool_by_key(&pool_key, true).await}- pub(crate) async fn detach_metadata_pool_after_error(+ pub(crate) async fn detach_metadata_pool_after_recovery(&self,connection_id: &str,database: Option<&str>,client_session_id: Option<&str>,- error: &str,+ agent_session_id: Option<&str>,replace_agent_runtime: bool,) -> bool {let config = {@@ -3159,11 +3161,11 @@ impl AppState {let base_pool_key = base_pool_key_for(db_type, connection_id, database, false);let pool_key =pool_key_for_session_role(config.as_ref(), base_pool_key, client_session_id, AgentSessionRole::Metadata);- if let Some(session_id) = crate::db::agent_driver::agent_rpc_error_session_id(error) {+ if let Some(session_id) = agent_session_id {let expected_client = {let connections = self.connections.read().await;match connections.get(&pool_key) {- Some(PoolKind::Agent(client)) if client.matches_session_id(&session_id) => Some(client.clone()),+ Some(PoolKind::Agent(client)) if client.matches_session_id(session_id) => Some(client.clone()),Some(PoolKind::Agent(_)) => return false,_ => None,}@@ -3786,9 +3788,9 @@ impl AppState {log::debug!("Agent connection pool '{key}' is busy; skipping resume health probe");continue;};- match agent.validate_connection(Some(timeout)).await {+ match agent.validate_connection_typed(Some(timeout)).await {Ok(_) => true,- Err(err) if is_agent_validate_connection_unsupported(&err) => {+ Err(err) if is_agent_validate_connection_unsupported(&err.to_string()) => {log::debug!("Agent connection pool '{key}' does not support validate_connection; keeping pool");@@ -3796,7 +3798,11 @@ impl AppState {}Err(e) => {log::warn!("Agent connection pool '{key}' is unhealthy: {e}");- failed_agent_checks.push((key.clone(), client.clone(), should_replace_agent_runtime(&e)));+ failed_agent_checks.push((+ key.clone(),+ client.clone(),+ RecoveryPolicy::decide(&e, RecoveryScope::Keepalive).replaces_runtime(),+ ));false}}@@ -4030,6 +4036,36 @@ enum KeepaliveTarget {Agent(Arc<db::agent_driver::PooledAgentClient>),}+#[derive(Debug)]+enum KeepaliveError {+ Agent(AgentCallError),+ Legacy(String),+}++impl KeepaliveError {+ fn recovery_decision(&self) -> Option<RecoveryDecision> {+ match self {+ Self::Agent(error) => Some(RecoveryPolicy::decide(error, RecoveryScope::Keepalive)),+ Self::Legacy(_) => None,+ }+ }+}++impl std::fmt::Display for KeepaliveError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Agent(error) => error.fmt(formatter),+ Self::Legacy(error) => formatter.write_str(error),+ }+ }+}++impl From<String> for KeepaliveError {+ fn from(error: String) -> Self {+ Self::Legacy(error)+ }+}+impl KeepaliveTarget {fn matches_pool(&self, pool: &PoolKind) -> bool {match (self, pool) {@@ -4095,41 +4131,55 @@ fn keepalive_target_from_pool(pool: &PoolKind, config: &ConnectionConfig) -> Opt}}-async fn ping_keepalive_target(target: &mut KeepaliveTarget, timeout: Duration) -> Result<(), String> {+async fn ping_keepalive_target(target: &mut KeepaliveTarget, timeout: Duration) -> Result<(), KeepaliveError> {match target {KeepaliveTarget::Mysql(pool) => {let mut conn = db::mysql::get_conn_with_health_check(pool).await?;- conn.ping().await.map_err(|e| e.to_string())+ conn.ping().await.map_err(|error| KeepaliveError::Legacy(error.to_string()))}KeepaliveTarget::Postgres(pool) => {let client = pool.get().await.map_err(|e| format!("PostgreSQL pool error: {e}"))?;- client.simple_query("SELECT 1").await.map(|_| ()).map_err(|e| e.to_string())+ client.simple_query("SELECT 1").await.map(|_| ()).map_err(|error| KeepaliveError::Legacy(error.to_string()))}- KeepaliveTarget::Rqlite(client) => db::rqlite_driver::test_connection(client, timeout).await,- KeepaliveTarget::Turso(client) => db::turso_driver::test_connection(client, timeout).await,+ KeepaliveTarget::Rqlite(client) => {+ db::rqlite_driver::test_connection(client, timeout).await.map_err(Into::into)+ }+ KeepaliveTarget::Turso(client) => db::turso_driver::test_connection(client, timeout).await.map_err(Into::into),KeepaliveTarget::MongoDb { client, database } => {- db::mongo_driver::test_connection(client, timeout, database.as_deref()).await+ db::mongo_driver::test_connection(client, timeout, database.as_deref()).await.map_err(Into::into)+ }+ KeepaliveTarget::ClickHouse(client) => {+ db::clickhouse_driver::test_connection(client, timeout).await.map_err(Into::into)}- KeepaliveTarget::ClickHouse(client) => db::clickhouse_driver::test_connection(client, timeout).await,KeepaliveTarget::SqlServer(client) => {let Ok(mut client) = client.try_lock() else {return Ok(());};- db::sqlserver::test_connection(&mut client).await+ db::sqlserver::test_connection(&mut client).await.map_err(Into::into)+ }+ KeepaliveTarget::Elasticsearch(client) => {+ db::elasticsearch_driver::test_connection(client, timeout).await.map_err(Into::into)+ }+ KeepaliveTarget::Easysearch(client) => {+ db::easysearch_driver::test_connection(client, timeout).await.map_err(Into::into)+ }+ KeepaliveTarget::HBase(client) => {+ db::hbase_driver::test_connection(client, timeout).await.map(|_| ()).map_err(Into::into)+ }+ KeepaliveTarget::VectorDb(client) => {+ db::vector_driver::test_connection(client, timeout).await.map_err(Into::into)+ }+ KeepaliveTarget::InfluxDb(client) => {+ db::influxdb_driver::test_connection(client, timeout).await.map_err(Into::into)}- KeepaliveTarget::Elasticsearch(client) => db::elasticsearch_driver::test_connection(client, timeout).await,- KeepaliveTarget::Easysearch(client) => db::easysearch_driver::test_connection(client, timeout).await,- KeepaliveTarget::HBase(client) => db::hbase_driver::test_connection(client, timeout).await.map(|_| ()),- KeepaliveTarget::VectorDb(client) => db::vector_driver::test_connection(client, timeout).await,- KeepaliveTarget::InfluxDb(client) => db::influxdb_driver::test_connection(client, timeout).await,KeepaliveTarget::Agent(client) => {let Ok(mut client) = client.try_lock() else {return Ok(());};- match client.validate_connection(Some(timeout)).await {+ match client.validate_connection_typed(Some(timeout)).await {Ok(_) => Ok(()),- Err(err) if is_agent_validate_connection_unsupported(&err) => Ok(()),- Err(err) => Err(err),+ Err(error) if is_agent_validate_connection_unsupported(&error.to_string()) => Ok(()),+ Err(error) => Err(KeepaliveError::Agent(error)),}}}@@ -4949,6 +4999,34 @@ mod tests {assert!(message.contains("enable SQL Server legacy compatibility mode again"));}+ #[test]+ fn sqlserver_legacy_driver_hint_preserves_structured_agent_error() {+ let error = crate::db::agent_driver::AgentCallError::Structured {+ rpc_code: -6007,+ message: "driver is not installed".to_string(),+ context: crate::db::agent_driver::AgentErrorContext {+ contract_version: 1,+ category: crate::db::agent_driver::AgentErrorCategory::Connection,+ retryable: false,+ session_disposition: crate::db::agent_driver::AgentSessionDisposition::Quarantine,+ stage: crate::db::agent_driver::AgentErrorStage::Connect,+ operation_outcome: crate::db::agent_driver::AgentOperationOutcome::NotStarted,+ agent_session_id: None,+ sql_state: None,+ vendor_code: None,+ exception_class: None,+ },+ }+ .into_legacy_string();++ let message = sqlserver_legacy_driver_error(&error);++ assert!(matches!(+ crate::db::agent_driver::agent_error_from_legacy(&message, None),+ crate::db::agent_driver::AgentCallError::Structured { .. }+ ));+ }+#[test]fn agent_connect_params_include_url_params() {let mut config = mysql_config(Some("testdb"));@@ -6788,13 +6866,12 @@ for line in sys.stdin:state.configs.write().await.insert(config.id.clone(), config);let pool_key = "conn:analytics:role:metadata";state.connections.write().await.insert(pool_key.to_string(), PoolKind::Agent(current_client.clone()));- let stale_error = concat!(- "Agent RPC error (-1): stale metadata failure\nDBX_AGENT_ERROR_DATA:",- r#"{"category":"resource","sessionDisposition":"replace_runtime","agentSessionId":"stale-session"}"#+ assert!(+ !state+ .detach_metadata_pool_after_recovery("conn", Some("analytics"), None, Some("stale-session"), true,)+ .await);- assert!(!state.detach_metadata_pool_after_error("conn", Some("analytics"), None, stale_error, true).await);-let connections = state.connections.read().await;let PoolKind::Agent(routed_client) = connections.get(pool_key).expect("new metadata generation must remain")else {@@ -6816,10 +6893,7 @@ for line in sys.stdin:let error = super::ping_keepalive_target(&mut target, Duration::from_secs(1)).await.unwrap_err();- assert_eq!(- crate::db::agent_driver::agent_session_disposition(&error),- Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime)- );+ assert!(matches!(error.recovery_decision(), Some(crate::agent_recovery::RecoveryDecision::ReplaceRuntime)));assert!(!runtime.is_failed());runtime.kill();let _ = std::fs::remove_dir_all(dir);diff --git a/crates/dbx-core/src/db/agent_driver.rs b/crates/dbx-core/src/db/agent_driver.rsindex ea46f777be..fc1805e76c 100644--- a/crates/dbx-core/src/db/agent_driver.rs+++ b/crates/dbx-core/src/db/agent_driver.rs@@ -1,4 +1,5 @@use std::collections::{HashMap, VecDeque};+use std::fmt;use std::io::{BufRead, BufReader, BufWriter, Write};use std::path::{Path, PathBuf};use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};@@ -11,6 +12,7 @@ use serde::{Deserialize, Serialize};use serde_json::Value;use tokio_util::sync::CancellationToken;+use crate::agent_recovery::{RecoveryDecision, RecoveryPolicy, RecoveryScope};use crate::models::connection::DatabaseConnectionInfo;type PendingAgentResponse = tokio::sync::oneshot::Sender<Result<Value, String>>;@@ -74,7 +76,7 @@ impl AgentRuntimeClient {});runtime.start_response_reader(stdout);let handshake = match runtime- .call::<AgentHandshake>(+ .call_typed::<AgentHandshake>(AgentMethod::Handshake.as_str(),agent_handshake_params(app_version),Some(Duration::from_secs(RPC_TIMEOUT_SECS)),@@ -83,13 +85,13 @@ impl AgentRuntimeClient {.await{Ok(handshake) => handshake,- Err(error) if is_unsupported_handshake_error(&error) => {+ Err(error) if is_unsupported_handshake_error(&error.to_string()) => {runtime.kill();return Err("Agent runtime does not support multi_session protocol v2".to_string());}Err(error) => {runtime.kill();- return Err(error);+ return Err(error.into_legacy_string());}};if handshake.protocol_version < 2 || !handshake.supports(AgentCapability::MultiSession) {@@ -137,15 +139,30 @@ impl AgentRuntimeClient {timeout_duration: Option<Duration>,cancel_token: Option<CancellationToken>,) -> Result<T, String> {+ self.call_typed(method, params, timeout_duration, cancel_token)+ .await+ .map_err(AgentCallError::into_legacy_string)+ }++ pub async fn call_typed<T: DeserializeOwned>(+ &self,+ method: &str,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {if self.failed.load(Ordering::Acquire) {- return Err("Agent runtime is unavailable".to_string());+ return Err(AgentCallError::Transport { message: "Agent runtime is unavailable".to_string() });}let id = self.next_id.fetch_add(1, Ordering::Relaxed) + 1;let request = serde_json::json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });- let request_line =- serde_json::to_string(&request).map_err(|e| format!("Failed to serialize JSON-RPC request: {e}"))?;+ let request_line = serde_json::to_string(&request)+ .map_err(|e| AgentCallError::Transport { message: format!("Failed to serialize JSON-RPC request: {e}") })?;let (sender, receiver) = tokio::sync::oneshot::channel();- self.pending.lock().map_err(|_| "Agent pending response lock poisoned".to_string())?.insert(id, sender);+ self.pending+ .lock()+ .map_err(|_| AgentCallError::Transport { message: "Agent pending response lock poisoned".to_string() })?+ .insert(id, sender);let write_result =self.stdin.lock().map_err(|_| "Agent stdin lock poisoned".to_string()).and_then(|mut writer| {writer@@ -156,21 +173,32 @@ impl AgentRuntimeClient {});if let Err(err) = write_result {self.pending.lock().expect("agent pending response lock poisoned").remove(&id);- return Err(err);+ return Err(AgentCallError::Transport { message: err });}- let receive = async { receiver.await.map_err(|_| "Agent response channel closed".to_string())? };+ let receive = async {+ receiver+ .await+ .map_err(|_| AgentCallError::Transport { message: "Agent response channel closed".to_string() })?+ .map_err(|message| AgentCallError::Transport { message })+ };let response = match (timeout_duration, cancel_token) {(Some(duration), Some(token)) => tokio::select! {_ = token.cancelled() => {self.cancel_session_request_for_method(method, ¶ms).await;- Err("Query canceled".to_string())+ Err(AgentCallError::Canceled {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ })},result = tokio::time::timeout(duration, receive) => match result {Ok(result) => result,Err(_) => {self.cancel_session_request_for_method(method, ¶ms).await;- Err(format!("Agent RPC call timed out ({}s)", duration.as_secs()))+ Err(AgentCallError::Timeout {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ })}},},@@ -178,13 +206,19 @@ impl AgentRuntimeClient {Ok(result) => result,Err(_) => {self.cancel_session_request_for_method(method, ¶ms).await;- Err(format!("Agent RPC call timed out ({}s)", duration.as_secs()))+ Err(AgentCallError::Timeout {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ })}},(None, Some(token)) => tokio::select! {_ = token.cancelled() => {self.cancel_session_request_for_method(method, ¶ms).await;- Err("Query canceled".to_string())+ Err(AgentCallError::Canceled {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ })},result = receive => result,},@@ -193,7 +227,12 @@ impl AgentRuntimeClient {if response.is_err() {self.pending.lock().expect("agent pending response lock poisoned").remove(&id);}- decode_agent_response(response?)+ let response = response?;+ decode_agent_response(+ response,+ self.handshake.supports(AgentCapability::StructuredErrorV1),+ params.get("agentSessionId").and_then(Value::as_str),+ )}async fn cancel_session_request_for_method(&self, method: &str, params: &Value) {@@ -206,7 +245,7 @@ impl AgentRuntimeClient {let Some(agent_session_id) = params.get("agentSessionId").and_then(Value::as_str) else {return;};- let _ = Box::pin(self.call::<Value>(+ let _ = Box::pin(self.call_typed::<Value>(AgentMethod::CancelSession.as_str(),serde_json::json!({ "agentSessionId": agent_session_id }),Some(Duration::from_secs(5)),@@ -275,78 +314,492 @@ impl AgentRuntimeClient {}}-fn decode_agent_response<T: DeserializeOwned>(response: Value) -> Result<T, String> {+fn decode_agent_response<T: DeserializeOwned>(+ response: Value,+ strict_structured_errors: bool,+ expected_session_id: Option<&str>,+) -> Result<T, AgentCallError> {if let Some(err) = response.get("error") {- return Err(format_agent_rpc_error(err));- }- let result =- response.get("result").ok_or_else(|| "Agent response missing both 'result' and 'error'".to_string())?;- serde_json::from_value(result.clone()).map_err(|e| format!("Failed to deserialize agent result: {e}"))+ return Err(parse_agent_call_error(err, strict_structured_errors, expected_session_id));+ }+ let result = response.get("result").ok_or_else(|| AgentCallError::ContractViolation {+ rpc_code: None,+ message: "Agent response missing both 'result' and 'error'".to_string(),+ reason: ContractViolationReason::MissingResultOrError,+ })?;+ serde_json::from_value(result.clone()).map_err(|e| AgentCallError::ContractViolation {+ rpc_code: None,+ message: format!("Failed to deserialize agent result: {e}"),+ reason: ContractViolationReason::InvalidResult,+ })}const AGENT_RPC_ERROR_DATA_MARKER: &str = "\nDBX_AGENT_ERROR_DATA:";-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]pub enum AgentSessionDisposition {Keep,Quarantine,ReplaceRuntime,}-pub fn agent_rpc_error_category(error: &str) -> Option<String> {- agent_rpc_error_data(error)?.get("category")?.as_str().map(str::to_string)+impl AgentSessionDisposition {+ fn as_str(self) -> &'static str {+ match self {+ Self::Keep => "keep",+ Self::Quarantine => "quarantine",+ Self::ReplaceRuntime => "replace_runtime",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum AgentErrorCategory {+ Connection,+ Sql,+ Resource,+ Protocol,+ Timeout,+ Canceled,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum AgentErrorStage {+ Request,+ Checkout,+ Connect,+ Validate,+ Execute,+ Fetch,+ Cancel,+ Close,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum AgentOperationOutcome {+ NotStarted,+ Unknown,}-pub fn agent_rpc_error_session_id(error: &str) -> Option<String> {- agent_rpc_error_data(error)?.get("agentSessionId")?.as_str().map(str::to_string)+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentErrorContext {+ pub contract_version: u8,+ pub category: AgentErrorCategory,+ pub retryable: bool,+ pub session_disposition: AgentSessionDisposition,+ pub stage: AgentErrorStage,+ pub operation_outcome: AgentOperationOutcome,+ #[serde(default)]+ pub agent_session_id: Option<String>,+ #[serde(default)]+ pub sql_state: Option<String>,+ #[serde(default)]+ pub vendor_code: Option<i32>,+ #[serde(default)]+ pub exception_class: Option<String>,+}++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct LegacyAgentHints {+ pub category: Option<AgentErrorCategory>,+ pub retryable: Option<bool>,+ pub session_disposition: Option<AgentSessionDisposition>,+ pub stage: Option<AgentErrorStage>,+ pub operation_outcome: Option<AgentOperationOutcome>,+ pub agent_session_id: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ContractViolationReason {+ MissingContractVersion,+ UnsupportedContractVersion,+ InvalidDataShape,+ InvalidSessionId,+ InvalidCombination,+ MissingResultOrError,+ InvalidResult,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum AgentCallError {+ Structured { rpc_code: i64, message: String, context: AgentErrorContext },+ Legacy { rpc_code: Option<i64>, message: String, hints: LegacyAgentHints },+ ContractViolation { rpc_code: Option<i64>, message: String, reason: ContractViolationReason },+ Transport { message: String },+ Timeout { stage: AgentErrorStage, operation_outcome: AgentOperationOutcome },+ Canceled { stage: AgentErrorStage, operation_outcome: AgentOperationOutcome },}-pub fn agent_session_disposition(error: &str) -> Option<AgentSessionDisposition> {- match agent_rpc_error_data(error)?.get("sessionDisposition")?.as_str()? {- "keep" => Some(AgentSessionDisposition::Keep),- "quarantine" => Some(AgentSessionDisposition::Quarantine),- "replace_runtime" => Some(AgentSessionDisposition::ReplaceRuntime),- _ => None,+/// Decode an already-stringified Agent failure at the compatibility boundary.+///+/// Business modules must use this adapter instead of inspecting the legacy+/// `DBX_AGENT_ERROR_DATA` marker themselves. Callers must only use it after the+/// owning pool has been identified as an Agent pool.+pub(crate) fn agent_error_from_legacy(error: &str, expected_session_id: Option<&str>) -> AgentCallError {+ if error == "Query canceled" {+ return AgentCallError::Canceled {+ stage: AgentErrorStage::Cancel,+ operation_outcome: AgentOperationOutcome::Unknown,+ };+ }+ let lower = error.to_ascii_lowercase();+ if lower.starts_with("agent rpc call timed out") {+ return AgentCallError::Timeout {+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ };}+ legacy_agent_call_error(error.to_string(), expected_session_id)}-fn format_agent_rpc_error(error: &Value) -> String {- let message = error.get("message").and_then(Value::as_str).unwrap_or("Unknown agent error");- let code = error.get("code").and_then(Value::as_i64).unwrap_or(-1);- let mut formatted = format!("Agent RPC error ({code}): {message}");- if let Some(data) = error.get("data").filter(|data| data.is_object()) {- formatted.push_str(AGENT_RPC_ERROR_DATA_MARKER);- formatted.push_str(&data.to_string());+/// Returns a typed error only when a mixed legacy path can prove the string+/// originated from the Agent call corridor.+pub(crate) fn try_agent_error_from_legacy(error: &str) -> Option<AgentCallError> {+ let lower = error.to_ascii_lowercase();+ let is_local_agent_failure = error == "Query canceled"+ || lower.starts_with("agent rpc call timed out")+ || lower.contains("agent stdin not available")+ || lower.contains("agent stdout not available")+ || lower.contains("agent runtime terminated")+ || lower.contains("agent runtime is unavailable")+ || lower.contains("agent runtime unavailable")+ || lower.contains("failed to write to agent stdin")+ || lower.contains("failed to flush agent stdin")+ || lower.contains("agent rpc task failed");+ (is_agent_rpc_response_error(error) || is_local_agent_failure).then(|| agent_error_from_legacy(error, None))+}++pub(crate) fn agent_recovery_decision(error: &str, scope: RecoveryScope) -> RecoveryDecision {+ RecoveryPolicy::decide(&agent_error_from_legacy(error, None), scope)+}++impl AgentCallError {+ pub fn into_legacy_string(self) -> String {+ match self {+ Self::Structured { rpc_code, message, context } => {+ let data = serde_json::json!({+ "contractVersion": context.contract_version,+ "category": category_name(context.category),+ "retryable": context.retryable,+ "sessionDisposition": context.session_disposition.as_str(),+ "stage": stage_name(context.stage),+ "operationOutcome": outcome_name(context.operation_outcome),+ "agentSessionId": context.agent_session_id,+ "sqlState": context.sql_state,+ "vendorCode": context.vendor_code,+ "exceptionClass": context.exception_class,+ });+ format_agent_rpc_error_parts(rpc_code, &message, Some(&data))+ }+ Self::Legacy { rpc_code, message, hints } => {+ let data = serde_json::json!({+ "category": hints.category.map(category_name),+ "retryable": hints.retryable,+ "sessionDisposition": hints.session_disposition.map(|value| value.as_str()),+ "stage": hints.stage.map(stage_name),+ "operationOutcome": hints.operation_outcome.map(outcome_name),+ "agentSessionId": hints.agent_session_id,+ });+ format_agent_rpc_error_parts(rpc_code.unwrap_or(-1), &message, Some(&data))+ }+ Self::ContractViolation { rpc_code, message, .. } => format_agent_rpc_error_parts(+ rpc_code.unwrap_or(-1),+ &message,+ Some(&serde_json::json!({ "contractVersion": 1 })),+ ),+ Self::Transport { message } => message,+ Self::Timeout { stage, .. } => format!("Agent RPC call timed out at {}", stage_name(stage)),+ Self::Canceled { .. } => "Query canceled".to_string(),+ }+ }++ fn into_legacy_string_with_session_id(self, agent_session_id: Option<&str>) -> String {+ let has_session_id = self.session_id().is_some();+ let message = self.into_legacy_string();+ match (has_session_id, agent_session_id) {+ (false, Some(agent_session_id)) => append_legacy_agent_session_id(&message, agent_session_id),+ _ => message,+ }+ }++ pub fn session_id(&self) -> Option<&str> {+ match self {+ Self::Structured { context, .. } => context.agent_session_id.as_deref(),+ Self::Legacy { hints, .. } => hints.agent_session_id.as_deref(),+ _ => None,+ }+ }++ pub fn session_disposition(&self) -> Option<AgentSessionDisposition> {+ match self {+ Self::Structured { context, .. } => Some(context.session_disposition),+ Self::Legacy { hints, .. } => hints.session_disposition,+ _ => None,+ }+ }++ pub fn category(&self) -> Option<AgentErrorCategory> {+ match self {+ Self::Structured { context, .. } => Some(context.category),+ Self::Legacy { hints, .. } => hints.category,+ Self::Timeout { .. } => Some(AgentErrorCategory::Timeout),+ Self::Canceled { .. } => Some(AgentErrorCategory::Canceled),+ Self::ContractViolation { .. } | Self::Transport { .. } => None,+ }+ }++ pub fn operation_outcome(&self) -> AgentOperationOutcome {+ match self {+ Self::Structured { context, .. } => context.operation_outcome,+ Self::Legacy { hints, .. } => hints.operation_outcome.unwrap_or(AgentOperationOutcome::Unknown),+ Self::Timeout { operation_outcome, .. } | Self::Canceled { operation_outcome, .. } => *operation_outcome,+ Self::ContractViolation { .. } | Self::Transport { .. } => AgentOperationOutcome::Unknown,+ }+ }++ fn with_legacy_session_id(mut self, agent_session_id: Option<&str>) -> Self {+ if let (Self::Legacy { hints, .. }, Some(agent_session_id)) = (&mut self, agent_session_id) {+ hints.agent_session_id.get_or_insert_with(|| agent_session_id.to_string());+ }+ self}- formatted}-fn agent_rpc_error_data(error: &str) -> Option<Value> {- let (_, data) = error.rsplit_once(AGENT_RPC_ERROR_DATA_MARKER)?;- serde_json::from_str(data).ok()+fn append_legacy_agent_session_id(error: &str, agent_session_id: &str) -> String {+ if let Some((header, data)) = error.rsplit_once(AGENT_RPC_ERROR_DATA_MARKER) {+ if let Some((mut data, suffix)) = parse_legacy_agent_error_data(data) {+ if let Some(object) = data.as_object_mut() {+ object.insert("agentSessionId".to_string(), Value::String(agent_session_id.to_string()));+ return format!("{header}{AGENT_RPC_ERROR_DATA_MARKER}{data}{suffix}");+ }+ }+ }+ format!("{error}{AGENT_RPC_ERROR_DATA_MARKER}{}", serde_json::json!({ "agentSessionId": agent_session_id }))}-fn with_agent_rpc_error_session_id(error: String, agent_session_id: Option<&str>) -> String {- let Some(agent_session_id) = agent_session_id else {- return error;+impl fmt::Display for AgentCallError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Structured { message, .. } | Self::Legacy { message, .. } => f.write_str(message),+ Self::ContractViolation { message, .. } => write!(f, "Agent error contract violation: {message}"),+ Self::Transport { message } => f.write_str(message),+ Self::Timeout { stage, .. } => write!(f, "Agent RPC call timed out at {}", stage_name(*stage)),+ Self::Canceled { .. } => f.write_str("Query canceled"),+ }+ }+}++impl From<AgentCallError> for String {+ fn from(error: AgentCallError) -> Self {+ error.into_legacy_string()+ }+}++impl From<String> for AgentCallError {+ fn from(message: String) -> Self {+ Self::Transport { message }+ }+}++impl From<&str> for AgentCallError {+ fn from(message: &str) -> Self {+ Self::Transport { message: message.to_string() }+ }+}++fn parse_agent_call_error(+ error: &Value,+ strict_structured_errors: bool,+ expected_session_id: Option<&str>,+) -> AgentCallError {+ let rpc_code = error.get("code").and_then(Value::as_i64);+ let message = error.get("message").and_then(Value::as_str).unwrap_or("Unknown agent error").to_string();+ let data = error.get("data");++ if !strict_structured_errors {+ return AgentCallError::Legacy { rpc_code, message, hints: data.map(legacy_agent_hints).unwrap_or_default() };+ }++ let Some(data) = data.filter(|value| value.is_object()) else {+ return AgentCallError::ContractViolation {+ rpc_code,+ message,+ reason: ContractViolationReason::MissingContractVersion,+ };};- let Some((message, data)) = error.rsplit_once(AGENT_RPC_ERROR_DATA_MARKER) else {- return format!(- "{error}{AGENT_RPC_ERROR_DATA_MARKER}{}",- serde_json::json!({ "agentSessionId": agent_session_id })- );+ match parse_structured_error_context(data, expected_session_id) {+ Ok(context) => AgentCallError::Structured { rpc_code: rpc_code.unwrap_or(-1), message, context },+ Err(reason) => AgentCallError::ContractViolation { rpc_code, message, reason },+ }+}++fn parse_structured_error_context(+ data: &Value,+ expected_session_id: Option<&str>,+) -> Result<AgentErrorContext, ContractViolationReason> {+ let Some(contract_version_value) = data.get("contractVersion") else {+ return Err(ContractViolationReason::MissingContractVersion);};- let Ok(mut data) = serde_json::from_str::<Value>(data) else {- return format!(- "{error}{AGENT_RPC_ERROR_DATA_MARKER}{}",- serde_json::json!({ "agentSessionId": agent_session_id })- );+ let Some(contract_version) = contract_version_value.as_u64() else {+ return Err(ContractViolationReason::InvalidDataShape);+ };+ if contract_version != 1 {+ return Err(ContractViolationReason::UnsupportedContractVersion);+ }+ let context = serde_json::from_value::<AgentErrorContext>(data.clone())+ .map_err(|_| ContractViolationReason::InvalidDataShape)?;+ if context.contract_version != 1 {+ return Err(ContractViolationReason::UnsupportedContractVersion);+ }+ if let Some(expected_session_id) = expected_session_id {+ if context.agent_session_id.as_deref() != Some(expected_session_id) {+ return Err(ContractViolationReason::InvalidSessionId);+ }+ }+ if !valid_agent_error_combination(&context) {+ return Err(ContractViolationReason::InvalidCombination);+ }+ Ok(context)+}++fn legacy_agent_hints(data: &Value) -> LegacyAgentHints {+ LegacyAgentHints {+ category: data.get("category").and_then(|value| serde_json::from_value(value.clone()).ok()),+ retryable: data.get("retryable").and_then(Value::as_bool),+ session_disposition: match data.get("sessionDisposition").and_then(Value::as_str) {+ Some("keep") => Some(AgentSessionDisposition::Keep),+ Some("quarantine") => Some(AgentSessionDisposition::Quarantine),+ Some("replace_runtime") => Some(AgentSessionDisposition::ReplaceRuntime),+ _ => None,+ },+ stage: data.get("stage").and_then(|value| serde_json::from_value(value.clone()).ok()),+ operation_outcome: data.get("operationOutcome").and_then(|value| serde_json::from_value(value.clone()).ok()),+ agent_session_id: data.get("agentSessionId").and_then(Value::as_str).map(str::to_string),+ }+}++pub(crate) fn valid_agent_error_combination(context: &AgentErrorContext) -> bool {+ let expected_outcome = match context.stage {+ AgentErrorStage::Request | AgentErrorStage::Checkout | AgentErrorStage::Connect | AgentErrorStage::Validate => {+ AgentOperationOutcome::NotStarted+ }+ AgentErrorStage::Execute | AgentErrorStage::Fetch | AgentErrorStage::Cancel | AgentErrorStage::Close => {+ AgentOperationOutcome::Unknown+ }};- let Some(data) = data.as_object_mut() else {- return error;+ if context.operation_outcome != expected_outcome {+ return false;+ }+ let valid_disposition = match context.category {+ AgentErrorCategory::Connection => context.session_disposition != AgentSessionDisposition::ReplaceRuntime,+ AgentErrorCategory::Sql => {+ matches!(+ context.stage,+ AgentErrorStage::Execute | AgentErrorStage::Fetch | AgentErrorStage::Cancel | AgentErrorStage::Close+ ) && context.session_disposition != AgentSessionDisposition::ReplaceRuntime+ }+ AgentErrorCategory::Resource => {+ context.session_disposition == AgentSessionDisposition::ReplaceRuntime+ || context.operation_outcome == AgentOperationOutcome::NotStarted+ }+ AgentErrorCategory::Protocol => {+ context.session_disposition != AgentSessionDisposition::ReplaceRuntime+ || context.operation_outcome == AgentOperationOutcome::Unknown+ }+ AgentErrorCategory::Timeout | AgentErrorCategory::Canceled => {+ context.session_disposition == AgentSessionDisposition::Quarantine+ }};- data.insert("agentSessionId".to_string(), Value::String(agent_session_id.to_string()));- format!("{message}{AGENT_RPC_ERROR_DATA_MARKER}{}", Value::Object(data.clone()))+ if !valid_disposition {+ return false;+ }+ valid_ascii_diagnostic(context.sql_state.as_deref(), 16)+ && valid_ascii_diagnostic(context.exception_class.as_deref(), 160)+ && context.agent_session_id.as_deref().is_none_or(valid_ascii_identifier)+}++fn valid_ascii_diagnostic(value: Option<&str>, max_length: usize) -> bool {+ value.is_none_or(|value| {+ !value.is_empty() && value.len() <= max_length && value.bytes().all(|byte| byte.is_ascii_graphic())+ })+}++fn valid_ascii_identifier(value: &str) -> bool {+ !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_graphic())+}++pub(crate) fn category_name(category: AgentErrorCategory) -> &'static str {+ match category {+ AgentErrorCategory::Connection => "connection",+ AgentErrorCategory::Sql => "sql",+ AgentErrorCategory::Resource => "resource",+ AgentErrorCategory::Protocol => "protocol",+ AgentErrorCategory::Timeout => "timeout",+ AgentErrorCategory::Canceled => "canceled",+ }+}++pub(crate) fn stage_name(stage: AgentErrorStage) -> &'static str {+ match stage {+ AgentErrorStage::Request => "request",+ AgentErrorStage::Checkout => "checkout",+ AgentErrorStage::Connect => "connect",+ AgentErrorStage::Validate => "validate",+ AgentErrorStage::Execute => "execute",+ AgentErrorStage::Fetch => "fetch",+ AgentErrorStage::Cancel => "cancel",+ AgentErrorStage::Close => "close",+ }+}++pub(crate) fn outcome_name(outcome: AgentOperationOutcome) -> &'static str {+ match outcome {+ AgentOperationOutcome::NotStarted => "not_started",+ AgentOperationOutcome::Unknown => "unknown",+ }+}++fn agent_error_stage(method: &str) -> AgentErrorStage {+ match method {+ "handshake" => AgentErrorStage::Request,+ "connect" | "open_session" | "test_connection" => AgentErrorStage::Connect,+ "validate_connection" | "validate_session" => AgentErrorStage::Validate,+ "cancel_session" => AgentErrorStage::Cancel,+ "close_session" | "disconnect" | "shutdown" | "close_query_session" | "close_table_read_session" => {+ AgentErrorStage::Close+ }+ "fetch_query_page" | "fetch_table_read_page" => AgentErrorStage::Fetch,+ _ => AgentErrorStage::Execute,+ }+}++fn agent_operation_outcome(method: &str) -> AgentOperationOutcome {+ match agent_error_stage(method) {+ AgentErrorStage::Request | AgentErrorStage::Checkout | AgentErrorStage::Connect | AgentErrorStage::Validate => {+ AgentOperationOutcome::NotStarted+ }+ _ => AgentOperationOutcome::Unknown,+ }+}++fn format_agent_rpc_error(error: &Value) -> String {+ let message = error.get("message").and_then(Value::as_str).unwrap_or("Unknown agent error");+ let code = error.get("code").and_then(Value::as_i64).unwrap_or(-1);+ format_agent_rpc_error_parts(code, message, error.get("data").filter(|data| data.is_object()))+}++fn format_agent_rpc_error_parts(code: i64, message: &str, data: Option<&Value>) -> String {+ let mut formatted = format!("Agent RPC error ({code}): {message}");+ if let Some(data) = data {+ formatted.push_str(AGENT_RPC_ERROR_DATA_MARKER);+ formatted.push_str(&data.to_string());+ }+ formatted}fn deserialize_cached_agent_result<T: DeserializeOwned>(result: Result<Value, String>) -> Result<T, String> {@@ -519,10 +972,88 @@ pub enum AgentCapability {EtcdLease,EtcdAuth,MultiSession,+ StructuredErrorV1,+}++pub(crate) fn legacy_agent_call_error(error: String, agent_session_id: Option<&str>) -> AgentCallError {+ if !is_agent_rpc_response_error(&error) {+ return AgentCallError::Transport { message: error };+ }+ let (header, data, suffix) =+ error.rsplit_once(AGENT_RPC_ERROR_DATA_MARKER).map_or((error.as_str(), None, ""), |(header, data)| {+ match parse_legacy_agent_error_data(data) {+ Some((data, suffix)) => (header, Some(data), suffix),+ None => (header, None, ""),+ }+ });+ let header_with_suffix = (!suffix.is_empty()).then(|| format!("{header}{suffix}"));+ let header = header_with_suffix.as_deref().unwrap_or(header);+ let (rpc_code, message) = parse_agent_rpc_error_header(header);+ if let Some(data) = data.as_ref().filter(|data| data.get("contractVersion").is_some()) {+ return match parse_structured_error_context(data, agent_session_id) {+ Ok(context) => AgentCallError::Structured { rpc_code: rpc_code.unwrap_or(-1), message, context },+ Err(reason) => AgentCallError::ContractViolation { rpc_code, message, reason },+ };+ }+ let mut hints = data.as_ref().map(legacy_agent_hints).unwrap_or_default();+ if hints.category.is_none() && is_legacy_connection_message(&message) {+ hints.category = Some(AgentErrorCategory::Connection);+ hints.session_disposition.get_or_insert(AgentSessionDisposition::Quarantine);+ }+ AgentCallError::Legacy { rpc_code, message, hints }.with_legacy_session_id(agent_session_id)+}++fn parse_legacy_agent_error_data(data: &str) -> Option<(Value, &str)> {+ let mut values = serde_json::Deserializer::from_str(data).into_iter::<Value>();+ let value = values.next()?.ok()?;+ Some((value, &data[values.byte_offset()..]))+}++pub(crate) fn append_legacy_error_context(error: &str, context: &str) -> String {+ if error.contains(context) {+ return error.to_string();+ }+ if let Some((header, data)) = error.rsplit_once(AGENT_RPC_ERROR_DATA_MARKER) {+ return format!("{header}\n{context}{AGENT_RPC_ERROR_DATA_MARKER}{data}");+ }+ format!("{error}\n{context}")+}++fn is_legacy_connection_message(message: &str) -> bool {+ let lower = message.to_ascii_lowercase();+ [+ "connection lost",+ "connection reset",+ "broken pipe",+ "communications link failure",+ "sqlrecoverableexception",+ "sqlnontransientconnectionexception",+ "sqltransientconnectionexception",+ "network communication",+ "网络通信异常",+ "通信异常",+ "关闭的连接",+ "连接已关闭",+ "not connected",+ "end of stream",+ "end-of-file",+ ]+ .iter()+ .any(|marker| lower.contains(marker))+}++fn parse_agent_rpc_error_header(header: &str) -> (Option<i64>, String) {+ let Some(rest) = header.strip_prefix("Agent RPC error (") else {+ return (None, header.to_string());+ };+ let Some((code, message)) = rest.split_once("): ") else {+ return (None, header.to_string());+ };+ (code.parse().ok(), message.to_string())}impl AgentCapability {- pub const ALL: [Self; 19] = [+ pub const ALL: [Self; 20] = [Self::Connect,Self::TestConnection,Self::Metadata,@@ -542,6 +1073,7 @@ impl AgentCapability {Self::EtcdLease,Self::EtcdAuth,Self::MultiSession,+ Self::StructuredErrorV1,];pub fn as_str(self) -> &'static str {@@ -565,6 +1097,7 @@ impl AgentCapability {Self::EtcdLease => "etcd_lease",Self::EtcdAuth => "etcd_auth",Self::MultiSession => "multi_session",+ Self::StructuredErrorV1 => "structured_error_v1",}}}@@ -1018,7 +1551,18 @@ impl AgentDriverClient {method: &str,params: Value,) -> Result<T, String> {- self.call_with_timeout(method, params, Some(Duration::from_secs(RPC_TIMEOUT_SECS))).await+ let agent_session_id = self.agent_session_id.clone();+ self.call_typed(method, params)+ .await+ .map_err(|error| error.into_legacy_string_with_session_id(agent_session_id.as_deref()))+ }++ pub async fn call_typed<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: &str,+ params: Value,+ ) -> Result<T, AgentCallError> {+ self.call_typed_with_timeout(method, params, Some(Duration::from_secs(RPC_TIMEOUT_SECS))).await}/// Send a JSON-RPC 2.0 request and wait for the response.@@ -1029,7 +1573,19 @@ impl AgentDriverClient {params: Value,timeout_duration: Option<Duration>,) -> Result<T, String> {- self.call_with_timeout_and_cancel(method, params, timeout_duration, None).await+ let agent_session_id = self.agent_session_id.clone();+ self.call_typed_with_timeout(method, params, timeout_duration)+ .await+ .map_err(|error| error.into_legacy_string_with_session_id(agent_session_id.as_deref()))+ }++ pub async fn call_typed_with_timeout<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: &str,+ params: Value,+ timeout_duration: Option<Duration>,+ ) -> Result<T, AgentCallError> {+ self.call_typed_with_timeout_and_cancel(method, params, timeout_duration, None).await}/// Send a JSON-RPC 2.0 request and wait for the response.@@ -1042,6 +1598,19 @@ impl AgentDriverClient {timeout_duration: Option<Duration>,cancel_token: Option<CancellationToken>,) -> Result<T, String> {+ let agent_session_id = self.agent_session_id.clone();+ self.call_typed_with_timeout_and_cancel(method, params, timeout_duration, cancel_token)+ .await+ .map_err(|error| error.into_legacy_string_with_session_id(agent_session_id.as_deref()))+ }++ pub async fn call_typed_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: &str,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {if let Some(runtime) = &self.shared_runtime {let agent_session_id = self.agent_session_id.clone();let mut params = params;@@ -1056,9 +1625,9 @@ impl AgentDriverClient {.insert("agentSessionId".to_string(), Value::String(session_id.clone()));}return runtime- .call(method, params, timeout_duration, cancel_token)+ .call_typed(method, params, timeout_duration, cancel_token).await- .map_err(|error| with_agent_rpc_error_session_id(error, agent_session_id.as_deref()));+ .map_err(|error| error.with_legacy_session_id(agent_session_id.as_deref()));}self.next_id += 1;let id = self.next_id;@@ -1084,7 +1653,7 @@ impl AgentDriverClient {.and_then(|_| writer.flush().map_err(|e| format!("Failed to flush agent stdin: {e}")))};if let Err(e) = write_result {- return Err(self.format_agent_process_error(&e));+ return Err(AgentCallError::Transport { message: self.format_agent_process_error(&e) });}// Read response from stdout (blocking, with timeout)@@ -1120,13 +1689,19 @@ impl AgentDriverClient {biased;_ = token.cancelled() => {self.kill();- return Err("Query canceled".to_string());+ return Err(AgentCallError::Canceled {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ });}result = tokio::time::timeout(duration, response_task) => match result {Ok(result) => result,Err(_) => {self.kill();- return Err(format!("Agent RPC call timed out ({}s)", duration.as_secs()));+ return Err(AgentCallError::Timeout {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ });}},}@@ -1135,7 +1710,10 @@ impl AgentDriverClient {Ok(result) => result,Err(_) => {self.kill();- return Err(format!("Agent RPC call timed out ({}s)", duration.as_secs()));+ return Err(AgentCallError::Timeout {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ });}},(None, Some(token)) => {@@ -1143,23 +1721,30 @@ impl AgentDriverClient {biased;_ = token.cancelled() => {self.kill();- return Err("Query canceled".to_string());+ return Err(AgentCallError::Canceled {+ stage: agent_error_stage(method),+ operation_outcome: agent_operation_outcome(method),+ });}result = response_task => result,}}(None, None) => response_task.await,}- .map_err(|e| format!("Agent RPC task failed: {e}"))?;+ .map_err(|e| AgentCallError::Transport { message: format!("Agent RPC task failed: {e}") })?;let _ = self.stdout.insert(returned_reader);- result.map_err(|error| {- if is_agent_rpc_response_error(&error) {- error- } else {- self.format_agent_process_error(&error)- }- })+ result+ .map_err(+ |error| {+ if is_agent_rpc_response_error(&error) {+ error+ } else {+ self.format_agent_process_error(&error)+ }+ },+ )+ .map_err(|error| legacy_agent_call_error(error, self.agent_session_id.as_deref()))}pub async fn call_method<T: DeserializeOwned + Send + 'static>(@@ -1170,6 +1755,14 @@ impl AgentDriverClient {self.call(method.as_str(), params).await}+ pub async fn call_method_typed<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: AgentMethod,+ params: Value,+ ) -> Result<T, AgentCallError> {+ self.call_typed(method.as_str(), params).await+ }+pub async fn call_method_with_timeout<T: DeserializeOwned + Send + 'static>(&mut self,method: AgentMethod,@@ -1179,6 +1772,15 @@ impl AgentDriverClient {self.call_with_timeout(method.as_str(), params, timeout_duration).await}+ pub async fn call_method_typed_with_timeout<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: AgentMethod,+ params: Value,+ timeout_duration: Option<Duration>,+ ) -> Result<T, AgentCallError> {+ self.call_typed_with_timeout(method.as_str(), params, timeout_duration).await+ }+pub async fn call_method_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(&mut self,method: AgentMethod,@@ -1189,6 +1791,16 @@ impl AgentDriverClient {self.call_with_timeout_and_cancel(method.as_str(), params, timeout_duration, cancel_token).await}+ pub async fn call_method_typed_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ method: AgentMethod,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {+ self.call_typed_with_timeout_and_cancel(method.as_str(), params, timeout_duration, cancel_token).await+ }+pub async fn connect(&mut self, params: Value) -> Result<Value, String> {self.call_method(AgentMethod::Connect, params).await}@@ -1226,6 +1838,14 @@ impl AgentDriverClient {self.call_method_with_timeout(AgentMethod::ValidateConnection, serde_json::json!({}), timeout_duration).await}+ pub async fn validate_connection_typed(+ &mut self,+ timeout_duration: Option<Duration>,+ ) -> Result<Value, AgentCallError> {+ self.call_method_typed_with_timeout(AgentMethod::ValidateConnection, serde_json::json!({}), timeout_duration)+ .await+ }+pub async fn connection_info(&mut self, timeout_duration: Option<Duration>) -> Result<AgentConnectionInfo, String> {self.call_method_with_timeout(AgentMethod::ConnectionInfo, serde_json::json!({}), timeout_duration).await}@@ -1552,6 +2172,15 @@ impl AgentDriverClient {self.call_method_with_timeout(AgentMethod::ExecuteQuery, params, timeout_duration).await}+ pub async fn execute_query_typed_with_timeout<T: DeserializeOwned + Send + 'static>(+ &mut self,+ params: Value,+ timeout_duration: Option<Duration>,+ ) -> Result<T, AgentCallError> {+ self.invalidate_cached_query();+ self.call_method_typed_with_timeout(AgentMethod::ExecuteQuery, params, timeout_duration).await+ }+pub async fn execute_query_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(&mut self,params: Value,@@ -1563,6 +2192,22 @@ impl AgentDriverClient {.await}+ pub async fn execute_query_typed_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {+ self.invalidate_cached_query();+ self.call_method_typed_with_timeout_and_cancel(+ AgentMethod::ExecuteQuery,+ params,+ timeout_duration,+ cancel_token,+ )+ .await+ }+pub async fn execute_query_cached_with_timeout<T: DeserializeOwned + Send + 'static>(&mut self,cache_key: String,@@ -1612,6 +2257,22 @@ impl AgentDriverClient {.await}+ pub async fn execute_query_page_typed_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {+ self.invalidate_cached_query();+ self.call_method_typed_with_timeout_and_cancel(+ AgentMethod::ExecuteQueryPage,+ params,+ timeout_duration,+ cancel_token,+ )+ .await+ }+pub async fn fetch_query_page<T: DeserializeOwned + Send + 'static>(&mut self, params: Value) -> Result<T, String> {self.call_method(AgentMethod::FetchQueryPage, params).await}@@ -1634,6 +2295,21 @@ impl AgentDriverClient {.await}+ pub async fn fetch_query_page_typed_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, AgentCallError> {+ self.call_method_typed_with_timeout_and_cancel(+ AgentMethod::FetchQueryPage,+ params,+ timeout_duration,+ cancel_token,+ )+ .await+ }+pub async fn get_explain_info<T: DeserializeOwned + Send + 'static>(&mut self, params: Value) -> Result<T, String> {self.call_method(AgentMethod::GetExplainInfo, params).await}@@ -1688,6 +2364,17 @@ impl AgentDriverClient {self.call_method(AgentMethod::ExecuteTransaction, agent_transaction_params(database, statements, schema)).await}+ pub async fn execute_transaction_typed<T: DeserializeOwned + Send + 'static>(+ &mut self,+ database: Option<&str>,+ statements: &[String],+ schema: Option<&str>,+ ) -> Result<T, AgentCallError> {+ self.invalidate_cached_query();+ self.call_method_typed(AgentMethod::ExecuteTransaction, agent_transaction_params(database, statements, schema))+ .await+ }+pub async fn execute_batch<T: DeserializeOwned + Send + 'static>(&mut self,database: Option<&str>,@@ -1704,6 +2391,22 @@ impl AgentDriverClient {.await}+ pub async fn execute_batch_typed<T: DeserializeOwned + Send + 'static>(+ &mut self,+ database: Option<&str>,+ statements: &[String],+ schema: Option<&str>,+ timeout_duration: Option<Duration>,+ ) -> Result<T, AgentCallError> {+ self.invalidate_cached_query();+ self.call_method_typed_with_timeout(+ AgentMethod::ExecuteBatch,+ agent_transaction_params(database, statements, schema),+ timeout_duration,+ )+ .await+ }+fn invalidate_cached_query(&mut self) {self.cached_query = None;}@@ -2348,17 +3051,19 @@ impl Drop for AgentDriverClient {#[cfg(test)]mod tests {use super::{- agent_close_query_session_params, agent_handshake_params, agent_java_args, agent_java_args_with_extra,- agent_java_args_with_extra_opts, agent_object_source_params, agent_proxy_env_vars, agent_rpc_error_category,- agent_rpc_error_session_id, agent_schema_params, agent_schema_table_params, agent_session_disposition,- agent_supports_capability, agent_transaction_params, decode_agent_response, format_agent_process_error,- format_agent_startup_error, is_agent_rpc_response_error, is_unsupported_handshake_error,- mongo_collection_params, mongo_database_params, mongo_document_id_params, parse_agent_java_opts,- read_agent_line, spawn_agent_process, start_stderr_collector, validate_dameng_java_system_properties,- AgentCapability, AgentDriverClient, AgentHandshake, AgentKvMethod, AgentLaunchSpec, AgentMethod,- AgentRuntimeClient, AgentSessionDisposition, AgentTableReadCloseParams, AgentTableReadPageParams,- AgentTableReadStartParams, MongoAgentMethod, StderrTail, AGENT_PROTOCOL_VERSION,+ agent_close_query_session_params, agent_error_from_legacy, agent_handshake_params, agent_java_args,+ agent_java_args_with_extra, agent_java_args_with_extra_opts, agent_object_source_params, agent_proxy_env_vars,+ agent_schema_params, agent_schema_table_params, agent_supports_capability, agent_transaction_params,+ append_legacy_error_context, decode_agent_response, format_agent_process_error, format_agent_startup_error,+ is_agent_rpc_response_error, is_unsupported_handshake_error, legacy_agent_call_error, mongo_collection_params,+ mongo_database_params, mongo_document_id_params, parse_agent_java_opts, read_agent_line, spawn_agent_process,+ start_stderr_collector, validate_dameng_java_system_properties, AgentCallError, AgentCapability,+ AgentDriverClient, AgentErrorCategory, AgentErrorContext, AgentErrorStage, AgentHandshake, AgentKvMethod,+ AgentLaunchSpec, AgentMethod, AgentOperationOutcome, AgentRuntimeClient, AgentSessionDisposition,+ AgentTableReadCloseParams, AgentTableReadPageParams, AgentTableReadStartParams, MongoAgentMethod, StderrTail,+ AGENT_PROTOCOL_VERSION,};+ use crate::agent_recovery::{RecoveryDecision, RecoveryPolicy, RecoveryScope};use std::io::Cursor;use std::io::Write;use std::process::{Command, Stdio};@@ -2404,6 +3109,26 @@ mod tests {fs::remove_dir_all(dir).unwrap();}+ fn test_python() -> &'static str {+ if cfg!(windows) {+ "python"+ } else {+ "python3"+ }+ }++ fn test_shell_command(unix_script: &str, windows_script: &str) -> Command {+ if cfg!(windows) {+ let mut command = Command::new("powershell");+ command.args(["-NoProfile", "-Command", windows_script]);+ command+ } else {+ let mut command = Command::new("sh");+ command.args(["-c", unix_script]);+ command+ }+ }+#[test]fn structured_agent_error_data_survives_legacy_string_boundary() {let response = serde_json::json!({@@ -2420,12 +3145,310 @@ mod tests {}});- let error = decode_agent_response::<serde_json::Value>(response).unwrap_err();+ let error = decode_agent_response::<serde_json::Value>(response, false, None).unwrap_err().into_legacy_string();assert!(error.starts_with("Agent RPC error (-1): connection lost"));- assert_eq!(agent_rpc_error_category(&error).as_deref(), Some("connection"));- assert_eq!(agent_rpc_error_session_id(&error).as_deref(), Some("session-generation-1"));- assert_eq!(agent_session_disposition(&error), Some(AgentSessionDisposition::Quarantine));+ let decoded = agent_error_from_legacy(&error, None);+ assert_eq!(decoded.category(), Some(AgentErrorCategory::Connection));+ assert_eq!(decoded.session_id(), Some("session-generation-1"));+ assert_eq!(decoded.session_disposition(), Some(AgentSessionDisposition::Quarantine));+ }++ #[test]+ fn strict_structured_error_requires_v1_and_preserves_diagnostics() {+ let response = serde_json::json!({+ "error": {+ "code": -6007,+ "message": "connection lost",+ "data": {+ "contractVersion": 1,+ "category": "connection",+ "retryable": false,+ "sessionDisposition": "quarantine",+ "stage": "execute",+ "operationOutcome": "unknown",+ "agentSessionId": "session-1",+ "sqlState": "08006",+ "vendorCode": -6007,+ "exceptionClass": "java.sql.SQLRecoverableException",+ "futureField": "allowed"+ }+ }+ });++ let error = decode_agent_response::<serde_json::Value>(response, true, Some("session-1")).unwrap_err();+ match error {+ AgentCallError::Structured { rpc_code, context, .. } => {+ assert_eq!(rpc_code, -6007);+ assert_eq!(context.contract_version, 1);+ assert_eq!(context.category, AgentErrorCategory::Connection);+ assert_eq!(context.stage, AgentErrorStage::Execute);+ assert_eq!(context.operation_outcome, AgentOperationOutcome::Unknown);+ assert_eq!(context.sql_state.as_deref(), Some("08006"));+ }+ other => panic!("expected structured error, got {other:?}"),+ }+ }++ #[test]+ fn strict_structured_error_keeps_identity_across_legacy_api_boundary() {+ let response = serde_json::json!({+ "error": {+ "code": -6007,+ "message": "connection lost",+ "data": {+ "contractVersion": 1,+ "category": "connection",+ "retryable": false,+ "sessionDisposition": "quarantine",+ "stage": "execute",+ "operationOutcome": "unknown",+ "agentSessionId": "session-1"+ }+ }+ });+ let legacy = decode_agent_response::<serde_json::Value>(response, true, Some("session-1"))+ .unwrap_err()+ .into_legacy_string();+ let legacy = append_legacy_error_context(&legacy, "SQL text omitted");++ assert!(matches!(agent_error_from_legacy(&legacy, Some("session-1")), AgentCallError::Structured { .. }));+ }++ #[test]+ fn contract_violation_keeps_identity_when_legacy_api_adds_session_id() {+ let legacy = AgentCallError::ContractViolation {+ rpc_code: Some(-6007),+ message: "invalid strict error".to_string(),+ reason: super::ContractViolationReason::InvalidDataShape,+ }+ .into_legacy_string_with_session_id(Some("session-1"));++ assert!(matches!(+ agent_error_from_legacy(&legacy, Some("session-1")),+ AgentCallError::ContractViolation { .. }+ ));+ assert_eq!(crate::backend_error::BackendError::from_legacy_string(&legacy).code(), "DBX-JDBC-5002");+ }++ #[test]+ fn legacy_adapter_preserves_strict_identity_when_old_callers_append_context() {+ let structured = AgentCallError::Structured {+ rpc_code: -6007,+ message: "connection lost".to_string(),+ context: AgentErrorContext {+ contract_version: 1,+ category: AgentErrorCategory::Connection,+ retryable: false,+ session_disposition: AgentSessionDisposition::Quarantine,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: None,+ vendor_code: None,+ exception_class: None,+ },+ };+ let suffixed = format!("{}: fallback failed", structured.into_legacy_string());+ assert!(matches!(agent_error_from_legacy(&suffixed, Some("session-1")), AgentCallError::Structured { .. }));++ let violation = AgentCallError::ContractViolation {+ rpc_code: Some(-6007),+ message: "invalid strict error".to_string(),+ reason: super::ContractViolationReason::InvalidDataShape,+ };+ let suffixed = format!("{}: fallback failed", violation.into_legacy_string());+ assert!(matches!(agent_error_from_legacy(&suffixed, None), AgentCallError::ContractViolation { .. }));+ assert_eq!(crate::backend_error::BackendError::from_legacy_string(&suffixed).code(), "DBX-JDBC-5002");+ }++ #[test]+ fn strict_structured_error_rejects_missing_fields_unknown_enums_and_session_mismatch() {+ let base = serde_json::json!({+ "contractVersion": 1,+ "category": "connection",+ "retryable": false,+ "sessionDisposition": "keep",+ "stage": "connect",+ "operationOutcome": "not_started",+ "agentSessionId": "session-1"+ });++ let missing = serde_json::json!({"error": {"message": "bad", "data": {"contractVersion": 1}}});+ assert!(matches!(+ decode_agent_response::<serde_json::Value>(missing, true, None).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidDataShape, .. }+ ));++ let mut unknown_enum = base.clone();+ unknown_enum["category"] = serde_json::json!("future");+ let response = serde_json::json!({"error": {"message": "bad", "data": unknown_enum}});+ assert!(matches!(+ decode_agent_response::<serde_json::Value>(response, true, None).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidDataShape, .. }+ ));++ let response = serde_json::json!({"error": {"message": "bad", "data": base}});+ assert!(matches!(+ decode_agent_response::<serde_json::Value>(response, true, Some("other")).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidSessionId, .. }+ ));+ }++ #[test]+ fn strict_structured_error_rejects_inconsistent_operation_outcome() {+ let response = serde_json::json!({+ "error": {+ "message": "bad",+ "data": {+ "contractVersion": 1,+ "category": "connection",+ "retryable": false,+ "sessionDisposition": "keep",+ "stage": "connect",+ "operationOutcome": "unknown"+ }+ }+ });++ assert!(matches!(+ decode_agent_response::<serde_json::Value>(response, true, None).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidCombination, .. }+ ));+ }++ #[test]+ fn strict_structured_error_rejects_dangerous_disposition_and_invalid_diagnostics() {+ let dangerous = serde_json::json!({+ "error": {+ "message": "bad",+ "data": {+ "contractVersion": 1,+ "category": "protocol",+ "retryable": false,+ "sessionDisposition": "replace_runtime",+ "stage": "request",+ "operationOutcome": "not_started"+ }+ }+ });+ assert!(matches!(+ decode_agent_response::<serde_json::Value>(dangerous, true, None).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidCombination, .. }+ ));++ let invalid_diagnostic = serde_json::json!({+ "error": {+ "message": "bad",+ "data": {+ "contractVersion": 1,+ "category": "sql",+ "retryable": false,+ "sessionDisposition": "keep",+ "stage": "execute",+ "operationOutcome": "unknown",+ "sqlState": "08\n006"+ }+ }+ });+ assert!(matches!(+ decode_agent_response::<serde_json::Value>(invalid_diagnostic, true, None).unwrap_err(),+ AgentCallError::ContractViolation { reason: super::ContractViolationReason::InvalidCombination, .. }+ ));+ }++ #[test]+ fn recovery_policy_never_replays_user_operations_and_retries_metadata_once() {+ let quarantined = AgentCallError::Structured {+ rpc_code: -1,+ message: "connection lost".to_string(),+ context: AgentErrorContext {+ contract_version: 1,+ category: AgentErrorCategory::Connection,+ retryable: true,+ session_disposition: AgentSessionDisposition::Quarantine,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: Some("08006".to_string()),+ vendor_code: None,+ exception_class: None,+ },+ };++ assert_eq!(+ RecoveryPolicy::decide(&quarantined, RecoveryScope::UserOperation),+ RecoveryDecision::QuarantineSession+ );+ assert_eq!(+ RecoveryPolicy::decide(&quarantined, RecoveryScope::ReadOnlyMetadata { retried: false }),+ RecoveryDecision::RetryReadOnlyMetadata+ );+ assert_eq!(+ RecoveryPolicy::decide(&quarantined, RecoveryScope::ReadOnlyMetadata { retried: true }),+ RecoveryDecision::QuarantineSession+ );+ }++ #[test]+ fn recovery_policy_is_conservative_for_runtime_local_and_legacy_failures() {+ let replace = AgentCallError::Structured {+ rpc_code: -1,+ message: "runtime saturated".to_string(),+ context: AgentErrorContext {+ contract_version: 1,+ category: AgentErrorCategory::Resource,+ retryable: false,+ session_disposition: AgentSessionDisposition::ReplaceRuntime,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: None,+ vendor_code: None,+ exception_class: None,+ },+ };+ assert_eq!(RecoveryPolicy::decide(&replace, RecoveryScope::Keepalive), RecoveryDecision::ReplaceRuntime);+ let structured_timeout = AgentCallError::Structured {+ rpc_code: -1,+ message: "timed out".to_string(),+ context: AgentErrorContext {+ contract_version: 1,+ category: AgentErrorCategory::Timeout,+ retryable: false,+ session_disposition: AgentSessionDisposition::Keep,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: None,+ vendor_code: None,+ exception_class: None,+ },+ };+ assert_eq!(+ RecoveryPolicy::decide(&structured_timeout, RecoveryScope::UserOperation),+ RecoveryDecision::QuarantineSession+ );+ assert_eq!(+ RecoveryPolicy::decide(+ &AgentCallError::Timeout {+ stage: AgentErrorStage::Connect,+ operation_outcome: AgentOperationOutcome::NotStarted,+ },+ RecoveryScope::UserOperation,+ ),+ RecoveryDecision::QuarantineSession+ );++ let legacy = legacy_agent_call_error(+ "Agent RPC error (-1): SQLRecoverableException: connection lost".to_string(),+ Some("legacy-session"),+ );+ assert_eq!(legacy.category(), Some(AgentErrorCategory::Connection));+ assert_eq!(+ RecoveryPolicy::decide(&legacy, RecoveryScope::ReadOnlyMetadata { retried: false }),+ RecoveryDecision::RetryReadOnlyMetadata+ );}#[test]@@ -2587,9 +3610,10 @@ mod tests {#[test]fn startup_error_waits_briefly_for_exit_status_and_stderr_tail() {- let mut child = Command::new("sh")- .arg("-c")- .arg("sleep 0.05; echo 'java.lang.UnsupportedClassVersionError: class file version 65.0' >&2; exit 1")+ let mut child = test_shell_command(+ "sleep 0.05; echo 'java.lang.UnsupportedClassVersionError: class file version 65.0' >&2; exit 1",+ "Start-Sleep -Milliseconds 50; [Console]::Error.WriteLine('java.lang.UnsupportedClassVersionError: class file version 65.0'); exit 1",+ ).stderr(Stdio::piped()).spawn().expect("child should start");@@ -2605,7 +3629,12 @@ mod tests {);assert!(message.contains("Failed to read startup line from agent: end of stream"));- assert!(message.contains("agent process exited with exit status: 1"));+ let expected_exit = if cfg!(windows) {+ "agent process exited with exit code: 1"+ } else {+ "agent process exited with exit status: 1"+ };+ assert!(message.contains(expected_exit), "unexpected message: {message}");assert!(message.contains("Agent requires Java 21"));assert!(message.contains("details: Failed to read startup line from agent: end of stream"));assert!(message.contains("UnsupportedClassVersionError"));@@ -2613,9 +3642,7 @@ mod tests {#[test]fn runtime_agent_process_error_does_not_wait_for_live_child() {- let child = Command::new("sh")- .arg("-c")- .arg("sleep 2")+ let child = test_shell_command("sleep 2", "Start-Sleep -Seconds 2").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())@@ -2755,7 +3782,9 @@ for line in sys.stdin:.await.unwrap_err();assert!(error.contains("Agent RPC call timed out"));- assert_eq!(agent_rpc_error_session_id(&error).as_deref(), Some("timeout-session"));+ let typed_error = agent_error_from_legacy(&error, None);+ assert_eq!(typed_error.category(), Some(AgentErrorCategory::Timeout));+ assert_eq!(typed_error.operation_outcome(), AgentOperationOutcome::Unknown);let started = Instant::now();client.call_with_timeout::<serde_json::Value>("probe", serde_json::json!({}), Some(Duration::from_millis(500)))@@ -2772,7 +3801,9 @@ for line in sys.stdin:.await.unwrap_err();assert!(error.contains("Agent RPC call timed out"));- assert_eq!(agent_rpc_error_session_id(&error).as_deref(), Some("timeout-session"));+ let typed_error = agent_error_from_legacy(&error, None);+ assert_eq!(typed_error.category(), Some(AgentErrorCategory::Timeout));+ assert_eq!(typed_error.operation_outcome(), AgentOperationOutcome::Unknown);let started = Instant::now();client.call_with_timeout::<serde_json::Value>("probe", serde_json::json!({}), Some(Duration::from_millis(500)))@@ -2962,7 +3993,7 @@ for line in sys.stdin:drop(script);let runtime = AgentRuntimeClient::spawn(- AgentLaunchSpec::new("python3").with_args([script_path.to_string_lossy().to_string()]),+ AgentLaunchSpec::new(test_python()).with_args([script_path.to_string_lossy().to_string()]),"test",).await@@ -2997,7 +4028,7 @@ for line in sys.stdin:.unwrap();let error = match AgentRuntimeClient::spawn(- AgentLaunchSpec::new("python3").with_args([script_path.to_string_lossy().to_string()]),+ AgentLaunchSpec::new(test_python()).with_args([script_path.to_string_lossy().to_string()]),"test",).await@@ -3063,7 +4094,10 @@ for line in sys.stdin:let error = client.disconnect().await.unwrap_err();- assert_eq!(agent_session_disposition(&error), Some(AgentSessionDisposition::ReplaceRuntime));+ assert_eq!(+ agent_error_from_legacy(&error, None).session_disposition(),+ Some(AgentSessionDisposition::ReplaceRuntime)+ );assert!(!runtime.is_failed());runtime.kill();drop(client);@@ -3090,7 +4124,7 @@ for line in sys.stdin:).unwrap();let runtime = AgentRuntimeClient::spawn(- AgentLaunchSpec::new("python3").with_args([script_path.to_string_lossy().to_string()]),+ AgentLaunchSpec::new(test_python()).with_args([script_path.to_string_lossy().to_string()]),"test",).await@@ -3140,7 +4174,7 @@ for line in sys.stdin:).unwrap();let runtime = AgentRuntimeClient::spawn(- AgentLaunchSpec::new("python3").with_args([script_path.to_string_lossy().to_string()]),+ AgentLaunchSpec::new(test_python()).with_args([script_path.to_string_lossy().to_string()]),"test",).await@@ -3209,7 +4243,8 @@ for line in sys.stdin:assert_eq!(AgentCapability::EtcdLease.as_str(), "etcd_lease");assert_eq!(AgentCapability::EtcdAuth.as_str(), "etcd_auth");assert_eq!(AgentCapability::MultiSession.as_str(), "multi_session");- assert_eq!(AgentCapability::ALL.len(), 19);+ assert_eq!(AgentCapability::ALL.len(), 20);+ assert_eq!(AgentCapability::StructuredErrorV1.as_str(), "structured_error_v1");}#[test]@@ -3499,7 +4534,7 @@ for line in sys.stdin:string_array(&contract["allCapabilities"]),AgentCapability::ALL.iter().map(|method| method.as_str()).collect::<Vec<_>>());- assert_eq!(string_array(&contract["capabilities"]), default_sql_capabilities());+ assert_eq!(string_array(&contract["capabilities"]), multi_session_capabilities());assert_eq!(string_array(&contract["defaultSqlCapabilities"]), default_sql_capabilities());assert_eq!(string_array(&contract["commonMethods"]),@@ -3574,9 +4609,17 @@ for line in sys.stdin:AgentCapability::Transaction,AgentCapability::Ddl,AgentCapability::MultiSession,+ AgentCapability::StructuredErrorV1,].iter().map(|capability| capability.as_str()).collect()}++ fn multi_session_capabilities() -> Vec<&'static str> {+ default_sql_capabilities()+ .into_iter()+ .filter(|capability| *capability != AgentCapability::StructuredErrorV1.as_str())+ .collect()+ }}diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex f49b441a20..d2d1d470a5 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -5,6 +5,7 @@ pub mod agent_explain;pub mod agent_kv;pub mod agent_loop;pub mod agent_manager;+pub mod agent_recovery;pub mod agent_runtime;pub mod agent_service;pub mod agent_tools;@@ -15,6 +16,7 @@ pub mod ai_codex_cli;pub mod ai_effort;mod ai_model_filter;pub mod ai_pi_agent_cli;+pub mod backend_error;pub mod changelog;pub mod cloud_sync;pub mod config;diff --git a/crates/dbx-core/src/plugins.rs b/crates/dbx-core/src/plugins.rsindex 70f5d597a0..e56a3d27f8 100644--- a/crates/dbx-core/src/plugins.rs+++ b/crates/dbx-core/src/plugins.rs@@ -337,7 +337,7 @@ impl PluginDriverSession {process.child.id()}- #[cfg(test)]+ #[cfg(all(test, unix))]pub(crate) async fn start_for_test(plugin: InstalledPlugin,driver_id: String,@@ -513,10 +513,9 @@ fn resolve_plugin_executable(plugin_dir: &Path, executable: &str) -> PathBuf {#[cfg(test)]mod tests {- use super::{- read_decoded_plugin_response, read_plugin_line, InstalledPlugin, PluginDriverManifest, PluginDriverSession,- PluginManifest, PluginRuntimeEnv,- };+ use super::{read_decoded_plugin_response, read_plugin_line, InstalledPlugin, PluginManifest};+ #[cfg(unix)]+ use super::{PluginDriverManifest, PluginDriverSession, PluginRuntimeEnv};use std::path::PathBuf;use tokio::io::BufReader;diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 78cd941fc3..61c896c699 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -17,9 +17,11 @@ use std::time::Duration;use tokio::time::timeout;use tokio_util::sync::CancellationToken;+use crate::agent_recovery::{RecoveryDecision, RecoveryPolicy, RecoveryScope};use crate::connection::{AppState, PoolKind, TransactionSession, TxnConnection};use crate::database_capabilities;use crate::db;+use crate::db::agent_driver::{AgentCallError, AgentErrorStage, AgentOperationOutcome};use crate::models::connection::{ConnectionConfig, DatabaseType};use crate::query_execution_sql::is_write_sql;use crate::sql::{split_sql_batches, split_sql_statements};@@ -43,14 +45,100 @@ pub enum PoolErrorAction {ReconnectAndRetry,}-fn query_error_with_omitted_sql_context(error: &str, _sql: &str) -> String {- if error.contains(SQL_OMITTED_ERROR_CONTEXT) {- error.to_string()- } else {- format!("{error}\n{SQL_OMITTED_ERROR_CONTEXT}")+#[derive(Debug, Clone)]+pub enum QueryExecutionError {+ Agent(AgentCallError),+ Canceled { stage: AgentErrorStage, operation_outcome: AgentOperationOutcome },+ Timeout(String),+ Sql(String),+ Legacy(String),+}++impl QueryExecutionError {+ pub fn into_legacy_string(self) -> String {+ match self {+ Self::Agent(error) => error.into_legacy_string(),+ Self::Canceled { .. } => canceled_error(),+ Self::Timeout(error) => error,+ Self::Sql(error) => error,+ Self::Legacy(error) => error,+ }+ }++ pub fn into_backend_error(self) -> crate::backend_error::BackendError {+ match self {+ Self::Agent(error) => crate::backend_error::BackendError::from_agent_call_error(&error),+ Self::Canceled { stage, operation_outcome } => {+ crate::backend_error::BackendError::from_canceled(stage, operation_outcome)+ }+ Self::Timeout(error) => crate::backend_error::BackendError::from_timeout_detail(&error),+ Self::Sql(error) => crate::backend_error::BackendError::from_sql_detail(&error),+ Self::Legacy(error) => crate::backend_error::BackendError::from_legacy_string(&error),+ }+ }++ fn with_omitted_sql_context(self, sql: &str) -> Self {+ match self {+ Self::Agent(error) => Self::Agent(error),+ canceled @ Self::Canceled { .. } => canceled,+ Self::Timeout(error) => Self::Timeout(query_error_with_omitted_sql_context(&error, sql)),+ Self::Sql(error) => Self::Sql(query_error_with_omitted_sql_context(&error, sql)),+ Self::Legacy(error) => Self::Legacy(query_error_with_omitted_sql_context(&error, sql)),+ }+ }++ fn with_context(self, context: &str) -> Self {+ match self {+ Self::Agent(error) => Self::Agent(error),+ canceled @ Self::Canceled { .. } => canceled,+ Self::Timeout(error) => Self::Timeout(format!("{error}; {context}")),+ Self::Sql(error) => Self::Sql(format!("{error}; {context}")),+ Self::Legacy(error) => Self::Legacy(format!("{error}; {context}")),+ }+ }++ fn as_agent_error(&self) -> Option<&AgentCallError> {+ match self {+ Self::Agent(error) => Some(error),+ Self::Canceled { .. } | Self::Timeout(_) | Self::Sql(_) | Self::Legacy(_) => None,+ }+ }+}++impl std::fmt::Display for QueryExecutionError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Agent(error) => error.fmt(formatter),+ Self::Canceled { .. } => formatter.write_str(QUERY_CANCELED),+ Self::Timeout(error) => formatter.write_str(error),+ Self::Sql(error) => formatter.write_str(error),+ Self::Legacy(error) => formatter.write_str(error),+ }+ }+}++impl From<AgentCallError> for QueryExecutionError {+ fn from(error: AgentCallError) -> Self {+ Self::Agent(error)+ }+}++impl From<String> for QueryExecutionError {+ fn from(error: String) -> Self {+ Self::Legacy(error)+ }+}++impl From<&str> for QueryExecutionError {+ fn from(error: &str) -> Self {+ Self::Legacy(error.to_string())}}+fn query_error_with_omitted_sql_context(error: &str, _sql: &str) -> String {+ crate::db::agent_driver::append_legacy_error_context(error, SQL_OMITTED_ERROR_CONTEXT)+}+/// A multi-statement result with metadata intended for query clients.////// `execution_error` is emitted for synthesized per-statement errors so clients@@ -64,9 +152,11 @@ pub struct ExecuteMultiResult {pub execution_error: bool,#[serde(skip_serializing_if = "Option::is_none")]pub statement_index: Option<usize>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<crate::backend_error::BackendError>,}-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq)]pub struct ExecuteMultiProgress {pub statement_index: usize,pub completed: usize,@@ -74,7 +164,7 @@ pub struct ExecuteMultiProgress {pub success: bool,pub execution_time_ms: u128,pub affected_rows: u64,- pub error: Option<String>,+ pub error: Option<crate::backend_error::BackendError>,}pub type ExecuteMultiProgressCallback = Arc<dyn Fn(ExecuteMultiProgress) + Send + Sync>;@@ -85,7 +175,7 @@ fn report_execute_multi_progress(total: usize,result: &db::QueryResult,success: bool,- error: Option<String>,+ error: Option<crate::backend_error::BackendError>,) {if let Some(progress) = progress {progress(ExecuteMultiProgress {@@ -102,15 +192,30 @@ fn report_execute_multi_progress(impl ExecuteMultiResult {fn execution_error(result: db::QueryResult) -> Self {- Self { result, execution_error: true, statement_index: None }+ let error = error_from_query_result(&result);+ Self { result, execution_error: true, statement_index: None, error }}fn execution_error_with_index(result: db::QueryResult, statement_index: usize) -> Self {- Self { result, execution_error: true, statement_index: Some(statement_index) }+ let error = error_from_query_result(&result);+ Self { result, execution_error: true, statement_index: Some(statement_index), error }+ }++ fn execution_error_with_backend(+ result: db::QueryResult,+ statement_index: Option<usize>,+ error: crate::backend_error::BackendError,+ ) -> Self {+ Self { result, execution_error: true, statement_index, error: Some(error) }}fn success_with_index(result: db::QueryResult, statement_index: usize) -> Self {- Self { result, execution_error: false, statement_index: Some(statement_index) }+ Self { result, execution_error: false, statement_index: Some(statement_index), error: None }+ }++ pub fn without_error_detail(mut self) -> Self {+ self.error = self.error.map(crate::backend_error::BackendError::without_detail);+ self}fn into_query_result(self) -> db::QueryResult {@@ -120,7 +225,7 @@ impl ExecuteMultiResult {impl From<db::QueryResult> for ExecuteMultiResult {fn from(result: db::QueryResult) -> Self {- Self { result, execution_error: false, statement_index: None }+ Self { result, execution_error: false, statement_index: None, error: None }}}@@ -128,6 +233,10 @@ fn is_false(value: &bool) -> bool {!*value}+fn error_from_query_result(result: &db::QueryResult) -> Option<crate::backend_error::BackendError> {+ result.rows.first()?.first()?.as_str().map(crate::backend_error::BackendError::from_legacy_string)+}+/// Unified database operation execution budget./// query_timeout = None only means SQL execution has no upper limit;/// checkout/connect/recycle/cancel/cleanup always have hard upper limits and cannot be disabled.@@ -545,9 +654,6 @@ pub fn agent_close_query_session_params(session_id: &str) -> serde_json::Value {}pub fn is_connection_error(err: &str) -> bool {- if crate::db::agent_driver::agent_rpc_error_category(err).as_deref() == Some("connection") {- return true;- }let lower = err.to_lowercase();if is_dbx_query_timeout_error(&lower) || is_agent_rpc_timeout_error(&lower) {return false;@@ -596,46 +702,23 @@ fn is_schema_reset_cleanup_error(lower: &str) -> bool {}fn should_discard_agent_pool_after_error(err: &str) -> bool {- if matches!(- crate::db::agent_driver::agent_session_disposition(err),- Some(- crate::db::agent_driver::AgentSessionDisposition::Quarantine- | crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime- )- ) {- return true;- }- let lower = err.to_lowercase();- is_dbx_query_timeout_error(&lower)- || is_agent_rpc_timeout_error(&lower)- || lower.contains("agent stdin not available")- || lower.contains("agent stdout not available")- || lower.contains("failed to write to agent stdin")- || lower.contains("failed to flush agent stdin")- || lower.contains("agent rpc task failed")+ crate::db::agent_driver::agent_recovery_decision(err, RecoveryScope::UserOperation).discards_session()}pub fn pool_error_action(db_type: Option<DatabaseType>, err: &str) -> PoolErrorAction {- if db_type.is_some_and(|db_type| database_capabilities::is_agent_type(&db_type))- && matches!(- crate::db::agent_driver::agent_session_disposition(err),- Some(- crate::db::agent_driver::AgentSessionDisposition::Quarantine- | crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime- )- )- {- // The connection may be replaced, but the result of the user operation is unknown.- // Discard the session without replaying SQL, DDL, writes, or transactions.- return PoolErrorAction::Discard;+ if db_type.is_some_and(|db_type| database_capabilities::is_agent_type(&db_type)) {+ return if should_discard_agent_pool_after_error(err) {+ // Agent user operations are never replayed from an error hint because+ // the database-side outcome may be unknown.+ PoolErrorAction::Discard+ } else {+ PoolErrorAction::Keep+ };}let lower = err.to_lowercase();if db::sqlserver::is_driver_panic_error(err)|| (is_dbx_query_timeout_error(&lower) && should_discard_pool_after_query_timeout(db_type))|| is_schema_reset_cleanup_error(&lower)- || (db_type.is_some_and(|db_type| database_capabilities::is_agent_type(&db_type))- && should_discard_agent_pool_after_error(err)- && !is_connection_error(err)){return PoolErrorAction::Discard;}@@ -714,10 +797,8 @@ async fn discard_pool_after_error(state: &AppState, pool_key: &str, db_type: Optreturn;}- let replace_agent_runtime = matches!(- crate::db::agent_driver::agent_session_disposition(error),- Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime)- );+ let replace_agent_runtime = db_type.is_some_and(|db_type| database_capabilities::is_agent_type(&db_type))+ && crate::db::agent_driver::agent_recovery_decision(error, RecoveryScope::UserOperation).replaces_runtime();if replace_agent_runtime {state.detach_pool_by_key(pool_key, true).await;} else {@@ -725,22 +806,25 @@ async fn discard_pool_after_error(state: &AppState, pool_key: &str, db_type: Opt}}-async fn discard_agent_pool_after_error(+async fn discard_agent_pool_after_typed_error(state: &AppState,pool_key: &str,client: &Arc<crate::db::agent_driver::PooledAgentClient>,- db_type: Option<DatabaseType>,- error: &str,+ error: &AgentCallError,+ scope: RecoveryScope,) {- let action = pool_error_action(db_type, error);- if !matches!(action, PoolErrorAction::Discard | PoolErrorAction::ReconnectAndRetry) {- return;+ discard_agent_pool_after_decision(state, pool_key, client, RecoveryPolicy::decide(error, scope)).await;+}++async fn discard_agent_pool_after_decision(+ state: &AppState,+ pool_key: &str,+ client: &Arc<crate::db::agent_driver::PooledAgentClient>,+ decision: RecoveryDecision,+) {+ if decision.discards_session() {+ state.detach_agent_pool_if_current(pool_key, client, decision.replaces_runtime()).await;}- let replace_agent_runtime = matches!(- crate::db::agent_driver::agent_session_disposition(error),- Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime)- );- state.detach_agent_pool_if_current(pool_key, client, replace_agent_runtime).await;}fn query_pool_error_action(db_type: Option<DatabaseType>, sql: &str, err: &str) -> PoolErrorAction {@@ -753,6 +837,27 @@ fn query_pool_error_action(db_type: Option<DatabaseType>, sql: &str, err: &str)}}+fn query_execution_error_action(+ db_type: Option<DatabaseType>,+ sql: &str,+ error: &QueryExecutionError,+) -> PoolErrorAction {+ if let Some(agent_error) = error.as_agent_error() {+ return if RecoveryPolicy::decide(agent_error, RecoveryScope::UserOperation).discards_session() {+ PoolErrorAction::Discard+ } else {+ PoolErrorAction::Keep+ };+ }+ match error {+ QueryExecutionError::Canceled { .. } => PoolErrorAction::Keep,+ QueryExecutionError::Timeout(message)+ | QueryExecutionError::Sql(message)+ | QueryExecutionError::Legacy(message) => query_pool_error_action(db_type, sql, message),+ QueryExecutionError::Agent(_) => unreachable!("Agent errors return above"),+ }+}+fn is_os_connection_error(lower: &str) -> bool {let os_error_codes = ["10053", "10054", "10057", "10058", "10060", "10061"];if let Some(pos) = lower.find("os error ") {@@ -776,6 +881,36 @@ pub fn canceled_error() -> String {QUERY_CANCELED.to_string()}+fn canceled_query_execution_error() -> QueryExecutionError {+ QueryExecutionError::Canceled { stage: AgentErrorStage::Cancel, operation_outcome: AgentOperationOutcome::Unknown }+}++fn pre_dispatch_canceled_query_execution_error() -> QueryExecutionError {+ QueryExecutionError::Canceled {+ stage: AgentErrorStage::Request,+ operation_outcome: AgentOperationOutcome::NotStarted,+ }+}++fn postgres_transaction_statement_error(+ statement_index: usize,+ message: &str,+ sql: &str,+ is_server_error: bool,+) -> QueryExecutionError {+ let detail = query_error_with_omitted_sql_context(&format!("Statement {statement_index} failed: {message}"), sql);+ let lower = message.to_ascii_lowercase();+ if is_dbx_query_timeout_error(&lower) {+ QueryExecutionError::Timeout(detail)+ } else if message == QUERY_CANCELED {+ canceled_query_execution_error()+ } else if is_server_error {+ QueryExecutionError::Sql(detail)+ } else {+ QueryExecutionError::Legacy(detail)+ }+}+pub(crate) struct StreamProgressClock {started_at: tokio::time::Instant,last_progress_ms: AtomicU64,@@ -1035,7 +1170,7 @@ async fn apply_oceanbase_mysql_session_timeout(}#[allow(clippy::too_many_arguments)]-pub async fn do_execute(+async fn do_execute_typed(state: &AppState,pool_key: &str,mysql_dialect: db::mysql::MySqlQueryDialect,@@ -1044,7 +1179,7 @@ pub async fn do_execute(schema: Option<&str>,cancel_token: Option<CancellationToken>,options: QueryExecutionOptions,-) -> Result<db::QueryResult, String> {+) -> Result<db::QueryResult, QueryExecutionError> {crate::sql_diagnostics::debug_sql("do_execute", sql);if let Some(execution_id) = options.execution_id.as_deref() {state.running_queries.set_pool_key(execution_id, pool_key.to_string());@@ -1067,7 +1202,8 @@ pub async fn do_execute(let connections = state.connections.read().await;let pool = connections.get(pool_key).ok_or("Connection not found")?;- let result = match pool {+ let mut typed_agent_error = None;+ let result: Result<db::QueryResult, String> = match pool {#[cfg(feature = "duckdb-sidecar")]PoolKind::DuckDbWorker(client) => {let client = client.clone();@@ -1090,7 +1226,7 @@ pub async fn do_execute(}#[cfg(not(feature = "duckdb-sidecar"))]PoolKind::DuckDbWorker(_) => {- return Err("DuckDB worker support is not compiled in this build".to_string());+ return Err("DuckDB worker support is not compiled in this build".into());}PoolKind::Mysql(p, mode) => {let p = p.clone();@@ -1108,9 +1244,9 @@ pub async fn do_execute(Ok(conn) => conn,Err(err) if err == QUERY_CANCELED => {state.remove_pool_by_key(pool_key).await;- return Err(err);+ return Err(err.into());}- Err(err) => return Err(err),+ Err(err) => return Err(err.into()),};let connection_id = conn.id();if let Some(ref execution_id) = options.execution_id {@@ -1240,7 +1376,7 @@ pub async fn do_execute(let mut client = match cancel_token.as_ref() {Some(token) => tokio::select! {biased;- _ = token.cancelled() => return Err(canceled_error()),+ _ = token.cancelled() => return Err(canceled_error().into()),guard = client.lock() => guard,},None => client.lock().await,@@ -1342,7 +1478,7 @@ pub async fn do_execute(let rpc_timeout = query_timeout;drop(connections);if is_canceled(&cancel_token) {- return Err(canceled_error());+ return Err(canceled_error().into());}let cancel_for_agent = cancel_token.clone();let result = async move {@@ -1350,7 +1486,10 @@ pub async fn do_execute(Some(token) => {tokio::select! {biased;- _ = token.cancelled() => return Err(canceled_error()),+ _ = token.cancelled() => return Err(AgentCallError::Canceled {+ stage: AgentErrorStage::Cancel,+ operation_outcome: AgentOperationOutcome::Unknown,+ }),guard = client.lock() => guard,}}@@ -1358,28 +1497,35 @@ pub async fn do_execute(};if let Some(session_id) = options.result_session_id.as_deref() {let params = agent_fetch_query_page_params(session_id, options.page_size.unwrap_or(MAX_ROWS));- client.fetch_query_page_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone()).await+ client+ .fetch_query_page_typed_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone())+ .await} else if options.page_size.is_some() {let params = agent_execute_query_page_params(&sql, database.as_deref(), schema.as_deref(), options);client- .execute_query_page_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone())+ .execute_query_page_typed_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone()).await} else {let params = agent_execute_query_params(&sql, database.as_deref(), schema.as_deref(), options);- client.execute_query_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone()).await+ client+ .execute_query_typed_with_timeout_and_cancel(params, rpc_timeout, cancel_for_agent.clone())+ .await}}.await.map(|result| truncate_result_with_max_rows(result, max_rows));- if matches!(result.as_ref(), Err(err) if err == QUERY_CANCELED) {- state.detach_agent_pool_if_current(pool_key, &source_client, false).await;- }if let Err(err) = result.as_ref() {- if err != QUERY_CANCELED {- discard_agent_pool_after_error(state, pool_key, &source_client, pool_db_type, err).await;- }+ discard_agent_pool_after_typed_error(+ state,+ pool_key,+ &source_client,+ err,+ RecoveryScope::UserOperation,+ )+ .await;}- result+ typed_agent_error = result.as_ref().err().cloned();+ result.map_err(AgentCallError::into_legacy_string)}PoolKind::ExternalDriver { config, session, .. } => {let config = config.clone();@@ -1413,7 +1559,42 @@ pub async fn do_execute(}PoolKind::HBase(_) => Err("SQL execution is not supported for HBase connections".to_string()),};- result.map(normalize_query_result_for_js)+ result+ .map(normalize_query_result_for_js)+ .map_err(|error| {+ typed_agent_error.map_or_else(|| QueryExecutionError::Legacy(error), QueryExecutionError::Agent)+ })+ .map_err(|error| classify_query_error(pool_db_type, error))+}++fn classify_query_error(db_type: Option<DatabaseType>, error: QueryExecutionError) -> QueryExecutionError {+ match error {+ QueryExecutionError::Legacy(message) if message == QUERY_CANCELED => canceled_query_execution_error(),+ QueryExecutionError::Legacy(message) if is_dbx_query_timeout_error(&message.to_ascii_lowercase()) => {+ QueryExecutionError::Timeout(message)+ }+ QueryExecutionError::Legacy(message)+ if db_type == Some(DatabaseType::Postgres) && message.trim_start().starts_with("ERROR:") =>+ {+ QueryExecutionError::Sql(message)+ }+ other => other,+ }+}++pub async fn do_execute(+ state: &AppState,+ pool_key: &str,+ mysql_dialect: db::mysql::MySqlQueryDialect,+ database: Option<&str>,+ sql: &str,+ schema: Option<&str>,+ cancel_token: Option<CancellationToken>,+ options: QueryExecutionOptions,+) -> Result<db::QueryResult, String> {+ do_execute_typed(state, pool_key, mysql_dialect, database, sql, schema, cancel_token, options)+ .await+ .map_err(QueryExecutionError::into_legacy_string)}async fn invoke_external_driver_query_page(@@ -1501,7 +1682,7 @@ pub async fn execute_sql_statement(.await}-pub async fn execute_sql_statement_with_options(+pub async fn execute_sql_statement_with_options_typed(state: &AppState,connection_id: &str,database: &str,@@ -1509,13 +1690,13 @@ pub async fn execute_sql_statement_with_options(schema: Option<&str>,cancel_token: Option<CancellationToken>,options: QueryExecutionOptions,-) -> Result<db::QueryResult, String> {+) -> Result<db::QueryResult, QueryExecutionError> {// MongoDB connections use shell-style commands dispatched through the// frontend parser. Queries that fall through to the generic SQL executor// (e.g. typos) must be rejected before any pool/key creation so that// session-scoped pools do not leak MongoDB Clients and SSH tunnels.if connection_is_mongodb(state, connection_id).await {- return Err(MONGO_SHELL_COMMAND_HINT.to_string());+ return Err(MONGO_SHELL_COMMAND_HINT.into());}let db_type = connection_database_type(state, connection_id).await;@@ -1529,7 +1710,8 @@ pub async fn execute_sql_statement_with_options(if let Some(target_database) = postgres_drop_database_target(db_type, sql) {return execute_postgres_drop_database(state, connection_id, &target_database, sql, cancel_token, options)- .await;+ .await+ .map_err(Into::into);}// When a query tab has a client session, keep even database-less execution@@ -1542,18 +1724,27 @@ pub async fn execute_sql_statement_with_options(.map_err(|e| query_error_with_omitted_sql_context(&e, sql))?;if is_canceled(&cancel_token) {- return Err(canceled_error());+ return Err(pre_dispatch_canceled_query_execution_error());}let mysql_dialect = connection_mysql_query_dialect(state, connection_id).await;- let result =- do_execute(state, &pool_key, mysql_dialect, Some(database), sql, schema, cancel_token.clone(), options.clone())- .await;+ let result = do_execute_typed(+ state,+ &pool_key,+ mysql_dialect,+ Some(database),+ sql,+ schema,+ cancel_token.clone(),+ options.clone(),+ )+ .await;- let with_sql_context =- |r: Result<db::QueryResult, String>| r.map_err(|e| query_error_with_omitted_sql_context(&e, sql));+ let with_sql_context = |result: Result<db::QueryResult, QueryExecutionError>| {+ result.map_err(|error| error.with_omitted_sql_context(sql))+ };- let action = result.as_ref().err().map(|e| query_pool_error_action(db_type, sql, e));+ let action = result.as_ref().err().map(|error| query_execution_error_action(db_type, sql, error));match action {Some(PoolErrorAction::ReconnectAndRetry) if !is_canceled(&cancel_token) => {let pool_database = query_pool_database(database, options.catalog.as_deref());@@ -1562,7 +1753,8 @@ pub async fn execute_sql_statement_with_options(.await.map_err(|e| query_error_with_omitted_sql_context(&e, sql))?;with_sql_context(- do_execute(state, &new_key, mysql_dialect, Some(database), sql, schema, cancel_token, options).await,+ do_execute_typed(state, &new_key, mysql_dialect, Some(database), sql, schema, cancel_token, options)+ .await,)}Some(PoolErrorAction::Discard) => {@@ -1577,6 +1769,20 @@ pub async fn execute_sql_statement_with_options(}}+pub async fn execute_sql_statement_with_options(+ state: &AppState,+ connection_id: &str,+ database: &str,+ sql: &str,+ schema: Option<&str>,+ cancel_token: Option<CancellationToken>,+ options: QueryExecutionOptions,+) -> Result<db::QueryResult, String> {+ execute_sql_statement_with_options_typed(state, connection_id, database, sql, schema, cancel_token, options)+ .await+ .map_err(QueryExecutionError::into_legacy_string)+}+async fn execute_postgres_drop_database(state: &AppState,connection_id: &str,@@ -1731,7 +1937,22 @@ pub async fn execute_multi_core_with_options_for_client(cancel_token: Option<CancellationToken>,options: QueryExecutionOptions,) -> Result<Vec<ExecuteMultiResult>, String> {- execute_multi_core_with_options_for_client_and_progress(+ execute_multi_core_with_options_for_client_typed(state, connection_id, database, sql, schema, cancel_token, options)+ .await+ .map_err(QueryExecutionError::into_legacy_string)+}++/// Execute a SQL batch for a client while preserving typed failures.+pub async fn execute_multi_core_with_options_for_client_typed(+ state: &AppState,+ connection_id: &str,+ database: &str,+ sql: &str,+ schema: Option<&str>,+ cancel_token: Option<CancellationToken>,+ options: QueryExecutionOptions,+) -> Result<Vec<ExecuteMultiResult>, QueryExecutionError> {+ execute_multi_core_with_options_for_client_and_progress_typed(state,connection_id,database,@@ -1755,10 +1976,35 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(options: QueryExecutionOptions,progress: Option<ExecuteMultiProgressCallback>,) -> Result<Vec<ExecuteMultiResult>, String> {+ execute_multi_core_with_options_for_client_and_progress_typed(+ state,+ connection_id,+ database,+ sql,+ schema,+ cancel_token,+ options,+ progress,+ )+ .await+ .map_err(QueryExecutionError::into_legacy_string)+}++/// Executes a SQL batch without erasing structured query errors at transport boundaries.+pub async fn execute_multi_core_with_options_for_client_and_progress_typed(+ state: &AppState,+ connection_id: &str,+ database: &str,+ sql: &str,+ schema: Option<&str>,+ cancel_token: Option<CancellationToken>,+ options: QueryExecutionOptions,+ progress: Option<ExecuteMultiProgressCallback>,+) -> Result<Vec<ExecuteMultiResult>, QueryExecutionError> {let pool_database = query_pool_database(database, options.catalog.as_deref());// Reject MongoDB queries that fall through to the generic executor.if connection_is_mongodb(state, connection_id).await {- return Err(MONGO_SHELL_COMMAND_HINT.to_string());+ return Err(MONGO_SHELL_COMMAND_HINT.into());}let pool_key = state@@ -1777,9 +2023,7 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(};if is_sqlserver {- return execute_multi_sqlserver(state, &pool_key, sql, cancel_token, options)- .await- .map(|results| results.into_iter().map(Into::into).collect());+ return execute_multi_sqlserver(state, &pool_key, sql, cancel_token, options).await.map_err(Into::into);}let is_http_sqlite = {@@ -1792,10 +2036,18 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(// HTTP SQLite providers send all statements in one request so the provider// can preserve batch ordering and atomicity.if is_http_sqlite {- let result =- execute_sql_statement_with_options(state, connection_id, database, sql, schema, cancel_token, options)- .await?;- return Ok(vec![result.into()]);+ return single_statement_multi_result(+ execute_sql_statement_with_options_typed(+ state,+ connection_id,+ database,+ sql,+ schema,+ cancel_token,+ options,+ )+ .await,+ );}let db_type = connection_database_type(state, connection_id).await;@@ -1810,7 +2062,7 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(// When use_transaction is explicitly true and we have multiple statements,// route through the transaction wrapper instead of the sequential auto-commit loop.if options.use_transaction == Some(true) && statements.len() > 1 {- let result = execute_statements_in_transaction(+ let result = execute_statements_in_transaction_typed(state,connection_id,database,@@ -1832,17 +2084,18 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(if statements.len() <= 1 {let single_sql = statements.into_iter().next().unwrap_or_default();- let result = execute_sql_statement_with_options(- state,- connection_id,- database,- &single_sql,- schema,- cancel_token,- options,- )- .await?;- return Ok(vec![result.into()]);+ return single_statement_multi_result(+ execute_sql_statement_with_options_typed(+ state,+ connection_id,+ database,+ &single_sql,+ schema,+ cancel_token,+ options,+ )+ .await,+ );}if let Some((pool, mode)) = mysql_pool {@@ -1864,7 +2117,8 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(options,progress.as_ref(),)- .await;+ .await+ .map_err(Into::into);}// Kingbase Go keeps one physical connection per Agent session, so an open@@ -1875,10 +2129,15 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(let mut results = Vec::with_capacity(statements.len());for (statement_index, stmt) in statements.iter().enumerate() {if is_canceled(&cancel_token) {- results.push(ExecuteMultiResult::execution_error(error_query_result(canceled_error())));+ let error = canceled_query_execution_error();+ results.push(ExecuteMultiResult::execution_error_with_backend(+ error_query_result(error.clone().into_legacy_string()),+ Some(statement_index),+ error.into_backend_error(),+ ));break;}- match execute_sql_statement_with_options(+ match execute_sql_statement_with_options_typed(state,connection_id,database,@@ -1893,18 +2152,23 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(report_execute_multi_progress(progress.as_ref(), statement_index, statements.len(), &r, true, None);results.push(ExecuteMultiResult::success_with_index(r, statement_index));}- Err(e) => {- let action = query_pool_error_action(db_type, stmt, &e);- let result = error_query_result(e.clone());+ Err(error) => {+ let action = query_execution_error_action(db_type, stmt, &error);+ let result = error_query_result(error.clone().into_legacy_string());+ let backend_error = error.into_backend_error();report_execute_multi_progress(progress.as_ref(),statement_index,statements.len(),&result,false,- Some(e),+ Some(backend_error.clone()),);- results.push(ExecuteMultiResult::execution_error_with_index(result, statement_index));+ results.push(ExecuteMultiResult::execution_error_with_backend(+ result,+ Some(statement_index),+ backend_error,+ ));if !should_continue_batch_after_error(options.continue_on_error, action) {break;}@@ -1915,6 +2179,12 @@ pub async fn execute_multi_core_with_options_for_client_and_progress(Ok(results)}+fn single_statement_multi_result(+ result: Result<db::QueryResult, QueryExecutionError>,+) -> Result<Vec<ExecuteMultiResult>, QueryExecutionError> {+ result.map(|result| vec![result.into()])+}+trait MysqlBatchStatementExecutor {async fn execute_statement(&mut self, statement: &str) -> Result<Vec<db::QueryResult>, String>;}@@ -1977,7 +2247,14 @@ whereErr(err) => {let action = pool_error_action(db_type, &err);let result = error_query_result(err.clone());- report_execute_multi_progress(progress, statement_index, statements.len(), &result, false, Some(err));+ report_execute_multi_progress(+ progress,+ statement_index,+ statements.len(),+ &result,+ false,+ Some(crate::backend_error::BackendError::from_legacy_backend(&err)),+ );results.push(ExecuteMultiResult::execution_error_with_index(result, statement_index));// Statement errors are safe to collect, but connection-level failures leave// the protocol state unusable and must still trigger pool cleanup.@@ -2102,7 +2379,7 @@ async fn execute_multi_sqlserver(sql: &str,cancel_token: Option<CancellationToken>,options: QueryExecutionOptions,-) -> Result<Vec<db::QueryResult>, String> {+) -> Result<Vec<ExecuteMultiResult>, String> {let batches = split_sql_batches(sql);// Read-only check for SQL Server batch path@@ -2112,22 +2389,14 @@ async fn execute_multi_sqlserver(let query_timeout = resolve_query_timeout(options.timeout_secs);let execution_mode = options.execution_mode;- for batch in &batches {+ for (statement_index, batch) in batches.iter().enumerate() {if is_canceled(&cancel_token) {- all_results.push(db::QueryResult {- columns: vec!["Error".to_string()],- column_types: Vec::new(),- column_sortables: vec![],- spatial_columns: vec![],- spatial_values: vec![],- rows: vec![vec![serde_json::Value::String(canceled_error())]],- affected_rows: 0,- execution_time_ms: 0,- truncated: false,- session_id: None,- has_more: false,- elasticsearch_raw_body: None,- });+ let error = canceled_error();+ all_results.push(ExecuteMultiResult::execution_error_with_backend(+ error_query_result(error.clone()),+ Some(statement_index),+ crate::backend_error::BackendError::from_legacy_backend(&error),+ ));break;}@@ -2142,14 +2411,21 @@ async fn execute_multi_sqlserver(let mut client_guard = match wait_for_value_opt(cancel_token.clone(), query_timeout, client.lock()).await {Ok(guard) => guard,Err(err) => {- all_results.push(error_query_result(err));+ all_results.push(ExecuteMultiResult::execution_error_with_backend(+ error_query_result(err.clone()),+ Some(statement_index),+ crate::backend_error::BackendError::from_legacy_backend(&err),+ ));break;}};if !sqlserver_pool_is_current(state, pool_key, &client).await {- all_results.push(error_query_result(- "SQL Server connection was reset while waiting for the query lock; please retry.".to_string(),+ let error = "SQL Server connection was reset while waiting for the query lock; please retry.".to_string();+ all_results.push(ExecuteMultiResult::execution_error_with_backend(+ error_query_result(error.clone()),+ Some(statement_index),+ crate::backend_error::BackendError::from_legacy_backend(&error),));break;}@@ -2165,23 +2441,16 @@ async fn execute_multi_sqlserver(drop(client_guard);match result {- Ok(results) => all_results.extend(results),+ Ok(results) => all_results.extend(+ results.into_iter().map(|result| ExecuteMultiResult::success_with_index(result, statement_index)),+ ),Err(e) => {let action = pool_error_action(Some(DatabaseType::SqlServer), &e);- all_results.push(db::QueryResult {- columns: vec!["Error".to_string()],- column_types: Vec::new(),- column_sortables: vec![],- spatial_columns: vec![],- spatial_values: vec![],- rows: vec![vec![serde_json::Value::String(e)]],- affected_rows: 0,- execution_time_ms: 0,- truncated: false,- session_id: None,- has_more: false,- elasticsearch_raw_body: None,- });+ all_results.push(ExecuteMultiResult::execution_error_with_backend(+ error_query_result(e.clone()),+ Some(statement_index),+ crate::backend_error::BackendError::from_legacy_backend(&e),+ ));if matches!(action, PoolErrorAction::Discard | PoolErrorAction::ReconnectAndRetry) {state.remove_pool_by_key(pool_key).await;}@@ -2193,20 +2462,7 @@ async fn execute_multi_sqlserver(}if all_results.is_empty() {- all_results.push(db::QueryResult {- columns: vec![],- column_types: Vec::new(),- column_sortables: vec![],- spatial_columns: vec![],- spatial_values: vec![],- rows: vec![],- affected_rows: 0,- execution_time_ms: 0,- truncated: false,- session_id: None,- has_more: false,- elasticsearch_raw_body: None,- });+ all_results.push(empty_query_result(0).into());}Ok(all_results)@@ -2218,8 +2474,8 @@ async fn execute_multi_agent(statements: &[String],schema: Option<&str>,timeout_secs: Option<u64>,-) -> Result<db::QueryResult, String> {- client.execute_batch(database, statements, schema, resolve_query_timeout(timeout_secs)).await+) -> Result<db::QueryResult, AgentCallError> {+ client.execute_batch_typed(database, statements, schema, resolve_query_timeout(timeout_secs)).await}pub async fn execute_statements(@@ -2271,14 +2527,20 @@ pub async fn execute_statements(match result {Ok(result) => return Ok(db::QueryResult { execution_time_ms: start.elapsed().as_millis(), ..result }),Err(err) => {- if is_agent_execute_batch_unsupported(&err) {+ if is_agent_execute_batch_unsupported(&err.to_string()) {log::warn!("Agent does not support execute_batch; falling back to statement-by-statement execution");} else {- let db_type = connection_database_type(state, connection_id).await;- discard_agent_pool_after_error(state, &pool_key, &source_client, db_type, &err).await;- return Err(query_error_with_omitted_sql_context(&err, sql_ctx));+ discard_agent_pool_after_typed_error(+ state,+ &pool_key,+ &source_client,+ &err,+ RecoveryScope::UserOperation,+ )+ .await;+ return Err(query_error_with_omitted_sql_context(&err.into_legacy_string(), sql_ctx));}}}@@ -2314,10 +2576,11 @@ pub async fn execute_statements(}PoolErrorAction::Discard | PoolErrorAction::Keep => {}}- return Err(query_error_with_omitted_sql_context(- &format!("Statement {} failed: {}. Previous {} statement(s) may have been committed.", i + 1, e, i),- sql,- ));+ let error = crate::db::agent_driver::append_legacy_error_context(+ &e,+ &format!("Statement {} failed; previous {} statement(s) may have been committed.", i + 1, i),+ );+ return Err(query_error_with_omitted_sql_context(&error, sql));}}}@@ -2606,6 +2869,20 @@ pub async fn execute_statements_in_transaction(schema: Option<&str>,catalog: Option<&str>,) -> Result<db::QueryResult, String> {+ execute_statements_in_transaction_typed(state, connection_id, database, statements, schema, catalog)+ .await+ .map_err(QueryExecutionError::into_legacy_string)+}++/// Execute multiple SQL statements transactionally while retaining typed failures.+pub async fn execute_statements_in_transaction_typed(+ state: &AppState,+ connection_id: &str,+ database: &str,+ statements: &[String],+ schema: Option<&str>,+ catalog: Option<&str>,+) -> Result<db::QueryResult, QueryExecutionError> {let sql_ctx = statements.first().map(|s| s.as_str()).unwrap_or("");let pool_database = query_pool_database(database, catalog);let pool_key = state@@ -2613,8 +2890,16 @@ pub async fn execute_statements_in_transaction(.await.map_err(|e| query_error_with_omitted_sql_context(&e, sql_ctx))?;- execute_statements_in_transaction_on_pool(state, &pool_key, connection_id, database, statements, schema, catalog)- .await+ execute_statements_in_transaction_on_pool_typed(+ state,+ &pool_key,+ connection_id,+ database,+ statements,+ schema,+ catalog,+ )+ .await}/// Execute multiple SQL statements transactionally on an already-resolved pool.@@ -2628,6 +2913,29 @@ pub async fn execute_statements_in_transaction_on_pool(schema: Option<&str>,catalog: Option<&str>,) -> Result<db::QueryResult, String> {+ execute_statements_in_transaction_on_pool_typed(+ state,+ pool_key,+ connection_id,+ database,+ statements,+ schema,+ catalog,+ )+ .await+ .map_err(QueryExecutionError::into_legacy_string)+}++/// Execute a transaction on an already-resolved pool without erasing typed failures.+pub async fn execute_statements_in_transaction_on_pool_typed(+ state: &AppState,+ pool_key: &str,+ connection_id: &str,+ database: &str,+ statements: &[String],+ schema: Option<&str>,+ catalog: Option<&str>,+) -> Result<db::QueryResult, QueryExecutionError> {// Read-only check: intercept all transaction paths before dispatchingcheck_read_only_for_connection_multi(state, pool_key, statements).await?;@@ -2665,21 +2973,20 @@ pub async fn execute_statements_in_transaction_on_pool(let cancel_context = state.get_postgres_cancel_context(pool_key).await;exec_tx_pg_inner(pool, statements, schema, start, operation_budget.clone(), cancel_context).await}- Some(TxPath::Mysql(pool, _bare)) => {- exec_tx_mysql_inner(- state,- pool_key,- pool,- statements,- start,- operation_budget.clone(),- mysql_catalog_dialect,- catalog,- database,- )- .await- }- Some(TxPath::Sqlite(pool)) => exec_tx_sqlite_inner(pool, statements, start).await,+ Some(TxPath::Mysql(pool, _bare)) => exec_tx_mysql_inner(+ state,+ pool_key,+ pool,+ statements,+ start,+ operation_budget.clone(),+ mysql_catalog_dialect,+ catalog,+ database,+ )+ .await+ .map_err(Into::into),+ Some(TxPath::Sqlite(pool)) => exec_tx_sqlite_inner(pool, statements, start).await.map_err(Into::into),Some(TxPath::CloudflareD1(client)) => {let sql = statements.join(";\n");wait_for_query_opt(@@ -2688,27 +2995,33 @@ pub async fn execute_statements_in_transaction_on_pool(db::cloudflare_d1_driver::execute_query_with_max_rows(&client, &sql, None),).await+ .map_err(Into::into)}Some(TxPath::Agent(client)) => {let result = exec_tx_agent_inner(client.clone(), db_type, Some(database), statements, schema, start).await;if let Err(error) = result.as_ref() {- discard_agent_pool_after_error(state, pool_key, &client, db_type, error).await;+ discard_agent_pool_after_typed_error(state, pool_key, &client, error, RecoveryScope::UserOperation)+ .await;}- return result;+ return result.map_err(QueryExecutionError::Agent);}Some(TxPath::Explicit) => {let mysql_dialect = connection_mysql_query_dialect(state, connection_id).await;- exec_tx_explicit_inner(state, pool_key, mysql_dialect, Some(database), statements, schema, start).await+ exec_tx_explicit_inner(state, pool_key, mysql_dialect, Some(database), statements, schema, start)+ .await+ .map_err(Into::into)}Some(TxPath::None) => {let mysql_dialect = connection_mysql_query_dialect(state, connection_id).await;- exec_tx_none_inner(state, pool_key, mysql_dialect, Some(database), statements, schema, start).await+ exec_tx_none_inner(state, pool_key, mysql_dialect, Some(database), statements, schema, start)+ .await+ .map_err(Into::into)}- None => Err("Connection not found for transaction".to_string()),+ None => Err("Connection not found for transaction".to_string().into()),};if let Err(err) = result.as_ref() {- discard_pool_after_error(state, pool_key, db_type, err).await;+ discard_pool_after_error(state, pool_key, db_type, &err.to_string()).await;}result@@ -2735,7 +3048,7 @@ async fn exec_tx_pg_inner(start: std::time::Instant,budget: DbOperationBudget,cancel_context: Option<db::postgres::PostgresCancelContext>,-) -> Result<db::QueryResult, String> {+) -> Result<db::QueryResult, QueryExecutionError> {let mut client = db::postgres::checkout_postgres_client(&pool, None, budget.checkout_timeout).await.map_err(|e| format!("Failed to acquire connection: {}", e))?;@@ -2761,7 +3074,7 @@ async fn exec_tx_pg_inner("schema.reset",).await- .map_err(|err| format!("PostgreSQL schema.reset cleanup failed: {err}"))+ .map_err(|err| QueryExecutionError::Legacy(format!("PostgreSQL schema.reset cleanup failed: {err}")))} else {Ok(0)};@@ -2783,7 +3096,7 @@ async fn exec_tx_pg_inner(}),(Err(e), Ok(_)) => Err(e),(Ok(_), Err(reset_err)) => Err(reset_err),- (Err(e), Err(reset_err)) => Err(format!("{e}; {reset_err}")),+ (Err(e), Err(reset_err)) => Err(e.with_context(&reset_err.to_string())),}}@@ -2792,7 +3105,7 @@ async fn exec_tx_pg_statements(statements: &[String],budget: &DbOperationBudget,cancel_context: Option<db::postgres::PostgresCancelContext>,-) -> Result<u64, String> {+) -> Result<u64, QueryExecutionError> {let tx = tokio::time::timeout(budget.recycle_timeout, client.transaction()).await.map_err(|_| {@@ -2802,15 +3115,21 @@ async fn exec_tx_pg_statements(let mut total_affected: u64 = 0;for (i, sql) in statements.iter().enumerate() {let pg_cancel_token = tx.client().cancel_token();+ let mut is_server_error = false;let affected = db::postgres::wait_postgres_operation(pg_cancel_token,cancel_context.clone(),budget.query_timeout,budget.cancel_timeout,- async { tx.execute(sql, &[]).await.map_err(|e| e.to_string()) },+ async {+ tx.execute(sql, &[]).await.map_err(|error| {+ is_server_error = error.as_db_error().is_some();+ error.to_string()+ })+ },).await- .map_err(|e| query_error_with_omitted_sql_context(&format!("Statement {} failed: {}", i + 1, e), sql))?;+ .map_err(|e| postgres_transaction_statement_error(i + 1, &e, sql, is_server_error))?;total_affected += affected;}tokio::time::timeout(budget.cleanup_timeout, tx.commit())@@ -3016,7 +3335,7 @@ async fn exec_tx_agent_inner(statements: &[String],schema: Option<&str>,start: std::time::Instant,-) -> Result<db::QueryResult, String> {+) -> Result<db::QueryResult, AgentCallError> {let execution_schema = schema_for_execution_context(db_type, schema);let rewritten_statements;let statements = if qualifies_unqualified_agent_relations(db_type) {@@ -3027,7 +3346,7 @@ async fn exec_tx_agent_inner(statements};let mut client = client.lock().await;- let result: db::QueryResult = client.execute_transaction(database, statements, execution_schema).await?;+ let result: db::QueryResult = client.execute_transaction_typed(database, statements, execution_schema).await?;Ok(db::QueryResult { execution_time_ms: start.elapsed().as_millis(), ..result })}@@ -3741,7 +4060,13 @@ for line in sys.stdin:let error = execute_multi_agent(&mut client, None, &["slow".to_string()], None, Some(1)).await.unwrap_err();- assert_eq!(error, "Agent RPC call timed out (1s)");+ assert!(matches!(+ error,+ AgentCallError::Timeout {+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ }+ ));}#[cfg(unix)]@@ -4063,6 +4388,104 @@ for line in sys.stdin:let _ = std::fs::remove_dir_all(dir);}+ #[tokio::test]+ async fn single_statement_multi_core_keeps_query_error_typed() {+ let (state, dir, runtime) = agent_error_state("keep").await;++ let error = execute_multi_core_with_options_for_client_and_progress_typed(+ &state,+ "conn-1",+ "",+ "SELECT 1",+ None,+ None,+ QueryExecutionOptions::default(),+ None,+ )+ .await+ .unwrap_err();++ assert!(matches!(error, QueryExecutionError::Agent(_)));++ runtime.kill();+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn native_pre_dispatch_cancellation_stays_typed() {+ let dir = std::env::temp_dir().join(format!("dbx-query-native-cancel-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ let connection_id = "sqlite-cancel";+ let sqlite = db::sqlite::connect_path_create_if_missing(dir.join("query.db").to_str().unwrap()).await.unwrap();+ state.connections.write().await.insert(connection_id.to_string(), PoolKind::Sqlite(sqlite));+ state.configs.write().await.insert(connection_id.to_string(), test_connection_config(DatabaseType::Sqlite));+ let cancel_token = CancellationToken::new();+ cancel_token.cancel();++ let error = execute_sql_statement_with_options_typed(+ &state,+ connection_id,+ "",+ "SELECT 1",+ None,+ Some(cancel_token),+ QueryExecutionOptions::default(),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ &error,+ QueryExecutionError::Canceled {+ stage: AgentErrorStage::Request,+ operation_outcome: AgentOperationOutcome::NotStarted,+ }+ ));+ let backend_error = error.into_backend_error();+ assert_eq!(backend_error.code(), "DBX-JDBC-2003");+ assert_eq!(backend_error.source(), crate::backend_error::BackendErrorSource::LegacyBackend);+ assert_eq!(backend_error.operation_outcome(), crate::backend_error::BackendOperationOutcome::NotStarted);++ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn agent_pre_dispatch_cancellation_stays_local_and_typed() {+ let (state, dir, runtime) = agent_error_state("keep").await;+ let cancel_token = CancellationToken::new();+ cancel_token.cancel();++ let error = execute_sql_statement_with_options_typed(+ &state,+ "conn-1",+ "",+ "SELECT 1",+ None,+ Some(cancel_token),+ QueryExecutionOptions::default(),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ &error,+ QueryExecutionError::Canceled {+ stage: AgentErrorStage::Request,+ operation_outcome: AgentOperationOutcome::NotStarted,+ }+ ));+ let backend_error = error.into_backend_error();+ assert_eq!(backend_error.code(), "DBX-JDBC-2003");+ assert_eq!(backend_error.source(), crate::backend_error::BackendErrorSource::LegacyBackend);+ assert_eq!(backend_error.operation_outcome(), crate::backend_error::BackendOperationOutcome::NotStarted);+ assert!(!runtime.is_failed());++ runtime.kill();+ let _ = std::fs::remove_dir_all(dir);+ }+#[tokio::test]async fn agent_transaction_replace_runtime_error_detaches_pool_and_stops_runtime() {let (state, dir, runtime) = agent_error_state("replace_runtime").await;@@ -4300,7 +4723,7 @@ for line in sys.stdin:success: false,execution_time_ms: 0,affected_rows: 0,- error: Some("Duplicate entry".to_string()),+ error: Some(crate::backend_error::BackendError::from_legacy_backend("Duplicate entry")),},]);@@ -4446,6 +4869,13 @@ for line in sys.stdin:assert!(success.get("execution_error").is_none());assert!(success.get("statement_index").is_none());+ let mut error_column = empty_query_result(0);+ error_column.columns = vec!["Error".to_string()];+ error_column.rows = vec![vec![serde_json::json!("valid query value")]];+ let error_column = serde_json::to_value(ExecuteMultiResult::success_with_index(error_column, 0)).unwrap();+ assert!(error_column.get("execution_error").is_none());+ assert!(error_column.get("error").is_none());+let failure = serde_json::to_value(ExecuteMultiResult::execution_error_with_index(error_query_result("failed".to_string()),2,@@ -4454,6 +4884,142 @@ for line in sys.stdin:assert_eq!(failure.get("execution_error"), Some(&serde_json::Value::Bool(true)));assert_eq!(failure.get("statement_index"), Some(&serde_json::json!(2)));assert_eq!(failure.get("columns"), Some(&serde_json::json!(["Error"])));+ assert_eq!(+ failure.get("error").and_then(|value| value.get("code")),+ Some(&serde_json::json!("DBX-LEGACY-0001"))+ );++ let redacted = serde_json::to_value(+ ExecuteMultiResult::execution_error_with_index(error_query_result("safe failure".to_string()), 2)+ .without_error_detail(),+ )+ .unwrap();+ assert!(redacted.get("error").and_then(|value| value.get("detail")).is_none());+ }++ #[test]+ fn query_execution_error_preserves_structured_catalog_identity() {+ let error = QueryExecutionError::Agent(AgentCallError::Structured {+ rpc_code: -1,+ message: "connection lost".to_string(),+ context: crate::db::agent_driver::AgentErrorContext {+ contract_version: 1,+ category: crate::db::agent_driver::AgentErrorCategory::Connection,+ retryable: false,+ session_disposition: crate::db::agent_driver::AgentSessionDisposition::Quarantine,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: None,+ vendor_code: None,+ exception_class: None,+ },+ });++ assert_eq!(error.into_backend_error().code(), "DBX-JDBC-1002");+ }++ #[test]+ fn query_timeout_preserves_timeout_catalog_identity_and_detail() {+ let error = classify_query_error(+ Some(DatabaseType::Postgres),+ QueryExecutionError::Legacy("Query timed out after 1 seconds".to_string()),+ )+ .with_omitted_sql_context("SELECT pg_sleep(10)");+ let backend_error = error.into_backend_error();++ assert_eq!(backend_error.code(), "DBX-JDBC-2002");+ assert_eq!(+ backend_error.message_params().get("stage"),+ Some(&crate::backend_error::BackendMessageParam::String("execute".to_string()))+ );+ assert_eq!(+ backend_error.detail(),+ Some("Query timed out after 1 seconds SQL text omitted from user-facing error; enable debug SQL diagnostics for a redacted statement.")+ );+ }++ #[test]+ fn postgres_server_error_preserves_sql_catalog_identity_and_detail() {+ let error = classify_query_error(+ Some(DatabaseType::Postgres),+ QueryExecutionError::Legacy("ERROR: relation \"dbx_table_that_does_not_exist\" does not exist".to_string()),+ )+ .with_omitted_sql_context("SELECT * FROM dbx_table_that_does_not_exist");+ let backend_error = error.into_backend_error();++ assert_eq!(backend_error.code(), "DBX-JDBC-4001");+ assert_eq!(+ backend_error.message_params().get("stage"),+ Some(&crate::backend_error::BackendMessageParam::String("execute".to_string()))+ );+ assert_eq!(+ backend_error.detail(),+ Some(+ "ERROR: relation \"dbx_table_that_does_not_exist\" does not exist SQL text omitted from user-facing error; enable debug SQL diagnostics for a redacted statement."+ )+ );+ }++ #[test]+ fn single_statement_multi_result_preserves_sql_error_type() {+ let error = classify_query_error(+ Some(DatabaseType::Postgres),+ QueryExecutionError::Legacy("ERROR: relation \"dbx_table_that_does_not_exist\" does not exist".to_string()),+ )+ .with_omitted_sql_context("SELECT * FROM dbx_table_that_does_not_exist");++ let error = single_statement_multi_result(Err(error)).unwrap_err();+ let backend_error = error.into_backend_error();++ assert_eq!(backend_error.code(), "DBX-JDBC-4001");+ assert_eq!(backend_error.message_key(), "backendErrors.jdbc.sqlFailed");+ assert_eq!(+ backend_error.detail(),+ Some(+ "ERROR: relation \"dbx_table_that_does_not_exist\" does not exist SQL text omitted from user-facing error; enable debug SQL diagnostics for a redacted statement."+ )+ );+ }++ #[test]+ fn postgres_transaction_statement_error_preserves_sql_catalog_identity() {+ let error = postgres_transaction_statement_error(+ 1,+ "ERROR: relation \"dbx_table_that_does_not_exist\" does not exist",+ "SELECT * FROM dbx_table_that_does_not_exist",+ true,+ );+ let backend_error = error.into_backend_error();++ assert_eq!(backend_error.code(), "DBX-JDBC-4001");+ assert_eq!(backend_error.message_key(), "backendErrors.jdbc.sqlFailed");+ assert_eq!(+ backend_error.detail(),+ Some(+ "Statement 1 failed: ERROR: relation \"dbx_table_that_does_not_exist\" does not exist SQL text omitted from user-facing error; enable debug SQL diagnostics for a redacted statement."+ )+ );+ }++ #[test]+ fn postgres_transaction_uses_driver_fact_not_error_wording() {+ let error = postgres_transaction_statement_error(+ 1,+ "ERROR: relation \"connection_closed\" does not exist",+ "SELECT * FROM connection_closed",+ true,+ );++ assert_eq!(error.into_backend_error().code(), "DBX-JDBC-4001");+ }++ #[test]+ fn sequential_multi_cancellation_uses_canceled_catalog() {+ let backend_error = canceled_query_execution_error().into_backend_error();++ assert_eq!(backend_error.code(), "DBX-JDBC-2003");+ assert_eq!(backend_error.message_key(), "backendErrors.jdbc.operationCanceled");}#[test]@@ -4927,14 +5493,14 @@ for line in sys.stdin:}#[test]- fn pool_error_action_reconnects_connection_errors() {+ fn pool_error_action_reconnects_non_agent_errors_but_never_replays_agent_operations() {let err = "connection reset by peer";assert_eq!(pool_error_action(Some(DatabaseType::SqlServer), err), PoolErrorAction::ReconnectAndRetry);assert_eq!(pool_error_action(Some(DatabaseType::Postgres), err), PoolErrorAction::ReconnectAndRetry);let dameng_err = "Agent RPC error (-1): dm.jdbc.driver.DMException: 网络通信异常";- assert_eq!(pool_error_action(Some(DatabaseType::Dameng), dameng_err), PoolErrorAction::ReconnectAndRetry);+ assert_eq!(pool_error_action(Some(DatabaseType::Dameng), dameng_err), PoolErrorAction::Discard);}#[test]@@ -5306,13 +5872,12 @@ for line in sys.stdin:assert!(should_discard_agent_pool_after_error(quarantined));assert!(should_discard_agent_pool_after_error(replace_runtime));- assert!(is_connection_error(quarantined));assert_eq!(pool_error_action(Some(DatabaseType::Oracle), quarantined), PoolErrorAction::Discard);assert_eq!(pool_error_action(Some(DatabaseType::Oracle), replace_runtime), PoolErrorAction::Discard);}#[test]- fn unavailable_agent_pipes_are_reconnectable_errors() {+ fn unavailable_agent_pipes_discard_without_replaying_user_operations() {assert!(should_discard_agent_pool_after_error("Agent stdin not available"));assert!(should_discard_agent_pool_after_error("Agent stdout not available"));assert!(is_connection_error("Agent stdin not available"));@@ -5321,15 +5886,12 @@ for line in sys.stdin:assert!(is_connection_error("Agent runtime is unavailable"));assert_eq!(pool_error_action(Some(DatabaseType::Oracle), "Agent stdin not available"),- PoolErrorAction::ReconnectAndRetry- );- assert_eq!(- pool_error_action(Some(DatabaseType::Oracle), "Agent runtime terminated"),- PoolErrorAction::ReconnectAndRetry+ PoolErrorAction::Discard);+ assert_eq!(pool_error_action(Some(DatabaseType::Oracle), "Agent runtime terminated"), PoolErrorAction::Discard);assert_eq!(pool_error_action(Some(DatabaseType::Oracle), "Agent runtime is unavailable"),- PoolErrorAction::ReconnectAndRetry+ PoolErrorAction::Discard);}diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rsindex 2225dbed6c..6afc8f814b 100644--- a/crates/dbx-core/src/schema.rs+++ b/crates/dbx-core/src/schema.rs@@ -1,3 +1,4 @@+use crate::agent_recovery::{RecoveryDecision, RecoveryPolicy, RecoveryScope};use crate::connection::{connection_url_for_endpoint, database_connection_config, gaussdb_uses_m_jdbc_driver, task_client_session_id,AppState, MysqlMode, PoolKind,@@ -793,8 +794,9 @@ async fn list_schemas_once(.await.map(|schemas| filter_visible_schema_names(schemas, visible_schema_filter.as_deref())).map_err(|fallback_error| {- format!(- "{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}"+ crate::db::agent_driver::append_legacy_error_context(+ &agent_error,+ &format!("Native PostgreSQL metadata fallback failed: {fallback_error}"),)});}@@ -2043,7 +2045,10 @@ async fn list_tables_once(db::postgres::list_tables_filtered(&pool, schema, filter, limit, offset).await};return result.map_err(|fallback_error| {- format!("{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}")+ crate::db::agent_driver::append_legacy_error_context(+ &agent_error,+ &format!("Native PostgreSQL metadata fallback failed: {fallback_error}"),+ )});}}@@ -3052,7 +3057,10 @@ for line in sys.stdin:let error = super::get_table_ddl_core(&state, "conn", "analytics", "APP", "EVENTS", None).await.unwrap_err();- assert_eq!(crate::db::agent_driver::agent_rpc_error_category(&error).as_deref(), Some("timeout"));+ assert_eq!(+ crate::db::agent_driver::try_agent_error_from_legacy(&error).and_then(|error| error.category()),+ Some(crate::db::agent_driver::AgentErrorCategory::Timeout)+ );assert_eq!(std::fs::read_to_string(call_count_path).unwrap(), "1");assert!(!state.connections.read().await.contains_key(pool_key));runtime.kill();@@ -4686,8 +4694,9 @@ async fn list_objects_once({return db::postgres::list_objects(&pool, schema).await.map(unpaged_object_list).map_err(|fallback_error| {- format!(- "{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}"+ crate::db::agent_driver::append_legacy_error_context(+ &agent_error,+ &format!("Native PostgreSQL metadata fallback failed: {fallback_error}"),)},);@@ -4819,8 +4828,9 @@ async fn list_completion_objects_once(.await.map(filter_completion_objects).map_err(|fallback_error| {- format!(- "{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}"+ crate::db::agent_driver::append_legacy_error_context(+ &agent_error,+ &format!("Native PostgreSQL metadata fallback failed: {fallback_error}"),)});}@@ -4924,19 +4934,16 @@ wherelet mut retried = false;loop {let result = operation().await;- let action = result- .as_ref()- .err()- .map(|error| metadata_error_action(db_type, error, retried))- .unwrap_or(MetadataErrorAction::Return);- match action {+ let recovery =+ result.as_ref().err().map(|error| metadata_recovery(db_type, error, retried)).unwrap_or_default();+ match recovery.action {MetadataErrorAction::ReplaceRuntime => {state- .detach_metadata_pool_after_error(+ .detach_metadata_pool_after_recovery(connection_id,database,client_session_id,- result.as_ref().err().expect("replace-runtime action requires an error"),+ recovery.agent_session_id.as_deref(),true,).await;@@ -4944,11 +4951,11 @@ where}MetadataErrorAction::Discard => {state- .detach_metadata_pool_after_error(+ .detach_metadata_pool_after_recovery(connection_id,database,client_session_id,- result.as_ref().err().expect("discard action requires an error"),+ recovery.agent_session_id.as_deref(),false,).await;@@ -4959,25 +4966,26 @@ whereif let Err(error) =state.reconnect_metadata_pool_for_session(connection_id, database, client_session_id).await{- match metadata_error_action(db_type, &error, true) {+ let reconnect_recovery = metadata_recovery(db_type, &error, true);+ match reconnect_recovery.action {MetadataErrorAction::ReplaceRuntime => {state- .detach_metadata_pool_after_error(+ .detach_metadata_pool_after_recovery(connection_id,database,client_session_id,- &error,+ reconnect_recovery.agent_session_id.as_deref(),true,).await;}MetadataErrorAction::Retry | MetadataErrorAction::Discard => {state- .detach_metadata_pool_after_error(+ .detach_metadata_pool_after_recovery(connection_id,database,client_session_id,- &error,+ reconnect_recovery.agent_session_id.as_deref(),false,).await;@@ -4992,26 +5000,48 @@ where}}-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]enum MetadataErrorAction {Retry,Discard,ReplaceRuntime,+ #[default]Return,}+#[derive(Debug, Default)]+struct MetadataRecovery {+ action: MetadataErrorAction,+ agent_session_id: Option<String>,+}++#[cfg(test)]fn metadata_error_action(db_type: Option<DatabaseType>, error: &str, retried: bool) -> MetadataErrorAction {- if crate::db::agent_driver::agent_session_disposition(error)- == Some(crate::db::agent_driver::AgentSessionDisposition::ReplaceRuntime)- {- MetadataErrorAction::ReplaceRuntime- } else if !retried && is_retryable_metadata_error(error) {+ metadata_recovery(db_type, error, retried).action+}++fn metadata_recovery(db_type: Option<DatabaseType>, error: &str, retried: bool) -> MetadataRecovery {+ if db_type.is_some_and(|db_type| crate::database_capabilities::is_agent_type(&db_type)) {+ if let Some(error) = crate::db::agent_driver::try_agent_error_from_legacy(error) {+ let agent_session_id = error.session_id().map(str::to_string);+ let action = match RecoveryPolicy::decide(&error, RecoveryScope::ReadOnlyMetadata { retried }) {+ RecoveryDecision::RetryReadOnlyMetadata => MetadataErrorAction::Retry,+ RecoveryDecision::QuarantineSession => MetadataErrorAction::Discard,+ RecoveryDecision::ReplaceRuntime => MetadataErrorAction::ReplaceRuntime,+ RecoveryDecision::KeepSession => MetadataErrorAction::Return,+ };+ return MetadataRecovery { action, agent_session_id };+ }+ }++ let action = if !retried && is_retryable_metadata_error(error) {MetadataErrorAction::Retry} else if should_discard_pool_after_error(db_type, error) {MetadataErrorAction::Discard} else {MetadataErrorAction::Return- }+ };+ MetadataRecovery { action, agent_session_id: None }}#[cfg(test)]@@ -5025,11 +5055,9 @@ async fn replace_metadata_runtime(}fn is_retryable_metadata_error(error: &str) -> bool {- let category = crate::db::agent_driver::agent_rpc_error_category(error);- if let Some(category) = category {- return category == "connection"- && crate::db::agent_driver::agent_session_disposition(error)- == Some(crate::db::agent_driver::AgentSessionDisposition::Quarantine);+ if let Some(error) = crate::db::agent_driver::try_agent_error_from_legacy(error) {+ return RecoveryPolicy::decide(&error, RecoveryScope::ReadOnlyMetadata { retried: false })+ == RecoveryDecision::RetryReadOnlyMetadata;}error == "Pool not found" || crate::query::is_connection_error(error)}@@ -5294,8 +5322,9 @@ async fn get_columns_core_for_session_inner(.await.map(deduplicate_column_infos).map_err(|fallback_error| {- format!(- "{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}"+ crate::db::agent_driver::append_legacy_error_context(+ &agent_error,+ &format!("Native PostgreSQL metadata fallback failed: {fallback_error}"),)});}diff --git a/crates/dbx-web/src/error.rs b/crates/dbx-web/src/error.rsindex 501dc38f59..c85660e531 100644--- a/crates/dbx-web/src/error.rs+++ b/crates/dbx-web/src/error.rs@@ -1,11 +1,14 @@use axum::http::StatusCode;use axum::response::{IntoResponse, Response};+use axum::Json;+use dbx_core::backend_error::BackendError;use std::fmt;#[derive(Debug)]pub struct AppError {pub message: String,pub status: StatusCode,+ pub error: Box<BackendError>,}impl fmt::Display for AppError {@@ -16,32 +19,122 @@ impl fmt::Display for AppError {impl AppError {pub fn internal(msg: impl Into<String>) -> Self {- AppError { message: msg.into(), status: StatusCode::INTERNAL_SERVER_ERROR }+ Self::with_status(msg.into(), StatusCode::INTERNAL_SERVER_ERROR)}pub fn bad_request(msg: impl Into<String>) -> Self {- AppError { message: msg.into(), status: StatusCode::BAD_REQUEST }+ Self::with_status(msg.into(), StatusCode::BAD_REQUEST)}pub fn not_found(msg: impl Into<String>) -> Self {- AppError { message: msg.into(), status: StatusCode::NOT_FOUND }+ Self::with_status(msg.into(), StatusCode::NOT_FOUND)+ }++ fn with_status(message: String, status: StatusCode) -> Self {+ let error = BackendError::from_legacy_string(&message);+ Self { message, status, error: Box::new(error) }+ }++ pub fn from_backend_error(error: BackendError) -> Self {+ Self { message: error.code().to_string(), status: StatusCode::INTERNAL_SERVER_ERROR, error: Box::new(error) }}}impl IntoResponse for AppError {fn into_response(self) -> Response {- (self.status, self.message).into_response()+ (self.status, Json(*self.error)).into_response()}}impl From<String> for AppError {fn from(s: String) -> Self {- AppError { message: s, status: StatusCode::INTERNAL_SERVER_ERROR }+ Self::internal(s)}}impl From<&str> for AppError {fn from(s: &str) -> Self {- AppError { message: s.to_string(), status: StatusCode::INTERNAL_SERVER_ERROR }+ Self::internal(s)+ }+}++impl From<BackendError> for AppError {+ fn from(error: BackendError) -> Self {+ Self::from_backend_error(error)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn legacy_errors_are_exposed_as_the_shared_backend_envelope() {+ let error = AppError::internal("database failed");+ assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(error.error.version(), 1);+ assert_eq!(error.error.code(), "DBX-LEGACY-0001");+ assert_eq!(error.message, "database failed");+ }++ #[test]+ fn app_error_stays_small_for_route_result_types() {+ assert!(std::mem::size_of::<AppError>() <= 64);+ }++ #[test]+ fn structured_agent_text_keeps_catalog_identity_at_http_boundary() {+ let error = AppError::from(+ "Agent RPC error (-1): timed out\nDBX_AGENT_ERROR_DATA:{\"category\":\"timeout\",\"stage\":\"execute\"}",+ );+ assert_eq!(error.error.code(), "DBX-JDBC-9001");+ assert_eq!(error.error.source(), dbx_core::backend_error::BackendErrorSource::JdbcAgentLegacy);+ }++ #[tokio::test]+ async fn http_response_preserves_filtered_legacy_detail() {+ let response = AppError::internal("database failed").into_response();+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(response.headers()[axum::http::header::CONTENT_TYPE], "application/json");+ let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();+ let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(payload["version"], 1);+ assert_eq!(payload["code"], "DBX-LEGACY-0001");+ assert_eq!(payload["messageKey"], "backendErrors.legacy");+ assert_eq!(payload["detail"], "database failed");+ }++ #[tokio::test]+ async fn http_response_preserves_filtered_structured_agent_detail() {+ use dbx_core::db::agent_driver::{+ AgentCallError, AgentErrorCategory, AgentErrorContext, AgentErrorStage, AgentOperationOutcome,+ AgentSessionDisposition,+ };++ let error = BackendError::from_agent_call_error(&AgentCallError::Structured {+ rpc_code: -1,+ message: "relation customer_orders does not exist".to_string(),+ context: AgentErrorContext {+ contract_version: 1,+ category: AgentErrorCategory::Sql,+ retryable: false,+ session_disposition: AgentSessionDisposition::Keep,+ stage: AgentErrorStage::Execute,+ operation_outcome: AgentOperationOutcome::Unknown,+ agent_session_id: Some("session-1".to_string()),+ sql_state: Some("42P01".to_string()),+ vendor_code: None,+ exception_class: Some("java.sql.SQLException".to_string()),+ },+ });++ let response = AppError::from(error).into_response();+ let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();+ let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();++ assert_eq!(payload["code"], "DBX-JDBC-4001");+ assert_eq!(payload["source"], "jdbcAgent");+ assert_eq!(payload["detail"], "relation customer_orders does not exist");+ assert!(payload["diagnostics"].get("agentSessionId").is_none());}}diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rsindex bba1c7e6ce..82bc909896 100644--- a/crates/dbx-web/src/routes/query.rs+++ b/crates/dbx-web/src/routes/query.rs@@ -344,7 +344,7 @@ pub async fn execute_query(tracing::debug!(connection_id = %req.connection_id, "execute_query");- let result = dbx_core::query::execute_sql_statement_with_options(+ let result = dbx_core::query::execute_sql_statement_with_options_typed(&state.app,&req.connection_id,&req.database,@@ -366,7 +366,7 @@ pub async fn execute_query(},).await- .map_err(AppError::from)?;+ .map_err(|error| AppError::from(error.into_backend_error()))?;drop(registered);Ok(Json(result))@@ -390,7 +390,7 @@ pub async fn execute_multi(tracing::debug!(connection_id = %req.connection_id, "execute_multi");- let result = dbx_core::query::execute_multi_core_with_options_for_client(+ let result = dbx_core::query::execute_multi_core_with_options_for_client_typed(&state.app,&req.connection_id,&req.database,@@ -412,10 +412,16 @@ pub async fn execute_multi(},).await- .map_err(AppError::from)?;+ .map_err(|error| AppError::from(error.into_backend_error()))?;drop(registered);- Ok(Json(result))+ Ok(execute_multi_response(result))+}++fn execute_multi_response(+ result: Vec<dbx_core::query::ExecuteMultiResult>,+) -> Json<Vec<dbx_core::query::ExecuteMultiResult>> {+ Json(result)}pub async fn execute_batch(@@ -1004,4 +1010,35 @@ mod tests {// Missing connection cannot have applied statements.assert_eq!(log.executed_count, 0);}++ #[test]+ fn execute_multi_response_preserves_nested_filtered_error_detail() {+ let result = dbx_core::query::ExecuteMultiResult {+ result: dbx_core::db::QueryResult {+ columns: vec!["Error".to_string()],+ column_types: vec![],+ column_sortables: vec![],+ spatial_columns: vec![],+ spatial_values: vec![],+ rows: vec![vec![serde_json::json!("relation customer_orders does not exist")]],+ affected_rows: 0,+ execution_time_ms: 0,+ truncated: false,+ session_id: None,+ has_more: false,+ elasticsearch_raw_body: None,+ },+ execution_error: true,+ statement_index: Some(1),+ error: Some(dbx_core::backend_error::BackendError::from_sql_detail(+ "relation customer_orders does not exist",+ )),+ };++ let payload = serde_json::to_value(execute_multi_response(vec![result]).0).unwrap();++ assert_eq!(payload[0]["statement_index"], 1);+ assert_eq!(payload[0]["error"]["code"], "DBX-JDBC-4001");+ assert_eq!(payload[0]["error"]["detail"], "relation customer_orders does not exist");+ }}diff --git a/docs/backend-error-handling.md b/docs/backend-error-handling.mdnew file mode 100644index 0000000000..65f84ca7ee--- /dev/null+++ b/docs/backend-error-handling.md@@ -0,0 +1,147 @@+# 后端异常处理与错误码规范++本文记录 DBX 当前已经落地的后端错误契约、恢复边界和前端展示规则。目标是让恢复逻辑依赖可验证的类型,让对外错误身份稳定,同时保留数据库服务端返回的、经过安全过滤的真实诊断信息。++本文描述的是现有实现,不引入新的 Agent Protocol V3。结构化错误是 Agent Protocol v2 的可选 capability:`structured_error_v1`。++## 分层职责++1. Agent 只报告事实:`category`、`stage`、`operationOutcome`、`sessionDisposition` 以及 JDBC 诊断字段。+2. Rust `AgentCallError` 负责解码 Agent v2 的结构化错误;旧 Agent 或旧字符串接口只经过 `agent_driver` 中的兼容 adapter。+3. `RecoveryPolicy` 根据类型化错误和操作范围决定保留、隔离 Session 或替换 Runtime;它不从错误文本推断恢复动作。+4. `BackendError` catalog 将类型化错误映射为稳定的 `code`、`messageKey`、白名单参数和安全诊断字段。+5. 查询层通过 `QueryExecutionError::into_backend_error` 生成公共错误对象;Tauri、HTTP 和多语句结果只负责携带该对象,不重复分类。+6. 前端通过 `normalizeBackendError` 和 `translateBackendError` 生成本地化摘要,并在可用时追加服务端 `detail`。++## Agent 调用契约++Agent runtime 必须完成 Protocol v2 handshake,并支持 `multi_session`。如果声明 `structured_error_v1`,`call_typed` 在 RPC 失败时返回 `AgentCallError::Structured`;否则进入 `Legacy` 兼容路径。超时、取消、传输失败和契约不满足分别使用 `Timeout`、`Canceled`、`Transport` 和 `ContractViolation`。++业务代码应使用类型化入口:++```rust+let result = client.call_typed::<Response>(method, params, timeout, cancel).await;+if let Err(error) = &result {+ let decision = RecoveryPolicy::decide(error, RecoveryScope::UserOperation);+ // 只执行 Session/Runtime 恢复,不重放当前用户 SQL。+}+```++`AgentRuntimeClient::call` 和 `AgentCallError::into_legacy_string` 仅用于尚未迁移的字符串边界。旧字符串只有在 `try_agent_error_from_legacy` 能证明其来自 Agent 调用通道时才恢复为 Agent 错误;不要在 `query`、`schema`、`connection`、`keepalive` 或 UI 中增加新的文本分类规则。++## 公共错误对象++Rust `BackendError` 的字段由 catalog 构造,字段定义如下(JSON 使用 camelCase):++```json+{+ "version": 1,+ "code": "DBX-JDBC-4001",+ "messageKey": "backendErrors.jdbc.sqlFailed",+ "messageParams": { "stage": "execute" },+ "source": "jdbcAgent",+ "operationOutcome": "unknown",+ "detail": "relation missing_table does not exist",+ "diagnostics": {+ "category": "sql",+ "stage": "execute",+ "sqlState": "42P01",+ "vendorCode": 0,+ "exceptionClass": "java.sql.SQLException"+ }+}+```++约束:++- `version` 当前为 `1`;`code`、`messageKey` 和字段含义发布后不可复用或改义。+- `source` 只能是 `jdbcAgent`、`jdbcAgentLegacy` 或 `legacyBackend`。+- `operationOutcome` 只能是 `not_started` 或 `unknown`。结果未知时不能自动重放用户操作。+- `messageParams` 只能包含 catalog 声明的 string、number、boolean 标量,不得携带 SQL、URL、凭据或任意对象。+- Rust 字段保持私有,新增错误必须通过 catalog 构造,避免 code、key 和参数声明漂移。++## 错误码 catalog++| code | 含义 |+| --- | --- |+| `DBX-JDBC-1001` | 连接建立失败 |+| `DBX-JDBC-1002` | 已建立连接中断 |+| `DBX-JDBC-2001` | 操作超时且尚未开始 |+| `DBX-JDBC-2002` | 操作超时但结果未知 |+| `DBX-JDBC-2003` | 操作取消 |+| `DBX-JDBC-3001` | 资源繁忙,操作尚未开始 |+| `DBX-JDBC-3002` | Runtime 被替换 |+| `DBX-JDBC-4001` | 数据库 SQL 执行失败 |+| `DBX-JDBC-5001` | Agent 传输或协议失败 |+| `DBX-JDBC-5002` | Agent 错误上下文违反契约 |+| `DBX-JDBC-9001` | 旧 Agent 错误无法可靠分类 |+| `DBX-LEGACY-0001` | 非 Agent 或未迁移的字符串错误 |++新增错误码时:++1. 在 `crates/dbx-core/src/backend_error.rs` 的 catalog 中增加唯一 code、`messageKey` 和参数声明。+2. 为所有 locale 增加相同 key,并扩展 catalog 完整性测试。+3. 增加 Rust 映射和序列化测试,以及前端 normalize/翻译测试。+4. 若错误来自 Agent,先在 `AgentErrorContext` 中定义可验证的事实和合法组合,再添加 catalog 映射;不要用错误文本补分类。++## detail 与安全边界++`detail` 是服务端诊断的可选补充,不是分类依据。Agent 错误映射会调用 `safe_detail`:++- 最多保留 512 字节的 UTF-8 文本;换行、制表符和连续空白会折叠为单个空格,空内容会被丢弃。+- 过滤 JDBC URL、密码、token、授权头、密钥、Session 标识等敏感标记。+- 过滤包含 SQL 语句关键字的内容,避免把完整 SQL 回显给用户。+- `agentSessionId`、重试标记和内部恢复字段不会进入公共 envelope。+- Rust 查询执行器生成的查询超时会使用 `DBX-JDBC-2002`(阶段 `execute`)摘要,同时保留安全的超时诊断 detail;它不会作为 `DBX-LEGACY-0001` 展示。+- PostgreSQL native driver 返回的标准服务端 `ERROR:` 诊断会使用 `DBX-JDBC-4001`(阶段 `execute`)摘要并保留安全 detail;连接、超时、取消和清理错误不使用该分类。+- 超时和取消没有服务端 detail 时只返回摘要;被过滤的 detail 也不会使用替代文本冒充原始错误。++## 传输边界++### Tauri Desktop++查询命令将 `QueryExecutionError` 映射为 `BackendError`。单语句和事务查询即使通过 `execute_multi` 命令执行,`dbx-core` 也会在整个 multi-query 核心链路中保留 `QueryExecutionError`,直到 Tauri 边界才转换为 `BackendError`;不得先降级为字符串再重建 envelope。`apps/desktop/src/lib/backend/tauri.ts` 在查询失败时抛出 `BackendErrorException`,前端因此可以同时取得 `messageKey` 和安全 `detail`。++### HTTP Web++`crates/dbx-web` 的 multi-query 路由也消费 typed 核心入口,并将 `AppError` 序列化为同一套 envelope;当前响应使用 `BackendError::without_detail()`,因此 HTTP 客户端只获得稳定摘要身份,不获得 detail。HTTP status 只表示传输结果,不能替代或改变 `BackendError.code`。++### 多语句查询++`ExecuteMultiResult.error` 和进度事件中的 `error` 是权威的结构化错误字段,`execution_error` 表示该结果确实失败。已经进入 typed 通用逐语句路径的错误必须直接从 `QueryExecutionError` 生成该字段,不能从兼容字符串反向推断。MySQL 和 SQL Server 的专用 batch executor 当前仍是字符串驱动边界,只有在驱动层提供可验证的 typed failure facts 后才能迁移,不能在 query/UI 层按错误正文补分类。旧的 `Error` 行仅用于兼容;真实查询结果中名为 `Error` 的普通列不能被当作失败。++## 前端展示规则++`normalizeBackendError` 只接受完整且类型正确的 envelope;`detail` 如果存在必须是 string。`translateBackendError` 的结构化路径为:++1. 使用 `messageKey` 和 `messageParams` 生成当前 locale 的自定义摘要。+2. 若 `detail` 非空且不同于摘要,在摘要后追加空行和 detail。+3. 无法识别的旧字符串继续原样展示或按兼容 pattern 翻译。++catch 到异常时必须把原始对象传给翻译器:++```ts+translateBackendError(t, error)+```++不要先执行 `error.message || String(error)`,否则会丢失 `messageKey`、参数和服务端 detail。`BackendErrorException`、嵌套的 `{ error }`/`{ backendError }` 和普通 `Error` 都由 `normalizeBackendError` 统一处理。++## 恢复规则++- `operationOutcome=unknown`:禁止自动重放 SQL、写入、DDL、事务和批处理。+- 用户操作:即使 Agent 声明可重试,也只做 Session/Runtime 恢复并向用户返回原错误。+- 只读 metadata:只有 connection + quarantine 场景可以新建 Session 重试,最多一次。+- `replace_runtime`:移除共享同一 Runtime 的路由;最终决定权在 Rust,不在 Agent 或前端。+- contract violation、timeout、cancel:至少隔离当前 Session;旧 Session 的迟到结果不得影响新的路由代际。++## 提交前检查++```text+cargo fmt --all -- --check+cargo clippy -j 1 -p dbx-core --no-default-features --all-targets -- -D warnings+cargo test -j 1 -p dbx-core --no-default-features --lib backend_error::tests+cargo test -j 1 -p dbx-core --no-default-features --lib agent_recovery::tests+cargo check -j 1 -p dbx-web --no-default-features+pnpm typecheck+pnpm vitest run apps/desktop/src/i18n/__tests__/backendErrors.spec.ts+```diff --git a/packages/app-tests/dataTabActivation.test.ts b/packages/app-tests/dataTabActivation.test.tsindex f570ab4b9c..83c9aaea8f 100644--- a/packages/app-tests/dataTabActivation.test.ts+++ b/packages/app-tests/dataTabActivation.test.ts@@ -42,6 +42,22 @@ test("activates an existing data table tab with a usable result", () => {);});+test("activates a successful data table tab with a real Error column", () => {+ assert.equal(+ canActivateExistingDataTableTab(+ dataTab({+ result: {+ columns: ["Error"],+ rows: [["valid value"]],+ affected_rows: 0,+ execution_time_ms: 1,+ },+ }),+ ),+ true,+ );+});+test("reloads restored data table tabs without a result", () => {assert.equal(canActivateExistingDataTableTab(dataTab()), false);});@@ -55,6 +71,7 @@ test("reloads existing data table tabs showing an error result", () => {rows: [["MySQL connection failed: Input/output error: No route to host (os error 65)"]],affected_rows: 0,execution_time_ms: 0,+ execution_error: true,},}),),@@ -132,6 +149,7 @@ test("double activation preserves restored and error recovery behavior", () => {rows: [["connection failed"]],affected_rows: 0,execution_time_ms: 0,+ execution_error: true,},}),"double",diff --git a/packages/app-tests/queryStore.test.ts b/packages/app-tests/queryStore.test.tsindex 962e3255dc..d3a9596b8f 100644--- a/packages/app-tests/queryStore.test.ts+++ b/packages/app-tests/queryStore.test.ts@@ -5857,6 +5857,7 @@ test("failed schema session reset blocks query and Oracle explain execution", asconst queryTab = store.tabs.find((tab) => tab.id === queryTabId)!;assert.equal(executeRequests, 0);assert.equal(queryTab.result?.execution_error, true);+ assert.equal(queryTab.result?.error?.detail, "reset failed");assert.match(String(queryTab.result?.rows[0]?.[0]), /reset failed/i);store.updateSchema(explainTabId, undefined);diff --git a/packages/app-tests/tabPresentation.test.ts b/packages/app-tests/tabPresentation.test.tsindex 1ece4682dc..0241cfb517 100644--- a/packages/app-tests/tabPresentation.test.ts+++ b/packages/app-tests/tabPresentation.test.ts@@ -320,7 +320,7 @@ test("result grid cache key includes result run id and statement result index",test("execution summary items include table and non-table statement results", () => {const items = executionSummaryItems({- results: [result([]), result(["id"]), { ...result(["Error"]), rows: [["boom"]] }],+ results: [result([]), result(["id"]), { ...result(["Error"]), rows: [["boom"]], execution_error: true }],});assert.deepEqual(diff --git a/src-tauri/src/commands/mcp.rs b/src-tauri/src/commands/mcp.rsindex c1ca6b6365..09a2a8c5b5 100644--- a/src-tauri/src/commands/mcp.rs+++ b/src-tauri/src/commands/mcp.rs@@ -472,6 +472,7 @@ fn user_shell_node_candidate() -> Option<NodeRuntimeCandidate> {Some(NodeRuntimeCandidate { node_path })}+#[cfg(not(windows))]fn prefixed_output_path(output: &str, prefix: &str) -> Option<PathBuf> {output.lines()@@ -834,7 +835,7 @@ fn path_string(path: &Path) -> String {pub(crate) fn locate_command(command: &str) -> Option<String> {#[cfg(windows)]{- return locate_windows_command(command);+ locate_windows_command(command)}#[cfg(not(windows))]{@@ -909,7 +910,7 @@ fn command_output(command: &str, args: &[&str]) -> Result<CommandOutput, String>#[cfg(windows)]{- return run_windows_command_candidates(command, args).or(direct);+ run_windows_command_candidates(command, args).or(direct)}#[cfg(not(windows))]@@ -986,7 +987,7 @@ fn windows_common_command_dirs() -> Vec<std::path::PathBuf> {#[cfg(windows)]fn run_command_through_user_shell(command: &str, args: &[&str]) -> Result<CommandOutput, String> {let script = windows_command_script(command, args);- let mut output = run_command("powershell.exe", &["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script])?;+ let mut output = run_command("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script])?;output.stdout = stdout_after_shell_marker(&output.stdout);Ok(output)}@@ -1080,13 +1081,12 @@ mod tests {#[cfg(windows)]use super::first_windows_command_path;#[cfg(not(windows))]- use super::{bash_login_script, NodeRuntimeCandidate};+ use super::{bash_login_script, prefixed_output_path, NodeRuntimeCandidate};use super::{canonical_runtime_path, is_mcp_compatible_node_version, mcp_command_for_runtime, mcp_native_binary_path_for,mcp_package, normalized_reported_path, npm_cli_candidates, parse_minimum_node_version, parse_node_version,- prefer_runtime, prefixed_output_path, require_managed_mcp_command, resolve_managed_mcp_command,- stdout_after_shell_marker, NodeRuntime, NodeVersion, MCP_MIN_NODE_VERSION_REQUIREMENT, MCP_PACKAGE_NAME,- SHELL_COMMAND_MARKER,+ prefer_runtime, require_managed_mcp_command, resolve_managed_mcp_command, stdout_after_shell_marker,+ NodeRuntime, NodeVersion, MCP_MIN_NODE_VERSION_REQUIREMENT, MCP_PACKAGE_NAME, SHELL_COMMAND_MARKER,};#[cfg(not(windows))]use super::{shell_command_script, shell_quote};@@ -1151,6 +1151,7 @@ mod tests {}#[test]+ #[cfg(not(windows))]fn prefixed_output_path_ignores_empty_values() {let output = "node=/opt/node/bin/node\nmissing=\n";diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 19b50fecb5..ed4904f8e2 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -3,6 +3,7 @@ use std::time::Instant;use tauri::{AppHandle, Emitter, State};use crate::commands::connection::AppState;+use dbx_core::backend_error::BackendError;use dbx_core::db;use dbx_core::models::connection::DatabaseType;use dbx_core::query_cancel::RunningTaskMetadata;@@ -18,7 +19,8 @@ struct ExecuteMultiProgress {success: bool,execution_time_ms: u128,affected_rows: u64,- error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ error: Option<BackendError>,}#[tauri::command]@@ -38,7 +40,7 @@ pub async fn execute_query(client_session_id: Option<String>,timeout_secs: Option<u64>,execution_mode: Option<dbx_core::query::QueryExecutionMode>,-) -> Result<db::QueryResult, String> {+) -> Result<db::QueryResult, BackendError> {let execution_id = execution_id.filter(|id| !id.trim().is_empty());let registered_query = execution_id.as_ref().map(|id| {state.running_queries.register_task(@@ -48,7 +50,7 @@ pub async fn execute_query(});let cancel_token = registered_query.as_ref().map(|query| query.token());- dbx_core::query::execute_sql_statement_with_options(+ dbx_core::query::execute_sql_statement_with_options_typed(&state,&connection_id,&database,@@ -69,6 +71,7 @@ pub async fn execute_query(},).await+ .map_err(dbx_core::query::QueryExecutionError::into_backend_error)}#[tauri::command]@@ -91,7 +94,7 @@ pub async fn execute_multi(use_transaction: Option<bool>,continue_on_error: Option<bool>,execution_mode: Option<dbx_core::query::QueryExecutionMode>,-) -> Result<Vec<dbx_core::query::ExecuteMultiResult>, String> {+) -> Result<Vec<dbx_core::query::ExecuteMultiResult>, BackendError> {let execution_id = execution_id.filter(|id| !id.trim().is_empty());let registered_query = execution_id.as_ref().map(|id| {state.running_queries.register_task(@@ -130,7 +133,7 @@ pub async fn execute_multi(schema);- let result = dbx_core::query::execute_multi_core_with_options_for_client_and_progress(+ let result = dbx_core::query::execute_multi_core_with_options_for_client_and_progress_typed(&state,&connection_id,&database,@@ -169,7 +172,7 @@ pub async fn execute_multi(error),}- result+ result.map_err(dbx_core::query::QueryExecutionError::into_backend_error)}#[tauri::command]