From ab1f2a0ca9bd90bb2ae18ad53641292e0875d292 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:29:54 +0000 Subject: [PATCH] Fail GroupCommitLoop ops instead of hanging when the writer is not running _submit() only rejected ops after stop(). Before start() (for example a BrokerQueue used without "async with"), or after the writer task died, the op was appended to _pending and its future was awaited forever. If the writer task was cancelled mid-batch, the in-flight batch and everything still pending also hung, because _commit_batch only catches Exception. - _submit raises JQueueError when the writer task was never started or has finished. - _writer_loop fails the in-flight batch and all pending ops with JQueueError when it exits for any reason. --- jqueue/core/group_commit.py | 35 +++++++++++++++++-------- tests/test_group_commit.py | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/jqueue/core/group_commit.py b/jqueue/core/group_commit.py index a9ed9ee..df8274b 100644 --- a/jqueue/core/group_commit.py +++ b/jqueue/core/group_commit.py @@ -174,6 +174,9 @@ async def _submit[T]( """ if self._stopped: raise JQueueError("GroupCommitLoop is stopped") + if self._task is None or self._task.done(): + # Nobody would ever resolve the future — fail instead of hanging. + raise JQueueError("GroupCommitLoop is not running; call start() first") future: asyncio.Future[T] = asyncio.get_running_loop().create_future() self._pending.append(_PendingOp(fn=fn, future=future, undo=undo)) self._wakeup.set() @@ -190,18 +193,30 @@ def _submit_undo[T]( self._wakeup.set() async def _writer_loop(self) -> None: - """Background coroutine — runs until stopped and all pending ops drain.""" - while not self._stopped or self._pending: - if not self._pending: - self._wakeup.clear() - await self._wakeup.wait() - - if not self._pending: - continue + """ + Background coroutine — runs until stopped and all pending ops drain. - batch = list(self._pending) + If the task dies (e.g. it is cancelled), every op still waiting — + in flight or pending — is failed so no caller hangs. + """ + batch: list[_PendingOp[Any]] = [] + try: + while not self._stopped or self._pending: + if not self._pending: + self._wakeup.clear() + await self._wakeup.wait() + + if not self._pending: + continue + + batch = list(self._pending) + self._pending.clear() + await self._commit_batch(batch) + batch = [] + finally: + orphaned = batch + self._pending self._pending.clear() - await self._commit_batch(batch) + _fail_batch(orphaned, JQueueError("GroupCommitLoop writer stopped")) async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None: """ diff --git a/tests/test_group_commit.py b/tests/test_group_commit.py index 3014138..4b16829 100644 --- a/tests/test_group_commit.py +++ b/tests/test_group_commit.py @@ -5,6 +5,7 @@ import pytest from jqueue.adapters.storage.memory import InMemoryStorage +from jqueue.core.broker import BrokerQueue from jqueue.core.group_commit import GroupCommitLoop from jqueue.domain.errors import CASConflictError, JobNotFoundError, JQueueError from jqueue.domain.models import JobStatus @@ -64,6 +65,56 @@ async def test_submit_after_stop_raises() -> None: await gcl.enqueue("task", b"data") +async def test_submit_before_start_raises_instead_of_hanging() -> None: + gcl = GroupCommitLoop(storage=InMemoryStorage()) + with pytest.raises(JQueueError, match="not running"): + await asyncio.wait_for(gcl.enqueue("task", b"data"), timeout=1) + assert gcl._pending == [] + + +async def test_broker_used_without_context_manager_raises() -> None: + q = BrokerQueue(InMemoryStorage()) + with pytest.raises(JQueueError, match="not running"): + await asyncio.wait_for(q.dequeue("task"), timeout=1) + + +async def test_submit_after_start_succeeds() -> None: + gcl = GroupCommitLoop(storage=InMemoryStorage()) + await gcl.start() + try: + job = await asyncio.wait_for(gcl.enqueue("task", b"data"), timeout=1) + assert (await gcl.read_state()).find(job.id) is not None + finally: + await gcl.stop() + + +async def test_writer_cancelled_fails_waiting_ops_and_rejects_new_ones() -> None: + gate = asyncio.Event() + + class _BlockingStorage(InMemoryStorage): + async def write(self, content: bytes, if_match: str | None = None) -> str: + await gate.wait() + return await super().write(content, if_match) + + gcl = GroupCommitLoop(storage=_BlockingStorage()) + await gcl.start() + in_flight = asyncio.create_task(gcl.enqueue("task", b"in-flight")) + await asyncio.sleep(0.01) # writer is now blocked in write() + queued = asyncio.create_task(gcl.enqueue("task", b"queued")) + await asyncio.sleep(0) + + assert gcl._task is not None + gcl._task.cancel() + with pytest.raises(asyncio.CancelledError): + await gcl._task + + for task in (in_flight, queued): + with pytest.raises(JQueueError, match="writer stopped"): + await asyncio.wait_for(task, timeout=1) + with pytest.raises(JQueueError, match="not running"): + await asyncio.wait_for(gcl.enqueue("task", b"late"), timeout=1) + + async def test_stop_drains_pending_ops() -> None: storage = InMemoryStorage() gcl = GroupCommitLoop(storage=storage)