Skip to content

bug(aiosqlite): pool leaks connections between different database paths #360

@cofin

Description

@cofin

Description

When running multiple tests/operations with different database files, the aiosqlite pool appears to reuse connections from previous databases, causing "table already exists" errors even when using completely different database paths and config instances.

Reproduction

import tempfile
import asyncio
from sqlspec import SQLSpec
from sqlspec.adapters.aiosqlite import AiosqliteConfig

async def test():
    # Test 1 - creates table in db1
    with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as tmp1:
        path1 = tmp1.name
    print(f"Path 1: {path1}")
    spec = SQLSpec()
    config = AiosqliteConfig(database=path1)
    async with spec.provide_session(config) as session:
        await session.execute('CREATE TABLE test (id INTEGER)')
        print("Test 1: Created table")
        
    # Test 2 - FAILS with "table already exists" even though it's a different db
    with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as tmp2:
        path2 = tmp2.name  # Different path!
    print(f"Path 2: {path2}")
    spec2 = SQLSpec()
    config2 = AiosqliteConfig(database=path2)  # Different config!
    async with spec2.provide_session(config2) as session:
        await session.execute('CREATE TABLE test (id INTEGER)')  # ERROR!
        print("Test 2: Created table")

asyncio.run(test())

Output:

Path 1: /tmp/tmpXXXXXX.db
Test 1: Created table
Path 2: /tmp/tmpYYYYYY.db  # Different path!
sqlspec.exceptions.SQLSpecError: AIOSQLite database error: table test already exists

Expected Behavior

Each AiosqliteConfig with a different database path should get its own isolated pool/connections. Operations on path2 should not see tables created in path1.

Actual Behavior

The second test fails because it somehow uses the same database connection as the first test, even though:

  • The database paths are different
  • The SQLSpec instances are different
  • The AiosqliteConfig instances are different

Environment

  • Python 3.10+
  • sqlspec (from feat/performance branch)
  • aiosqlite

Investigation Areas

  1. Check if connection_instance is being shared via some global state
  2. Check if there's caching of pools by path that's not properly keyed
  3. Verify pool cleanup on context manager exit
  4. Check if asyncio event loop reuse affects pool state
  5. Compare with sync sqlite pool (which doesn't have this issue)

Impact

This bug prevents reliable use of aiosqlite adapter in tests or any scenario where multiple databases are used in sequence.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions