Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions jqueue/core/group_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ async def _submit[T](
"""
if self._stopped:
raise JQueueError("GroupCommitLoop is stopped")
if self._task is None or self._task.done():
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()
Expand All @@ -183,18 +185,29 @@ 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)
On exit (including cancellation) all unfinished ops are failed.
"""
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:
"""
Expand Down
51 changes: 51 additions & 0 deletions tests/test_group_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading