Skip to content

Database initialization race condition in HTTP dev server tests #255

Closed

Description

@malibio

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

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:

  1. Creates new DatabaseService::new(db_path)
  2. Calls initialize_schema() (runs CREATE TABLE IF NOT EXISTS)
  3. Swaps services in AppState using RwLock::write()

However, there's no synchronization between the database swap and in-flight connections:

  • libsql maintains an internal connection pool per Database instance
  • 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

  1. Database swap succeeds (confirmed by logs)
  2. Node creation typically works (uses fresh connections)
  3. Node updates fail (uses cached/stale connections)
  4. 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 calls initialize_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>> in AppState
  • 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

  1. added
    bug
    on Oct 12, 2025
  2. 4 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbugtesting

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions