Repository navigation
Description
Bug: Database Initialization Race Condition in HTTP Dev Server Tests
Summary
Integration tests using the HTTP dev server experience HTTP 500 "no such table: nodes" errors due to a race condition in database connection management when rapidly swapping databases across test cases.
Impact
- Affects: All integration tests that use HTTP dev server adapter
- Current Status: 7/14 tests in
indent-outdent-operations.test.tsfailing - Blocks: Issue Fix Indent/Outdent Operations (12 test failures) #228 (Indent/Outdent Operations) verification
Problem Description
Symptom
When running integration tests sequentially:
- First test: Usually succeeds
- Subsequent tests: Fail with "HTTP 500: Internal Server Error - no such table: nodes"
Root Cause
Race condition in libsql connection pooling when dev server swaps databases
Each test creates a unique database file and calls /api/database/init?db_path=... to initialize it. The endpoint:
- Creates new
DatabaseService::new(db_path) - Calls
initialize_schema()(runsCREATE TABLE IF NOT EXISTS) - Swaps services in
AppStateusingRwLock::write()
However, there's no synchronization between the database swap and in-flight connections:
- libsql maintains an internal connection pool per
Databaseinstance - After swapping
AppState, old connections may still be cached/active - Subsequent operations may use stale connections pointing to previous test's database
Test Flow Pattern
Test 1: [Init DB A] → [Create Node] → [Update Node] ✓ Works
Test 2: [Init DB B] → [Create Node] → [Update Node in-flight] →
❌ Update uses stale connection to DB A or uninitialized connection to DB B
Evidence
Dev Server Logs
🔄 Database SWAPPED to: /tmp/test-...098-0ve5gm.db
📝 UPDATE request for node: node-2
❌ Node update failed for node-2: QueryFailed("no such table: nodes")
Key Observations
- Database swap succeeds (confirmed by logs)
- Node creation typically works (uses fresh connections)
- Node updates fail (uses cached/stale connections)
- Pattern is consistent across multiple test runs
Investigation Details
Code Locations
Backend:
/packages/desktop-app/src-tauri/src/dev_server/node_endpoints.rs:init_database()- Database swap endpoint/packages/core/src/db/database.rs:DatabaseService::new()- Creates database and callsinitialize_schema()/packages/core/src/db/database.rs:initialize_schema()- Runs schema creation
Test Infrastructure:
/packages/desktop-app/src/tests/utils/test-database.ts:initializeTestDatabase()- Test database setup
Related Architecture
The dev server uses:
- libsql (SQLite) for database access
- Axum for HTTP server with
Arc<RwLock<DatabaseService>>inAppState - Connection pooling via
self.db.connect()calls
Recommended Solutions
Option 1: Explicit Connection Draining (Recommended)
Add connection lifecycle management to DatabaseService:
impl DatabaseService {
pub async fn drain_connections(&self) -> Result<(), DatabaseError> {
// Add small delay to let pending operations complete
// libsql doesn't expose drain API, so we rely on timeout
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
Ok(())
}
}Then drain before swapping in init_database():
// Drain old connections before creating new service
{
let old_db = state.db.read()?;
old_db.drain_connections().await?;
}
// Create and swap new service
let new_db = DatabaseService::new(db_path).await?;
// ...swap logic...Option 2: Connection Per Request
Store database path instead of DatabaseService in AppState, create fresh connections per request:
pub struct AppState {
pub db_path: Arc<RwLock<PathBuf>>,
}
async fn update_node(...) -> Result<...> {
let db_path = state.db_path.read()?.clone();
let db = DatabaseService::new(db_path).await?;
// ...use db...
}Pros: Eliminates connection caching entirely
Cons: Performance overhead from connection creation
Option 3: Test Infrastructure Workaround
Remove duplicate initialization call in test-database.ts:
// Current: Makes TWO HTTP requests
await adapter.initializeDatabase(dbPath);
await tauriNodeService.initializeDatabase(dbPath);
// Fixed: Single request, update singleton directly
await adapter.initializeDatabase(dbPath);
(tauriNodeService as any).dbPath = dbPath;
(tauriNodeService as any).initialized = true;Note: This helps but doesn't fully solve the race condition.
Acceptance Criteria
- All integration tests pass reliably without HTTP 500 errors
- Database swaps don't leave stale connections
- Solution works across multiple sequential test runs
- No performance regression in dev server
Additional Context
This issue was discovered while working on Issue #228 (Fix Indent/Outdent Operations). The circular dependency fix for #228 is complete and correct, but cannot be verified due to this database initialization bug.
Related Issues: #228
Activity
Improve test database initialization (partial fix for #255)
Fix Indent/Outdent Operations (12 test failures) (#253)
Partial fix for Issue #255: Add connection draining and WAL checkpoin…
Improve test database synchronization and fix parallel execution issues
Fix database race condition with 100ms delay before swap (Issue #255)
Implement proper database race condition fix with connection draining…
Database initialization race condition in HTTP dev server tests (#259)
Partial fix for Issue #255: Add connection draining and WAL checkpoin…
Improve test database synchronization and fix parallel execution issues
Fix database race condition with 100ms delay before swap (Issue #255)
Merge branch 'main' into feature/issue-228-fix-remaining-tests
4 remaining items
Database initialization race condition in HTTP dev server tests (#259)
Merge branch 'main' into feature/issue-228-fix-remaining-tests
Fix Indent/Outdent Operations (12 test failures) (#253)
Partial fix for Issue #255: Add connection draining and WAL checkpoin…
Improve test database synchronization and fix parallel execution issues
Fix database race condition with 100ms delay before swap (Issue #255)
Database initialization race condition in HTTP dev server tests (#259)
Merge branch 'main' into feature/issue-228-fix-remaining-tests
Fix Indent/Outdent Operations (12 test failures) (#253)
Partial fix for Issue #255: Add connection draining and WAL checkpoin…
Improve test database synchronization and fix parallel execution issues
Fix database race condition with 100ms delay before swap (Issue #255)
Database initialization race condition in HTTP dev server tests (#259)
Merge branch 'main' into feature/issue-228-fix-remaining-tests
Delete the dead database-write-queue module to end its cross-file fla…