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
27 changes: 25 additions & 2 deletions jqueue/core/direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from __future__ import annotations

import asyncio
import contextlib
import dataclasses
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
Expand Down Expand Up @@ -48,6 +49,10 @@ class DirectQueue:
storage: ObjectStoragePort
max_retries: int = 10

_cleanup: set[asyncio.Task[None]] = dataclasses.field(
default_factory=set, init=False, repr=False, compare=False
)

# ------------------------------------------------------------------ #
# Write operations #
# ------------------------------------------------------------------ #
Expand All @@ -73,10 +78,21 @@ async def dequeue(

Optionally filter by entrypoint. Returns the list of claimed jobs.
Returns an empty list if no jobs are available.

If cancelled mid-claim, the claimed jobs are released in the background.
"""
return await self._transaction(
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC))
claim = asyncio.ensure_future(
self._transaction(
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC))
)
)
try:
return await asyncio.shield(claim)
except asyncio.CancelledError:
task = asyncio.ensure_future(self._release_orphaned(claim))
self._cleanup.add(task)
task.add_done_callback(self._cleanup.discard)
raise

async def ack(self, job_id: str) -> None:
"""Mark a job as done and remove it from the queue."""
Expand Down Expand Up @@ -112,6 +128,13 @@ async def read_state(self) -> QueueState:
# Internal CAS loop #
# ------------------------------------------------------------------ #

async def _release_orphaned(self, claim: asyncio.Future[list[Job]]) -> None:
"""Best effort; the stale sweep is the fallback."""
with contextlib.suppress(Exception):
claimed = await claim
if claimed:
await self._transaction(lambda q: q.release_claims(claimed))

async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T:
"""
Read-modify-write with CAS retry loop.
Expand Down
34 changes: 31 additions & 3 deletions jqueue/core/group_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
------------------------------
If one mutation in a batch raises (e.g., JobNotFoundError), that future gets
the exception but the other mutations in the batch still commit normally.

Cancellation
------------
Ops cancelled before their batch is applied are dropped. A dequeue cancelled
after its claim committed has the claim released in the next batch.
"""

from __future__ import annotations
Expand All @@ -47,6 +52,7 @@ class _PendingOp[T]:

fn: Callable[[StateQueries], T]
future: asyncio.Future[T]
undo: Callable[[StateQueries, T], object] | None = None


@dataclasses.dataclass
Expand Down Expand Up @@ -121,7 +127,8 @@ async def dequeue(
) -> list[Job]:
"""Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS."""
return await self._submit(
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC))
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC)),
undo=lambda q, claimed: q.release_claims(claimed),
)

async def ack(self, job_id: str) -> None:
Expand All @@ -145,20 +152,35 @@ async def read_state(self) -> QueueState:
# Internal machinery #
# ------------------------------------------------------------------ #

async def _submit[T](self, fn: Callable[[StateQueries], T]) -> T:
async def _submit[T](
self,
fn: Callable[[StateQueries], T],
undo: Callable[[StateQueries, T], object] | None = None,
) -> T:
"""
Enqueue an operation and block until it is committed.

Appends the op to _pending, wakes the writer, then awaits the future
that resolves when the batch containing this op successfully commits.
If the caller is cancelled after commit, ``undo`` runs in a later batch.
"""
if self._stopped:
raise JQueueError("GroupCommitLoop is stopped")
future: asyncio.Future[T] = asyncio.get_running_loop().create_future()
self._pending.append(_PendingOp(fn=fn, future=future))
self._pending.append(_PendingOp(fn=fn, future=future, undo=undo))
self._wakeup.set()
return await future

def _submit_undo[T](
self, undo: Callable[[StateQueries, T], object], result: T
) -> None:
"""Queue an unawaited compensating op (allowed after stop())."""
future: asyncio.Future[object] = asyncio.get_running_loop().create_future()
# Retrieve failures so they aren't logged; the stale sweep is the fallback.
future.add_done_callback(lambda f: f.cancelled() or f.exception())
self._pending.append(_PendingOp(fn=lambda q: undo(q, result), future=future))
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:
Expand Down Expand Up @@ -193,6 +215,9 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None:
results: dict[int, Any] = {}
per_op_errors: dict[int, Exception] = {}
for i, op in enumerate(batch):
if op.future.done():
# Cancelled before apply: drop.
continue
try:
results[i] = op.fn(queries)
except Exception as exc:
Expand All @@ -203,6 +228,9 @@ async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None:

for i, op in enumerate(batch):
if op.future.done():
# Cancelled during the write: compensate.
if op.undo is not None and i in results:
self._submit_undo(op.undo, results[i])
continue
if i in per_op_errors:
op.future.set_exception(per_op_errors[i])
Expand Down
23 changes: 23 additions & 0 deletions jqueue/core/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,29 @@ def touch(self, job_id: str, now: datetime) -> Job:
self.state = self.state.with_job_replaced(updated)
return updated

def release_claims(self, claimed: list[Job]) -> list[Job]:
"""
Return jobs of an abandoned claim to QUEUED; returns those released.

Skips any job no longer IN_PROGRESS with the claim's heartbeat
(heartbeated, acked or re-claimed since). Never raises.
"""
state = self.state
released: list[Job] = []
for job in claimed:
current = state.find(job.id)
if (
current is None
or current.status != JobStatus.IN_PROGRESS
or current.heartbeat_at != job.heartbeat_at
):
continue
updated = current.with_status(JobStatus.QUEUED).with_heartbeat(None)
state = state.with_job_replaced(updated)
released.append(updated)
self.state = state
return released

def requeue_stale(self, cutoff: datetime) -> int:
"""
Return IN_PROGRESS jobs with a heartbeat older than ``cutoff`` to QUEUED.
Expand Down
91 changes: 91 additions & 0 deletions tests/test_direct_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,94 @@ async def test_empty_dequeue_does_not_conflict_with_concurrent_writer() -> None:

assert await queue.dequeue("task") == []
storage.write.assert_not_called()


# ---------------------------------------------------------------------------
# Cancelled dequeue does not orphan claimed jobs
# ---------------------------------------------------------------------------


class _GatedStorage(InMemoryStorage):
"""InMemoryStorage whose writes wait on ``gate`` once ``armed``."""

def __post_init__(self) -> None:
super().__post_init__()
self.armed = False
self.gate = asyncio.Event()
self.write_started = asyncio.Event()

async def write(self, content: bytes, if_match: str | None = None) -> str:
if self.armed:
self.write_started.set()
await self.gate.wait()
return await super().write(content, if_match)


async def _settle() -> None:
for _ in range(20):
await asyncio.sleep(0)


async def test_dequeue_cancelled_during_write_releases_claim() -> None:
storage = _GatedStorage()
queue = DirectQueue(storage)
job = await queue.enqueue("task", b"data")
storage.armed = True
task = asyncio.create_task(queue.dequeue("task"))
await storage.write_started.wait()

task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
storage.armed = False
storage.gate.set()
await _settle()

assert queue._cleanup == set()
stored = (await queue.read_state()).find(job.id)
assert stored is not None
assert stored.status == JobStatus.QUEUED
assert stored.heartbeat_at is None


async def test_uncancelled_dequeue_keeps_claim_direct() -> None:
storage = _GatedStorage()
queue = DirectQueue(storage)
job = await queue.enqueue("task", b"data")
storage.armed = True
task = asyncio.create_task(queue.dequeue("task"))
await storage.write_started.wait()
storage.armed = False
storage.gate.set()

[claimed] = await task
await _settle()

assert claimed.id == job.id
stored = (await queue.read_state()).find(job.id)
assert stored is not None
assert stored.status == JobStatus.IN_PROGRESS


async def test_cancelled_dequeue_with_failed_claim_leaves_state_alone() -> None:
storage = _GatedStorage()
queue = DirectQueue(storage, max_retries=1)
job = await queue.enqueue("task", b"data")
storage.armed = True
task = asyncio.create_task(queue.dequeue("task"))
await storage.write_started.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task

# A concurrent writer wins, so the gated claim hits a CAS conflict.
storage.armed = False
other = DirectQueue(storage)
await other.enqueue("task", b"other")
storage.gate.set()
await _settle()

assert queue._cleanup == set()
state = await queue.read_state()
assert state.in_progress_jobs() == ()
assert state.find(job.id) is not None
Loading
Loading