|
| 1 | +"""Tests for protocol operation serialization. |
| 2 | +
|
| 3 | +The dqlite wire protocol is single-request-at-a-time per connection. |
| 4 | +Concurrent protocol operations must be serialized to prevent wire corruption. |
| 5 | +""" |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import threading |
| 9 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from dqlitedbapi.aio.connection import AsyncConnection |
| 14 | +from dqlitedbapi.connection import Connection |
| 15 | +from dqlitedbapi.cursor import Cursor |
| 16 | + |
| 17 | + |
| 18 | +class TestAsyncProtocolSerialization: |
| 19 | + """Test that concurrent async operations are serialized.""" |
| 20 | + |
| 21 | + @pytest.mark.asyncio |
| 22 | + async def test_concurrent_execute_is_serialized(self) -> None: |
| 23 | + """Two concurrent execute() calls must not overlap on the wire. |
| 24 | +
|
| 25 | + Without serialization, both coroutines would call query_sql/exec_sql |
| 26 | + concurrently, corrupting the TCP stream. With serialization, they |
| 27 | + must run one after the other. |
| 28 | + """ |
| 29 | + conn = AsyncConnection("localhost:9001") |
| 30 | + |
| 31 | + call_log: list[tuple[str, str]] = [] # (operation, phase) pairs |
| 32 | + |
| 33 | + async def mock_query_sql(db_id: int, sql: str, params: object) -> tuple: |
| 34 | + call_log.append((sql, "start")) |
| 35 | + await asyncio.sleep(0.05) # Simulate network I/O |
| 36 | + call_log.append((sql, "end")) |
| 37 | + return (["id"], [[1]]) |
| 38 | + |
| 39 | + async def mock_exec_sql(db_id: int, sql: str, params: object) -> tuple: |
| 40 | + call_log.append((sql, "start")) |
| 41 | + await asyncio.sleep(0.05) |
| 42 | + call_log.append((sql, "end")) |
| 43 | + return (0, 1) |
| 44 | + |
| 45 | + with patch("dqlitedbapi.aio.connection.DqliteConnection") as MockDqliteConn: |
| 46 | + mock_instance = AsyncMock() |
| 47 | + mock_instance.connect = AsyncMock() |
| 48 | + mock_instance._protocol = MagicMock() |
| 49 | + mock_instance._protocol.query_sql = mock_query_sql |
| 50 | + mock_instance._protocol.exec_sql = mock_exec_sql |
| 51 | + mock_instance._db_id = 0 |
| 52 | + MockDqliteConn.return_value = mock_instance |
| 53 | + |
| 54 | + await conn.connect() |
| 55 | + |
| 56 | + cursor1 = conn.cursor() |
| 57 | + cursor2 = conn.cursor() |
| 58 | + |
| 59 | + # Run two operations concurrently |
| 60 | + await asyncio.gather( |
| 61 | + cursor1.execute("SELECT 1"), |
| 62 | + cursor2.execute("INSERT INTO t VALUES (1)"), |
| 63 | + ) |
| 64 | + |
| 65 | + # With proper serialization, operations must not interleave. |
| 66 | + # The call_log should show: start/end of one op, then start/end of the other. |
| 67 | + # NOT: start/start/end/end (interleaved). |
| 68 | + assert len(call_log) == 4 |
| 69 | + # First operation must complete before second starts |
| 70 | + assert call_log[0][1] == "start" |
| 71 | + assert call_log[1][1] == "end" |
| 72 | + assert call_log[2][1] == "start" |
| 73 | + assert call_log[3][1] == "end" |
| 74 | + |
| 75 | + |
| 76 | +class TestSyncProtocolSerialization: |
| 77 | + """Test that concurrent sync operations are serialized.""" |
| 78 | + |
| 79 | + def test_concurrent_run_sync_is_serialized(self) -> None: |
| 80 | + """Two threads calling _run_sync must not overlap on the event loop. |
| 81 | +
|
| 82 | + Without serialization, both threads submit coroutines concurrently |
| 83 | + to the same event loop, where they interleave at await points. |
| 84 | + """ |
| 85 | + conn = Connection("localhost:9001", timeout=5.0) |
| 86 | + |
| 87 | + call_log: list[tuple[str, str]] = [] |
| 88 | + log_lock = threading.Lock() |
| 89 | + |
| 90 | + async def mock_query_sql(db_id: int, sql: str, params: object) -> tuple: |
| 91 | + with log_lock: |
| 92 | + call_log.append((sql, "start")) |
| 93 | + await asyncio.sleep(0.05) |
| 94 | + with log_lock: |
| 95 | + call_log.append((sql, "end")) |
| 96 | + return (["id"], [[1]]) |
| 97 | + |
| 98 | + async def mock_exec_sql(db_id: int, sql: str, params: object) -> tuple: |
| 99 | + with log_lock: |
| 100 | + call_log.append((sql, "start")) |
| 101 | + await asyncio.sleep(0.05) |
| 102 | + with log_lock: |
| 103 | + call_log.append((sql, "end")) |
| 104 | + return (0, 1) |
| 105 | + |
| 106 | + with patch("dqlitedbapi.connection.DqliteConnection") as MockDqliteConn: |
| 107 | + mock_instance = AsyncMock() |
| 108 | + mock_instance.connect = AsyncMock() |
| 109 | + mock_instance._protocol = MagicMock() |
| 110 | + mock_instance._protocol.query_sql = mock_query_sql |
| 111 | + mock_instance._protocol.exec_sql = mock_exec_sql |
| 112 | + mock_instance._db_id = 0 |
| 113 | + MockDqliteConn.return_value = mock_instance |
| 114 | + |
| 115 | + cursor1 = Cursor(conn) |
| 116 | + cursor2 = Cursor(conn) |
| 117 | + |
| 118 | + barrier = threading.Barrier(2) |
| 119 | + errors: list[Exception] = [] |
| 120 | + |
| 121 | + def thread_work(cursor: Cursor, sql: str) -> None: |
| 122 | + try: |
| 123 | + barrier.wait(timeout=5) |
| 124 | + cursor.execute(sql) |
| 125 | + except Exception as e: |
| 126 | + errors.append(e) |
| 127 | + |
| 128 | + t1 = threading.Thread(target=thread_work, args=(cursor1, "SELECT 1")) |
| 129 | + t2 = threading.Thread(target=thread_work, args=(cursor2, "INSERT INTO t VALUES (1)")) |
| 130 | + t1.start() |
| 131 | + t2.start() |
| 132 | + t1.join(timeout=10) |
| 133 | + t2.join(timeout=10) |
| 134 | + |
| 135 | + assert not errors, f"Threads raised errors: {errors}" |
| 136 | + |
| 137 | + # Operations must be serialized: one completes before the other starts |
| 138 | + assert len(call_log) == 4 |
| 139 | + assert call_log[0][1] == "start" |
| 140 | + assert call_log[1][1] == "end" |
| 141 | + assert call_log[2][1] == "start" |
| 142 | + assert call_log[3][1] == "end" |
| 143 | + |
| 144 | + conn.close() |
| 145 | + |
| 146 | + |
| 147 | +class TestSyncConnectionLazyInitRace: |
| 148 | + """Test that _get_async_connection doesn't create duplicate connections.""" |
| 149 | + |
| 150 | + def test_concurrent_first_use_creates_single_connection(self) -> None: |
| 151 | + """Two threads using a connection for the first time must not |
| 152 | + create two underlying DqliteConnection instances.""" |
| 153 | + conn = Connection("localhost:9001", timeout=5.0) |
| 154 | + |
| 155 | + connect_count = 0 |
| 156 | + count_lock = threading.Lock() |
| 157 | + |
| 158 | + async def slow_connect() -> None: |
| 159 | + nonlocal connect_count |
| 160 | + with count_lock: |
| 161 | + connect_count += 1 |
| 162 | + await asyncio.sleep(0.05) |
| 163 | + |
| 164 | + with patch("dqlitedbapi.connection.DqliteConnection") as MockDqliteConn: |
| 165 | + mock_instance = AsyncMock() |
| 166 | + mock_instance.connect = slow_connect |
| 167 | + mock_instance._protocol = MagicMock() |
| 168 | + mock_instance._protocol.query_sql = AsyncMock(return_value=(["id"], [[1]])) |
| 169 | + mock_instance._db_id = 0 |
| 170 | + MockDqliteConn.return_value = mock_instance |
| 171 | + |
| 172 | + barrier = threading.Barrier(2) |
| 173 | + errors: list[Exception] = [] |
| 174 | + |
| 175 | + def thread_work() -> None: |
| 176 | + try: |
| 177 | + barrier.wait(timeout=5) |
| 178 | + cursor = conn.cursor() |
| 179 | + cursor.execute("SELECT 1") |
| 180 | + except Exception as e: |
| 181 | + errors.append(e) |
| 182 | + |
| 183 | + t1 = threading.Thread(target=thread_work) |
| 184 | + t2 = threading.Thread(target=thread_work) |
| 185 | + t1.start() |
| 186 | + t2.start() |
| 187 | + t1.join(timeout=10) |
| 188 | + t2.join(timeout=10) |
| 189 | + |
| 190 | + assert not errors, f"Threads raised errors: {errors}" |
| 191 | + # Only one DqliteConnection should have been created |
| 192 | + assert MockDqliteConn.call_count == 1 |
| 193 | + assert connect_count == 1 |
| 194 | + |
| 195 | + conn.close() |
0 commit comments