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(dbx-core): improve duckdb query cancellation
miracle30b9460442cb
diff --git a/apps/desktop/src/stores/__tests__/queryStore.cancel.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.cancel.spec.tsindex 08b041c0b2..07e20831ac 100644--- a/apps/desktop/src/stores/__tests__/queryStore.cancel.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.cancel.spec.ts@@ -48,4 +48,30 @@ describe("queryStore cancel timeout recovery", () => {});expect(store.tabs[0]?.result?.rows[0]?.[0]).toContain("Cancel request timed out");}, 15_000);++ it("clears cancelling state when cancel is acknowledged but execution does not settle", async () => {+ const cancelQuery = vi.fn(() => Promise.resolve(true));++ vi.doMock("@/lib/api", () => ({ cancelQuery }));++ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("duckdb-1", "main", "query_1");+ store.setExecutingWithId(tabId, "exec-1");++ const cancel = store.cancelTabExecution(tabId);+ await vi.advanceTimersByTimeAsync(1);+ expect(await cancel).toBe(true);+ expect(store.tabs[0]?.isCancelling).toBe(true);++ await vi.advanceTimersByTimeAsync(2_001);++ expect(cancelQuery).toHaveBeenCalledWith("exec-1");+ expect(store.tabs[0]).toMatchObject({+ isExecuting: false,+ isCancelling: false,+ executionId: undefined,+ });+ expect(store.tabs[0]?.result?.rows[0]?.[0]).toContain("Query canceled");+ }, 15_000);});diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 2ef3b59a9d..0b356fa42d 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -49,6 +49,7 @@ import type { SavedSqlFile } from "@/types/database";const ORACLE_LIKE_METADATA_TYPES = new Set<string>(["oracle", "dameng", "oceanbase-oracle"]);const BACKGROUND_CLIENT_SESSION_SUFFIXES = ["count", "explain", "export"] as const;const CANCEL_QUERY_TIMEOUT_MS = 10_000;+const CANCEL_ACK_SETTLE_TIMEOUT_MS = 2_000;type CloseConfirmContext = "tab" | "batch" | "app";function cloneTabDraft<T>(value: T): T {@@ -1538,6 +1539,22 @@ export const useQueryStore = defineStore("query", () => {tab.executionId = undefined;}+ function clearAcknowledgedCancelIfStillRunning(id: string, executionId: string) {+ setTimeout(() => {+ const current = tabs.value.find((t) => t.id === id);+ if (!current || current.executionId !== executionId || !current.isCancelling) return;+ current.isExecuting = false;+ current.isCancelling = false;+ current.executionId = undefined;+ current.queryExecutionStartedAt = undefined;+ current.result = toErrorResult(new Error("Query canceled"));+ current.results = undefined;+ current.activeResultIndex = undefined;+ current.resultSessionId = undefined;+ touchResult(current);+ }, CANCEL_ACK_SETTLE_TIMEOUT_MS);+ }+async function executeCurrentTab() {const tab = tabs.value.find((t) => t.id === activeTabId.value);if (!tab || !tab.sql.trim()) return;@@ -2403,6 +2420,9 @@ export const useQueryStore = defineStore("query", () => {tab.isCancelling = true;try {const canceled = await withCancelQueryTimeout(api.cancelQuery(executionId));+ if (canceled) {+ clearAcknowledgedCancelIfStillRunning(id, executionId);+ }if (!canceled) {const current = tabs.value.find((t) => t.id === id);if (current && current.executionId === executionId) {diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 34e842f5be..9358de5ede 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -38,7 +38,7 @@ const POOL_CLOSE_TIMEOUT_SECS: u64 = 3;#[cfg(feature = "duckdb-bundled")]mod duckdb_types {use std::sync::Arc;- pub type DuckDbHandle = Arc<std::sync::Mutex<duckdb::Connection>>;+ pub type DuckDbHandle = Arc<crate::db::duckdb_driver::DuckDbConnection>;pub type ExternalTabularHandle = Arc<crate::external::ExternalPool>;}#[cfg(not(feature = "duckdb-bundled"))]@@ -1630,6 +1630,76 @@ impl AppState {}}+ #[cfg(feature = "duckdb-bundled")]+ pub fn spawn_duckdb_pool_cleanup(&self, pool_key: String, con: DuckDbHandle) {+ let connections = self.connections.clone();+ let keepalive_tasks = self.keepalive_tasks.clone();+ let pool_activity = self.pool_activity.clone();+ let postgres_cancel_contexts = self.postgres_cancel_contexts.clone();+ tokio::spawn(async move {+ while Arc::strong_count(&con) > 2 {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ if let Some(handle) = keepalive_tasks.write().await.remove(&pool_key) {+ handle.abort();+ }+ pool_activity.write().await.remove(&pool_key);+ postgres_cancel_contexts.write().await.remove(&pool_key);+ let removed = {+ let mut conns = connections.write().await;+ match conns.get(&pool_key) {+ Some(PoolKind::DuckDb(current)) if Arc::ptr_eq(current, &con) => conns.remove(&pool_key),+ _ => None,+ }+ };+ if let Some(pool) = removed {+ // Keep the old DuckDB pool marked as draining until it is no longer+ // visible in the pool map, otherwise a concurrent query could reuse it.+ con.clear_draining();+ drop(con);+ close_pool_kind_with_timeout(pool_key, pool).await;+ }+ });+ }++ #[cfg(feature = "duckdb-bundled")]+ pub fn spawn_duckdb_draining_cleanup(+ &self,+ pool_key: String,+ con: DuckDbHandle,+ task: JoinHandle<Result<db::QueryResult, String>>,+ ) {+ let connections = self.connections.clone();+ let keepalive_tasks = self.keepalive_tasks.clone();+ let pool_activity = self.pool_activity.clone();+ let postgres_cancel_contexts = self.postgres_cancel_contexts.clone();+ tokio::spawn(async move {+ let _ = task.await;+ while Arc::strong_count(&con) > 2 {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ if let Some(handle) = keepalive_tasks.write().await.remove(&pool_key) {+ handle.abort();+ }+ pool_activity.write().await.remove(&pool_key);+ postgres_cancel_contexts.write().await.remove(&pool_key);+ let removed = {+ let mut conns = connections.write().await;+ match conns.get(&pool_key) {+ Some(PoolKind::DuckDb(current)) if Arc::ptr_eq(current, &con) => conns.remove(&pool_key),+ _ => None,+ }+ };+ if let Some(pool) = removed {+ // Keep the old DuckDB pool marked as draining until it is no longer+ // visible in the pool map, otherwise a concurrent query could reuse it.+ con.clear_draining();+ drop(con);+ close_pool_kind_with_timeout(pool_key, pool).await;+ }+ });+ }+pub async fn close_database_pool(&self, connection_id: &str, database: Option<&str>) -> Result<bool, String> {let db_type = {let configs = self.configs.read().await;diff --git a/crates/dbx-core/src/db/duckdb_driver.rs b/crates/dbx-core/src/db/duckdb_driver.rsindex ad7cf93942..2da89c8e34 100644--- a/crates/dbx-core/src/db/duckdb_driver.rs+++ b/crates/dbx-core/src/db/duckdb_driver.rs@@ -2,18 +2,56 @@use std::fs;use std::path::Path;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::sync::Mutex;+pub struct DuckDbConnection {+ connection: Mutex<duckdb::Connection>,+ interrupt_handle: Arc<duckdb::InterruptHandle>,+ draining: AtomicBool,+}++impl DuckDbConnection {+ pub fn new(connection: duckdb::Connection) -> Self {+ let interrupt_handle = connection.interrupt_handle();+ Self { connection: Mutex::new(connection), interrupt_handle, draining: AtomicBool::new(false) }+ }++ pub fn lock(&self) -> std::sync::LockResult<std::sync::MutexGuard<'_, duckdb::Connection>> {+ self.connection.lock()+ }++ pub fn interrupt_handle(&self) -> Arc<duckdb::InterruptHandle> {+ self.interrupt_handle.clone()+ }++ pub fn mark_draining(&self) {+ self.draining.store(true, Ordering::SeqCst);+ }++ pub fn clear_draining(&self) {+ self.draining.store(false, Ordering::SeqCst);+ }++ pub fn is_draining(&self) -> bool {+ self.draining.load(Ordering::SeqCst)+ }++ fn into_inner(self) -> std::sync::LockResult<duckdb::Connection> {+ self.connection.into_inner()+ }+}+/// Connects to a DuckDb database file with file validation.////// # Arguments/// * `path` - The file path to the DuckDb database////// # Returns-/// * `Ok(Arc<Mutex<duckdb::Connection>>)` on successful connection+/// * `Ok(Arc<DuckDbConnection>)` on successful connection/// * `Err(String)` with descriptive error message if connection fails-pub fn connect_path(path: &str) -> Result<Arc<Mutex<duckdb::Connection>>, String> {+pub fn connect_path(path: &str) -> Result<Arc<DuckDbConnection>, String> {let is_memory = is_memory_database_path(path);if !is_memory {validate_duckdb_path(path)?;@@ -23,7 +61,7 @@ pub fn connect_path(path: &str) -> Result<Arc<Mutex<duckdb::Connection>>, Stringlet connection = if is_memory { duckdb::Connection::open_in_memory() } else { duckdb::Connection::open(path) }.map_err(|e| format!("DuckDb connection failed: {e}"))?;- Ok(Arc::new(Mutex::new(connection)))+ Ok(Arc::new(DuckDbConnection::new(connection)))}fn validate_duckdb_path(path: &str) -> Result<(), String> {@@ -78,9 +116,9 @@ pub fn is_memory_database_path(path: &str) -> bool {/// Unlike relying on Drop, this calls `duckdb_disconnect` synchronously/// so the file handle is released before this function returns./// On Windows this prevents "file already in use" errors when reconnecting.-pub fn close_connection(con: Arc<Mutex<duckdb::Connection>>) {+pub fn close_connection(con: Arc<DuckDbConnection>) {match Arc::try_unwrap(con) {- Ok(mutex) => match mutex.into_inner() {+ Ok(handle) => match handle.into_inner() {Ok(conn) => {let _ = conn.close();}@@ -110,6 +148,14 @@ mod tests {assert_eq!(value, 42);}+ #[test]+ fn interrupt_handle_is_available_while_connection_is_locked() {+ let con = connect_path(":memory:").expect("connect in-memory DuckDB");+ let _locked = con.lock().expect("lock connection");++ let _interrupt_handle = con.interrupt_handle();+ }+#[test]fn connect_path_replaces_empty_placeholder_file() {let path = std::env::temp_dir().join(format!("dbx-duckdb-empty-{}.duckdb", uuid::Uuid::new_v4()));diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 8b410dd6e0..fcbe5fc808 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -32,6 +32,8 @@ pub const MAX_ROWS: usize = 10000;pub const QUERY_CANCELED: &str = "Query canceled";#[cfg(feature = "duckdb-bundled")]const DUCKDB_INTERRUPT_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);+#[cfg(feature = "duckdb-bundled")]+const DUCKDB_DRAINING_MESSAGE: &str = "上一条 DuckDB 查询仍在停止,请稍后重试。";#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PoolErrorAction {@@ -542,26 +544,51 @@ pub fn duckdb_execute_with_max_rows(}#[cfg(feature = "duckdb-bundled")]-async fn wait_for_duckdb_task_with_interrupt(+enum DuckDbTaskWait {+ Finished(Result<db::QueryResult, String>),+ Draining { error: String, task: JoinHandle<Result<db::QueryResult, String>> },+}++#[cfg(feature = "duckdb-bundled")]+fn duckdb_join_result(+ result: Result<Result<db::QueryResult, String>, tokio::task::JoinError>,+) -> Result<db::QueryResult, String> {+ result.map_err(|e| e.to_string())?+}++#[cfg(feature = "duckdb-bundled")]+async fn interrupt_and_drain_duckdb_task(+ interrupt_handle: std::sync::Arc<duckdb::InterruptHandle>,+ mut task: JoinHandle<Result<db::QueryResult, String>>,+ error: String,+) -> DuckDbTaskWait {+ interrupt_handle.interrupt();+ match timeout(DUCKDB_INTERRUPT_DRAIN_TIMEOUT, &mut task).await {+ Ok(result) => {+ let _ = result;+ DuckDbTaskWait::Finished(Err(error))+ }+ Err(_) => DuckDbTaskWait::Draining { error, task },+ }+}++#[cfg(feature = "duckdb-bundled")]+async fn wait_for_duckdb_task_with_interrupt_outcome(cancel_token: Option<CancellationToken>,timeout_duration: Option<Duration>,interrupt_handle: std::sync::Arc<duckdb::InterruptHandle>,mut task: JoinHandle<Result<db::QueryResult, String>>,-) -> Result<db::QueryResult, String> {+) -> DuckDbTaskWait {match (cancel_token, timeout_duration) {(Some(token), Some(duration)) => {tokio::select! {biased;_ = token.cancelled() => {- interrupt_handle.interrupt();- drain_interrupted_duckdb_task(&mut task).await;- Err(canceled_error())+ interrupt_and_drain_duckdb_task(interrupt_handle, task, canceled_error()).await}- result = &mut task => result.map_err(|e| e.to_string())?,+ result = &mut task => DuckDbTaskWait::Finished(duckdb_join_result(result)),_ = sleep(duration) => {- interrupt_handle.interrupt();- drain_interrupted_duckdb_task(&mut task).await;- Err(timeout_error())+ interrupt_and_drain_duckdb_task(interrupt_handle, task, timeout_error()).await}}}@@ -569,30 +596,34 @@ async fn wait_for_duckdb_task_with_interrupt(tokio::select! {biased;_ = token.cancelled() => {- interrupt_handle.interrupt();- drain_interrupted_duckdb_task(&mut task).await;- Err(canceled_error())+ interrupt_and_drain_duckdb_task(interrupt_handle, task, canceled_error()).await}- result = &mut task => result.map_err(|e| e.to_string())?,+ result = &mut task => DuckDbTaskWait::Finished(duckdb_join_result(result)),}}(None, Some(duration)) => {tokio::select! {- result = &mut task => result.map_err(|e| e.to_string())?,+ result = &mut task => DuckDbTaskWait::Finished(duckdb_join_result(result)),_ = sleep(duration) => {- interrupt_handle.interrupt();- drain_interrupted_duckdb_task(&mut task).await;- Err(timeout_error())+ interrupt_and_drain_duckdb_task(interrupt_handle, task, timeout_error()).await}}}- (None, None) => task.await.map_err(|e| e.to_string())?,+ (None, None) => DuckDbTaskWait::Finished(duckdb_join_result(task.await)),}}#[cfg(feature = "duckdb-bundled")]-async fn drain_interrupted_duckdb_task(task: &mut JoinHandle<Result<db::QueryResult, String>>) {- let _ = timeout(DUCKDB_INTERRUPT_DRAIN_TIMEOUT, task).await;+async fn wait_for_duckdb_task_with_interrupt(+ cancel_token: Option<CancellationToken>,+ timeout_duration: Option<Duration>,+ interrupt_handle: std::sync::Arc<duckdb::InterruptHandle>,+ task: JoinHandle<Result<db::QueryResult, String>>,+) -> Result<db::QueryResult, String> {+ match wait_for_duckdb_task_with_interrupt_outcome(cancel_token, timeout_duration, interrupt_handle, task).await {+ DuckDbTaskWait::Finished(result) => result,+ DuckDbTaskWait::Draining { error, .. } => Err(error),+ }}#[cfg(feature = "duckdb-bundled")]@@ -821,6 +852,11 @@ pub fn canceled_error() -> String {QUERY_CANCELED.to_string()}+#[cfg(feature = "duckdb-bundled")]+pub fn duckdb_draining_error() -> String {+ DUCKDB_DRAINING_MESSAGE.to_string()+}+pub fn is_canceled(cancel_token: &Option<CancellationToken>) -> bool {cancel_token.as_ref().map(|token| token.is_cancelled()).unwrap_or(false)}@@ -940,7 +976,11 @@ pub async fn do_execute(#[cfg(feature = "duckdb-bundled")]PoolKind::DuckDb(con) => {let con = con.clone();- let interrupt_handle = con.lock().map_err(|e| e.to_string())?.interrupt_handle();+ if con.is_draining() {+ drop(connections);+ return Err(duckdb_draining_error());+ }+ let interrupt_handle = con.interrupt_handle();if let Some(ref execution_id) = options.execution_id {let cancel_interrupt_handle = interrupt_handle.clone();state.running_queries.register_interrupt(execution_id, move || {@@ -952,11 +992,28 @@ pub async fn do_execute(let attached_names = _duckdb_attached_names;let max_rows = options.max_rows;drop(connections);+ let task_con = con.clone();let task = tokio::task::spawn_blocking(move || {- let con = con.lock().map_err(|e| e.to_string())?;+ let con = task_con.lock().map_err(|e| e.to_string())?;duckdb_execute_for_database(&con, &attached_names, database.as_deref(), &sql, max_rows)});- wait_for_duckdb_task_with_interrupt(cancel_token, query_timeout, interrupt_handle, task).await+ let result =+ wait_for_duckdb_task_with_interrupt_outcome(cancel_token, query_timeout, interrupt_handle, task).await;+ match result {+ DuckDbTaskWait::Finished(result) => {+ if matches!(result.as_ref(), Err(err) if err == QUERY_CANCELED || is_dbx_query_timeout_error(&err.to_lowercase()))+ {+ con.mark_draining();+ state.spawn_duckdb_pool_cleanup(pool_key.to_string(), con);+ }+ result+ }+ DuckDbTaskWait::Draining { error, task } => {+ con.mark_draining();+ state.spawn_duckdb_draining_cleanup(pool_key.to_string(), con, task);+ Err(error)+ }+ }}#[cfg(not(feature = "duckdb-bundled"))]PoolKind::DuckDb(_) => {@@ -2767,6 +2824,7 @@ pub async fn rollback_manual_transaction(state: &AppState, txn_session_id: &str)mod tests {use super::*;use crate::models::connection::{default_redis_key_separator, ConnectionConfig, DatabaseType};+ use crate::storage::Storage;fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {ConnectionConfig {@@ -2877,34 +2935,182 @@ mod tests {#[cfg(feature = "duckdb-bundled")]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn duckdb_timeout_interrupts_running_task_and_releases_connection() {- let con = std::sync::Arc::new(std::sync::Mutex::new(duckdb::Connection::open_in_memory().unwrap()));- let interrupt_handle = con.lock().unwrap().interrupt_handle();+ async fn duckdb_timeout_interrupts_running_task_without_waiting_for_it_to_finish() {+ let con = std::sync::Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(+ duckdb::Connection::open_in_memory().unwrap(),+ ));+ let interrupt_handle = con.interrupt_handle();let running_con = con.clone();let task = tokio::task::spawn_blocking(move || {let con = running_con.lock().map_err(|e| e.to_string())?;duckdb_execute_with_max_rows(&con, "SELECT sum(sin(i::DOUBLE)) FROM range(10000000000) tbl(i)", None)});+ let started = std::time::Instant::now();let result =wait_for_duckdb_task_with_interrupt(None, Some(Duration::from_millis(10)), interrupt_handle, task).await;assert_eq!(result.unwrap_err(), timeout_error());+ assert!(started.elapsed() < Duration::from_secs(5));+ }++ #[cfg(feature = "duckdb-bundled")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn duckdb_cancel_keeps_pool_draining_until_references_drop() {+ let dir = std::env::temp_dir().join(format!("dbx-query-duckdb-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 pool_key = "duckdb-1";+ let con = std::sync::Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(+ duckdb::Connection::open_in_memory().unwrap(),+ ));+ let extra_reference = con.clone();+ state.connections.write().await.insert(pool_key.to_string(), PoolKind::DuckDb(con));+ state.configs.write().await.insert(pool_key.to_string(), test_connection_config(DatabaseType::DuckDb));- let follow_con = con.clone();- let follow_up = timeout(- Duration::from_secs(5),- tokio::task::spawn_blocking(move || {- let con = follow_con.lock().map_err(|e| e.to_string())?;- duckdb_execute_with_max_rows(&con, "SELECT 1", None)- }),+ let token = CancellationToken::new();+ let cancel_token = token.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(10)).await;+ cancel_token.cancel();+ });++ let result = do_execute(+ &state,+ pool_key,+ db::mysql::MySqlQueryDialect::default(),+ Some("main"),+ "SELECT sum(sin(i::DOUBLE)) FROM range(10000000000) tbl(i)",+ None,+ Some(token),+ QueryExecutionOptions::default(),)+ .await;++ assert_eq!(result.unwrap_err(), QUERY_CANCELED);+ let still_present = {+ let conns = state.connections.read().await;+ matches!(conns.get(pool_key), Some(PoolKind::DuckDb(current)) if current.is_draining())+ };+ assert!(still_present);++ drop(extra_reference);+ timeout(Duration::from_secs(5), async {+ loop {+ if !state.connections.read().await.contains_key(pool_key) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ }).await- .expect("DuckDB connection should be released after timeout")- .expect("follow-up task should not panic")- .expect("follow-up query should succeed");+ .expect("draining DuckDB pool should be removed after references drop");+ }++ #[cfg(feature = "duckdb-bundled")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn duckdb_draining_pool_rejects_follow_up_query() {+ let dir = std::env::temp_dir().join(format!("dbx-query-duckdb-draining-{}", 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 pool_key = "duckdb-1";+ let con = std::sync::Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(+ duckdb::Connection::open_in_memory().unwrap(),+ ));+ con.mark_draining();+ state.connections.write().await.insert(pool_key.to_string(), PoolKind::DuckDb(con));+ state.configs.write().await.insert(pool_key.to_string(), test_connection_config(DatabaseType::DuckDb));++ let result = do_execute(+ &state,+ pool_key,+ db::mysql::MySqlQueryDialect::default(),+ Some("main"),+ "SELECT 1",+ None,+ None,+ QueryExecutionOptions::default(),+ )+ .await;++ assert_eq!(result.unwrap_err(), duckdb_draining_error());+ }++ #[cfg(feature = "duckdb-bundled")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn duckdb_draining_cleanup_removes_pool_after_task_finishes() {+ let dir = std::env::temp_dir().join(format!("dbx-query-duckdb-cleanup-{}", 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 pool_key = "duckdb-1";+ let con = std::sync::Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(+ duckdb::Connection::open_in_memory().unwrap(),+ ));+ con.mark_draining();+ state.connections.write().await.insert(pool_key.to_string(), PoolKind::DuckDb(con.clone()));- assert_eq!(follow_up.rows, vec![vec![serde_json::json!(1)]]);+ let task_con = con.clone();+ let task = tokio::task::spawn_blocking(move || {+ let _locked = task_con.lock().map_err(|e| e.to_string())?;+ std::thread::sleep(Duration::from_millis(100));+ Ok(empty_query_result(0))+ });+ state.spawn_duckdb_draining_cleanup(pool_key.to_string(), con.clone(), task);++ assert!(state.connections.read().await.contains_key(pool_key));+ drop(con);+ timeout(Duration::from_secs(5), async {+ loop {+ if !state.connections.read().await.contains_key(pool_key) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("draining cleanup should remove the DuckDB pool");+ }++ #[cfg(feature = "duckdb-bundled")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn duckdb_cleanup_keeps_draining_pool_while_extra_reference_exists() {+ let dir = std::env::temp_dir().join(format!("dbx-query-duckdb-cleanup-ref-{}", 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 pool_key = "duckdb-1";+ let con = std::sync::Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(+ duckdb::Connection::open_in_memory().unwrap(),+ ));+ con.mark_draining();+ state.connections.write().await.insert(pool_key.to_string(), PoolKind::DuckDb(con.clone()));++ let extra_reference = con.clone();+ let task = tokio::task::spawn_blocking(|| Ok(empty_query_result(0)));+ state.spawn_duckdb_draining_cleanup(pool_key.to_string(), con.clone(), task);+ tokio::time::sleep(Duration::from_millis(100)).await;++ let still_present = {+ let conns = state.connections.read().await;+ matches!(conns.get(pool_key), Some(PoolKind::DuckDb(current)) if current.is_draining())+ };+ assert!(still_present);++ drop(extra_reference);+ drop(con);+ timeout(Duration::from_secs(5), async {+ loop {+ if !state.connections.read().await.contains_key(pool_key) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("draining cleanup should remove the DuckDB pool after extra refs drop");}#[test]diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rsindex 65edada352..a7258cd853 100644--- a/crates/dbx-core/src/transfer.rs+++ b/crates/dbx-core/src/transfer.rs@@ -5631,7 +5631,7 @@ mod tests {con.execute_batch("CREATE SCHEMA analytics; CREATE TABLE analytics.items(id INTEGER);").unwrap();let state = AppState::new(storage);- let con = Arc::new(std::sync::Mutex::new(con));+ let con = Arc::new(crate::db::duckdb_driver::DuckDbConnection::new(con));state.connections.write().await.insert("duckdb-1".to_string(), PoolKind::DuckDb(con));state.configs.write().await.insert("duckdb-1".to_string(), duckdb_test_config("duckdb-1"));