|
| 1 | +"""Pin: cycle 22's cancel-and-detach guard on |
| 2 | +``DqliteConnection._invalidate``. |
| 3 | +
|
| 4 | +A second ``_invalidate`` call while a prior bounded-drain task is |
| 5 | +in-flight must cancel the prior task before overwriting |
| 6 | +``self._pending_drain`` with the new one. Without the cancel, |
| 7 | +the first task is orphaned (still running on the loop, no longer |
| 8 | +reachable from ``self``), and ``close()`` awaits only the second |
| 9 | +— recreating the exact "Task was destroyed but it is pending" |
| 10 | +warning the drain mechanism was added to suppress. |
| 11 | +
|
| 12 | +Also pins the cycle 22 ``RuntimeError("Event loop is closed")`` |
| 13 | +guard around ``loop.create_task``: when the loop is dead the |
| 14 | +fallback sets ``_pending_drain = None`` and preserves the |
| 15 | +original cancel/cause instead of replacing it with a bare |
| 16 | +``RuntimeError``. |
| 17 | +
|
| 18 | +And pins the ``_invalidation_cause`` clear on ``_close_impl`` |
| 19 | +(cycle 22) so the cached exception does not pin frame |
| 20 | +globals/locals across close → reconnect cycles. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import asyncio |
| 26 | +import logging |
| 27 | + |
| 28 | +import pytest |
| 29 | + |
| 30 | +from dqliteclient.connection import DqliteConnection |
| 31 | + |
| 32 | + |
| 33 | +def _make_conn_with_protocol() -> DqliteConnection: |
| 34 | + """Build a DqliteConnection skeleton sufficient to drive |
| 35 | + ``_invalidate`` end-to-end without a real wire connection.""" |
| 36 | + conn = DqliteConnection.__new__(DqliteConnection) |
| 37 | + conn._protocol = None |
| 38 | + conn._db_id = None |
| 39 | + conn._pending_drain = None |
| 40 | + conn._invalidation_cause = None |
| 41 | + conn._in_use = False |
| 42 | + conn._in_transaction = False |
| 43 | + conn._tx_owner = None |
| 44 | + conn._savepoint_stack = [] |
| 45 | + conn._closed = False # type: ignore[attr-defined] |
| 46 | + conn._close_timeout = 0.05 |
| 47 | + conn._address = "test:9001" |
| 48 | + conn._bound_loop = None |
| 49 | + conn._pool_released = False |
| 50 | + return conn |
| 51 | + |
| 52 | + |
| 53 | +class _FakeProtocol: |
| 54 | + """Minimal stand-in for DqliteProtocol covering the slots |
| 55 | + ``_invalidate`` reads (``close()``, ``wait_closed()``).""" |
| 56 | + |
| 57 | + def __init__(self) -> None: |
| 58 | + self.close_calls = 0 |
| 59 | + |
| 60 | + def close(self) -> None: |
| 61 | + self.close_calls += 1 |
| 62 | + |
| 63 | + async def wait_closed(self) -> None: |
| 64 | + # Yield once so the bounded drain has a chance to be |
| 65 | + # observed in pending state by a sibling _invalidate. |
| 66 | + await asyncio.sleep(0.5) |
| 67 | + |
| 68 | + |
| 69 | +@pytest.mark.asyncio |
| 70 | +async def test_second_invalidate_cancels_prior_pending_drain() -> None: |
| 71 | + conn = _make_conn_with_protocol() |
| 72 | + |
| 73 | + # First invalidate: scheduling a bounded-drain task. |
| 74 | + conn._protocol = _FakeProtocol() # type: ignore[assignment] |
| 75 | + conn._invalidate() |
| 76 | + first_task = conn._pending_drain |
| 77 | + assert first_task is not None |
| 78 | + assert not first_task.done() |
| 79 | + |
| 80 | + # Re-set the protocol so the second _invalidate's |
| 81 | + # ``if self._protocol is not None:`` branch runs. |
| 82 | + conn._protocol = _FakeProtocol() # type: ignore[assignment] |
| 83 | + conn._invalidate() |
| 84 | + second_task = conn._pending_drain |
| 85 | + |
| 86 | + assert second_task is not None |
| 87 | + assert second_task is not first_task |
| 88 | + # The cycle 22 contract: prior task has cancel() scheduled |
| 89 | + # before the slot is overwritten. ``cancel()`` flips the task |
| 90 | + # to ``cancelling`` (not yet ``cancelled``) until the task |
| 91 | + # observes the CancelledError at its next await — pump the |
| 92 | + # loop so the cancellation lands. |
| 93 | + assert first_task.cancelling() > 0 or first_task.cancelled() or first_task.done() |
| 94 | + await asyncio.sleep(0) |
| 95 | + await asyncio.sleep(0) |
| 96 | + assert first_task.cancelled() or first_task.done() |
| 97 | + |
| 98 | + |
| 99 | +@pytest.mark.asyncio |
| 100 | +async def test_invalidate_with_closed_loop_preserves_cause( |
| 101 | + caplog: pytest.LogCaptureFixture, |
| 102 | +) -> None: |
| 103 | + """``loop.create_task`` raising |
| 104 | + ``RuntimeError("Event loop is closed")`` must NOT replace the |
| 105 | + original cancel/cause; cycle 22 added the try/except guard |
| 106 | + that DEBUG-logs and continues with ``_pending_drain = None``.""" |
| 107 | + conn = _make_conn_with_protocol() |
| 108 | + conn._protocol = _FakeProtocol() # type: ignore[assignment] |
| 109 | + |
| 110 | + # Patch the running loop's create_task to simulate the |
| 111 | + # closed-loop shape during dispose. |
| 112 | + loop = asyncio.get_running_loop() |
| 113 | + real_create_task = loop.create_task |
| 114 | + |
| 115 | + def _raise_loop_closed(coro: object, **kwargs: object) -> object: |
| 116 | + # Close the coroutine to suppress "never awaited" warnings. |
| 117 | + coro.close() # type: ignore[attr-defined] |
| 118 | + raise RuntimeError("Event loop is closed") |
| 119 | + |
| 120 | + loop.create_task = _raise_loop_closed # type: ignore[assignment] |
| 121 | + try: |
| 122 | + caplog.set_level(logging.DEBUG, logger="dqliteclient.connection") |
| 123 | + conn._invalidate(cause=ValueError("original cause")) |
| 124 | + finally: |
| 125 | + loop.create_task = real_create_task |
| 126 | + |
| 127 | + # ``_pending_drain`` falls back to None instead of leaking the |
| 128 | + # un-scheduled coroutine; the original cause is preserved on |
| 129 | + # ``_invalidation_cause`` for downstream chaining. |
| 130 | + assert conn._pending_drain is None |
| 131 | + assert isinstance(conn._invalidation_cause, ValueError) |
| 132 | + assert any("loop.create_task" in r.message for r in caplog.records) |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.asyncio |
| 136 | +async def test_close_impl_clears_invalidation_cause() -> None: |
| 137 | + """Cycle 22 added ``self._invalidation_cause = None`` on |
| 138 | + ``_close_impl`` so the cached exception does NOT pin |
| 139 | + frame globals/locals across close → reconnect cycles. A |
| 140 | + regression that drops the line re-introduces the |
| 141 | + traceback-pin defect.""" |
| 142 | + conn = _make_conn_with_protocol() |
| 143 | + # Simulate a prior invalidation having stored a cause. |
| 144 | + conn._invalidation_cause = ValueError("prior failure") |
| 145 | + assert conn._invalidation_cause is not None |
| 146 | + |
| 147 | + await conn._close_impl() |
| 148 | + |
| 149 | + assert conn._invalidation_cause is None |
0 commit comments